implementing a conditional into a function - php

Im trying to put a conditional into a function. this is the original code
function do_meta_box( $meta_field_def, $key = '' ) {
$content = '';
$esc_form_key = esc_attr( self::$form_prefix . $key );
$post = $this->get_metabox_post();
$meta_value = self::get_value( $key, $post->ID );
// other stuff
$content .= '<input type="text"' . $placeholder . ' id="' . $esc_form_key . '" ' . $ac . 'name="' . $esc_form_key . '" value="' . esc_attr( $meta_value ) . '" class="large-text' . $class . '"/><br />';
// other sutff
}
Now i'm trying to put a conditional where the value is.
$my_custom_title = get_the_title() . ' My Custom Stuff';
if ( $post->post_type == 'post' ) { echo esc_attr( $my_custom_title ); } else { echo esc_attr( $meta_value ); };
Exactly right here: value="' . esc_attr( $meta_value ) . '"
Thanks in advance.

You can assign it to a variable...
$value = $post->post_type == 'post' ? esc_attr( $post->title ) : esc_attr( $meta_value );
$content .= '<input type="text"' . $placeholder . ' id="' . $esc_form_key . '" ' . $ac . 'name="' . $esc_form_key . '" value="' . $value . '" class="large-text' . $class . '"/><br />';

Related

Get woocommerce categories thumbnails for each category on category pages

I have a problem. I use a filter with thumbnails. At least this filter does not include get category thumbnail and you have to upload all thumbnails manually into the filter which is not a good solution.
What I try to do is to get the thumbnail automatically from the category thumbnail. So far I have a code which adds a thumbnail from the current query which is also not a good solution. I need to get the thumbnail for each category separately.
This code works with current query and display the same image for all categories from the current opened category. Do you have any idea how could I get thumbnail for each category separately?
if ( is_product_category() ){
global $wp_query;
// get the query object
$cat = $wp_query->get_queried_object();
// get the thumbnail id using the queried category term_id
$thumbnail_id = get_term_meta( $cat->term_id, 'thumbnail_id', true );
// get the image URL
$image = wp_get_attachment_url( $thumbnail_id );
return '<span class="prdctfltr_customize_block prdctfltr_customize"><span class="prdctfltr_customize_image"><img src="' . $image . '" alt="' . $cat->name . '"/></span>' . ( $cnt !== false ? ' <span class="prdctfltr_customize_count">' . absint( $cnt ) . '</span>' : '' ) . ( $tip !== false ? '<span class="prdctfltr_tooltip"><span>' . wp_kses_post( $tip ) . '</span></span>' : '' ) . ( $checked !== '' ? '<input type="checkbox" value="' . esc_attr( $term_slug ) . '"' . esc_html( $checked ) . '/>' : '' ) . '<span class="prdctfltr_customization_search">' . esc_html( $term_name ) . '</span>' . wp_kses_post( $sublevel ) . '</span>';
}
Thank you in advance.
UPDATE
PHP CODE
Note: The following snippet has been fully tested on wordpress 5.8 and woocommerce 5.2 and it works for the default woocommerce product categories. If you're trying to use it in third party plugins, you may encounter some discrepancies. Therefore, feel free to customize it as you see fit!
If i understood you correctly, you need all of your product categories thumbnails.
You could get the all of your products categories by using get_terms. Then use a foreach loop to output your thumbnails. Like so:
$args = array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
);
$terms = get_terms($args);
foreach ($terms as $product_cat) {
$thumbnail_id = get_woocommerce_term_meta($product_cat->term_id, 'thumbnail_id', true);
$image = wp_get_attachment_url($thumbnail_id);
echo "<img src='" . $image . "'>";
}
This section is related to the plugin used in the question!
UPDATE
Like i said in the comments, the php file that you provided is one giant file with "4634" lines of "spaghetti" code with multiple references to other external files. However, on line 1957, there is a function that seems what we're interested in, and called "get_customized_term_700" and takes in $term_id, $term_slug, $term_name, $cnt, $checked and $sublevel.
In the same function, there is also a switch case statement. One of the case conditions checks for image. If there is a filter, it'll output the categories. So we'll use it to output the image.
So go ahead and REPLACE the entire function called "get_customized_term_700" on line 1957 with the following function.
Note:
This has not been tested, since i don't have access to the plugin, this has been purely written based on the logic in the php file. Hope it helps you!
public static function get_customized_term_700($term_id, $term_slug, $term_name, $cnt, $checked = '', $sublevel = '')
{
if (!empty($term_id)) {
$data = array(
'tooltip' => '',
'data' => '',
);
if (!empty(self::$filter['style']['terms'])) {
$key = self::__find_customized_term($term_id, self::$filter['style']['terms']);
if ($key !== false) {
$data = array_merge(array(
'tooltip' => '',
'data' => '',
), self::$filter['style']['terms'][$key]);
}
}
} else {
$data = array(
'value' => '',
'title' => self::__get_none_string(),
'tooltip' => self::__get_none_tooltip_string(),
'data' => self::__get_customized_term_none(self::$filter['style']['style']['type']),
);
}
if (!empty($data['title'])) {
$term_name = $data['title'];
}
$tip = empty($data['tooltip']) ? false : $data['tooltip'];
switch (self::$filter['style']['style']['type']) {
case 'text':
return '<span class="prdctfltr_customize_' . esc_attr(self::$filter['style']['style']['css']) . ' prdctfltr_customize"><span class="prdctfltr_customize_name">' . esc_html($term_name) . '</span>' . ($cnt !== false ? ' <span class="prdctfltr_customize_count">' . absint($cnt) . '</span>' : '') . ($tip !== false ? '<span class="prdctfltr_tooltip"><span>' . wp_kses_post($tip) . '</span></span>' : '') . ($checked !== '' ? '<input type="checkbox" value="' . esc_attr($term_slug) . '"' . esc_html($checked) . '/>' : '') . wp_kses_post($sublevel) . '</span>';
break;
case 'color':
if (!empty(self::$filter['style']['label']) && self::$filter['style']['label'] == 'side') {
return '<span class="prdctfltr_customize_block prdctfltr_customize"' . (!empty(self::$filter['style']['size']) ? sprintf(' style="line-height:%1$spx;', absint(self::$filter['style']['size'])) : '') . '><span class="prdctfltr_customize_color_text"><span style="background-color:' . Prdctfltr()->esc_color($data['data']) . ';' . (!empty(self::$filter['style']['size']) ? sprintf('width:%1$spx;height:%1$spx;', absint(self::$filter['style']['size'])) : '') . '"></span></span>' . ($tip !== false ? '<span class="prdctfltr_tooltip"><span>' . wp_kses_post($tip) . '</span></span>' : '') . ($checked !== '' ? '<input type="checkbox" value="' . esc_attr($term_slug) . '"' . esc_html($checked) . '/>' : '') . '<span class="prdctfltr_customization_search">' . esc_html($term_name) . '</span><span class="prdctfltr_customize_color_text_tip">' . esc_html($term_name) . '</span>' . ($cnt !== false ? ' <span class="prdctfltr_count">' . absint($cnt) . '</span>' : '') . wp_kses_post($sublevel) . '</span>';
} else {
return '<span class="prdctfltr_customize_block prdctfltr_customize"><span class="prdctfltr_customize_color" style="background-color:' . Prdctfltr()->esc_color($data['data']) . ';' . (!empty(self::$filter['style']['size']) ? sprintf('width:%1$spx;height:%1$spx;', absint(self::$filter['style']['size'])) : '') . '"></span>' . ($cnt !== false ? ' <span class="prdctfltr_customize_count">' . absint($cnt) . '</span>' : '') . ($tip !== false ? '<span class="prdctfltr_tooltip"><span>' . wp_kses_post($tip) . '</span></span>' : '') . ($checked !== '' ? '<input type="checkbox" value="' . esc_attr($term_slug) . '"' . esc_html($checked) . '/>' : '') . '<span class="prdctfltr_customization_search">' . esc_html($term_name) . '</span>' . wp_kses_post($sublevel) . '</span>';
}
break;
case 'image':
if (!empty(self::$filter['style']['label']) && self::$filter['style']['label'] == 'side') {
$args = array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
);
$output = '';
$terms = get_terms($args);
foreach ($terms as $product_cat) {
$thumbnail_id = get_woocommerce_term_meta($product_cat->term_id, 'thumbnail_id', true);
$image = wp_get_attachment_url($thumbnail_id);
$output .= '<span class="prdctfltr_customize_block prdctfltr_customize"' . (!empty(self::$filter['style']['size']) ? sprintf(' style="line-height:%1$spx;"', absint(self::$filter['style']['size'])) : '') . '><span class="prdctfltr_customize_image_text"><img src="' . $image . '"/></span>' . ($tip !== false ? '<span class="prdctfltr_tooltip"><span>' . wp_kses_post($tip) . '</span></span>' : '') . ($checked !== '' ? '<input type="checkbox" value="' . esc_attr($product_cat->slug) . '"' . esc_html($checked) . '/>' : '') . '<span class="prdctfltr_customization_search">' . esc_html($product_cat->name) . '</span><span class="prdctfltr_customize_image_text_tip">' . esc_html($product_cat->name) . '</span>' . ($cnt !== false ? ' <span class="prdctfltr_count">' . absint($cnt) . '</span>' : '') . wp_kses_post($sublevel) . '</span>';
}
return $output;
}
break;
case 'select':
return '<span class="prdctfltr_customize_select prdctfltr_customize">' . ($checked !== '' ? '<input type="checkbox" value="' . esc_attr($term_slug) . '"' . esc_html($checked) . '/>' : '') . '<span class="prdctfltr_customize_name">' . esc_html($term_name) . '</span>' . ($cnt !== false ? ' <span class="prdctfltr_customize_count">' . absint($cnt) . '</span>' : '') . wp_kses_post($sublevel) . '</span>' . ($tip !== false ? '<span class="prdctfltr_tooltip"><span>' . wp_kses_post($tip) . '</span></span>' : '');
break;
case 'html':
if (!empty($data['data'])) {
return wp_kses_post(stripslashes($data['data'])) . '<span class="prdctfltr_customization_search">' . esc_html($term_name) . '</span>' . ($tip !== false ? '<span class="prdctfltr_tooltip"><span>' . wp_kses_post($tip) . '</span>' . wp_kses_post($sublevel) . '</span>' : '');
} else {
return esc_html($term_name);
}
break;
default:
return '';
break;
}
}

How to add a new line in textarea element in php code?

I want to add a newline in a textarea. I tried with < p> tag but it's not working. Can you help me to insert a newline in a textarea? Please find the code above for a generic contact form. Where should I add tags for line breaks here?
public function cs_form_textarea_render($params = '') {
global $post, $pagenow;
extract($params);
if ( $pagenow == 'post.php' ) {
$cs_value = get_post_meta($post->ID, 'cs_' . $id, true);
} else {
$cs_value = $std;
}
if ( isset($cs_value) && $cs_value != '' ) {
$value = $cs_value;
} else {
$value = $std;
}
$cs_rand_id = time();
if ( isset($force_std) && $force_std == true ) {
$value = $std;
}
$html_id = ' id="cs_' . sanitize_html_class($id) . '"';
$html_name = ' name="cs_' . sanitize_html_class($id) . '"';
if ( isset($array) && $array == true ) {
$html_id = ' id="cs_' . sanitize_html_class($id) . $cs_rand_id . '"';
$html_name = ' name="cs_' . sanitize_html_class($id) . '_array[]"';
}
$cs_required = '';
if ( isset($required) && $required == 'yes' ) {
$cs_required = ' required="required"';
}
$cs_output = '<div class="' . $classes . '">';
$cs_output .= ' <textarea' . $cs_required . ' rows="5" cols="30"' . $html_id . $html_name . ' placeholder="' . $name . '">' . sanitize_text_field($value) . '</textarea>';
$cs_output .= $this->cs_form_description($description);
$cs_output .= '</div>';
if ( isset($return) && $return == true ) {
return force_balance_tags($cs_output);
} else {
echo force_balance_tags($cs_output);
}
}
Just add a "\n" char somewhere between your text area tags
$cs_output .= ' <textarea' . $cs_required . ' rows="5" cols="30"' . $html_id . $html_name . ' placeholder="' . $name . '">' . sanitize_text_field($value) . "\n" . "this text is on a new line". '</textarea>';
You will try to add "\n" before your end position of the tag. You need to concatenate Like ."\n".

Passing default arguments value in function not working

First of all, sorry for my lack of knowledge in PHP. I have tried googling for the answer, and also tried several answers here. For some reason passing argument in my function isn't working. However, if I directly call the default value in function, it works. Here is the function I am using.
function pnet_breadcrumbs( $seperator = '»', $home = true, $blog = true, $show_hierarchy = true ) {
global $post, $wp_query;
$html = '<div class="breadcrumbs" typeof="BreadcrumbList" vocab="http://schema.org/">';
$position = 1;
if ( $home ) {
$html .= '<span property="itemListElement" typeof="ListItem"><a property="item" typeof="WebPage" title="Go to ' . get_option( 'blogname' ) . '." href="' . home_url( '/' ) . '" class="home"><span property="name">' . get_option( 'blogname' ) . '</span></a><meta property="position" content="' . $position . '"></span>' . $seperator;
$html .= ' ' . $seperator . ' '; //Not Working
$html .= ' » '; //Working
$position = $position + 1;
}
if ( is_tax() || is_category() || is_tag() ) {
$obj = $wp_query->get_queried_object();
if ( $show_hierarchy ) {
$ancestors = get_ancestors( $obj->term_id, $obj->taxonomy, 'taxonomy' );
if ( is_array($ancestors) && !empty($ancestors) ) {
$ancestors = array_reverse( $ancestors );
foreach( $ancestors as $ancestor ) {
$term_obj = get_term($ancestor);
$term_url = get_term_link($term_obj->term_id);
$html .= '<span property="itemListElement" typeof="ListItem"><a property="item" typeof="WebPage" title="' . sprintf( __( 'View Archive for %s.', 'pnet' ), $term_obj->name ) . '." href="' . $term_url . '" class="home"><span property="name">' . $term_obj->name . '</span></a><meta property="position" content="' . $position . '"></span>';
$html .= $seperator;
$position++;
}
}
}
$html .= '<span property="itemListElement" typeof="ListItem"><span property="name">' . $obj->name . '</span><meta property="position" content="' . $position . '"></span>';
}
if ( is_search() ) {
$html .= '<span property="itemListElement" typeof="ListItem"><span property="name">' . sprintf( __( 'Search results for %s.', 'pnet' ), get_search_query() ) . '</span><meta property="position" content="' . $position . '"></span>';
}
$html .= '</div>';
echo $html;
}
add_action( 'wp_footer', 'pnet_breadcrumbs', 0 );
The variable $seperator is returning empty.
I know this is basic PHP, but I really can't figure out why I can't use a default value. What am I doing wrong?

Add specific attribute and values to input and label html tags in Woocommerce

I'm trying to add style, depending on whether the checkbox is clicked. This code is missing "id" and "for" for input and label (line 11). Logical decision to add generation of numbers. How to do it correctly?
foreach ($choices as $choice) {
$attr = '';
$key_val = explode("|", $choice);
/* It has to be two items ( Value => Label ), otherwise don't proceed */
if (count($key_val) == 2) {
if (in_array(trim($key_val[0]), $defaults)) {
$attr = 'checked';
}
/* For admin field, we don't need <li></li> wrapper */
$html .= (($_ptype != "wccaf") ? '<li>' : '') . '<input type="checkbox" data-has_field_rules="'.$has_field_rules.'" data-is_pricing_rules="'.$_is_pricing_rules.'" class="' . $_ptype . '-field ' . $_class . '" name="' . esc_attr($_meta["name"] . $_index) . '[]" value="' . esc_attr(trim($key_val[0])) . '" ' . $attr . ' ' . $_ptype . '-type="checkbox" ' . $_ptype . '-pattern="mandatory" ' . $_ptype . '-mandatory="' . $_meta["required"] . '" ' . $_readonly . ' /><label class="wcff-option-wrapper-label">' . esc_attr(trim($key_val[1])) . '</label>' . (($_ptype != "wccaf") ? '</li>' : '');
}
}
Updated
Try the following (untested), that will add a for attribute + value to the <label> and an id attribute + value to the <input>:
foreach ($choices as $choice) {
$attr = '';
$key_val = explode("|", $choice);
/* It has to be two items ( Value => Label ), otherwise don't proceed */
if (count($key_val) == 2) {
if (in_array(trim($key_val[0]), $defaults)) {
$attr = 'checked';
}
$sprintf = sprintf( '<input type="checkbox" %s %s %s %s %s %s %s /><label %s class="wcff-option-wrapper-label">%s</label>',
'id="' . esc_attr($_meta["name"] . $_index) . '"',
'data-has_field_rules="'.$has_field_rules.'"',
'data-is_pricing_rules="'.$_is_pricing_rules.'"',
'class="' . $_ptype . '-field ' . $_class . '"',
'name="' . esc_attr($_meta["name"] . $_index) . '[]"',
'value="' . esc_attr(trim($key_val[0])) . '"',
$attr . ' ' . $_ptype . '-type="checkbox" ' . $_ptype . '-pattern="mandatory' . $_meta["required"] . '" ' . $_readonly,
'for="' . esc_attr($_meta["name"] . $_index) . '"',
esc_attr(trim($key_val[1]) ) );
$html .= $_ptype != "wccaf" ? '<li>'.$sprintf.'</li>' : $sprintf;
}
}
I have embedded the code in a sprintf() function to make it more readable, functional and easy to tune.

How do I write a ternary operator for this line?

I can't figure out how to write a ternary operator for the ending of this line (i.e. "location" and "description"). I've defined the $location and $description variables but I'm getting an error that says unexpected $location variable.
Basically, for both location and description, I'm trying to say: If the field has been filled out, display the field. If not, don't print anything.
$content .= '<div data-order="' . $count . '" data-group="' . $group . '"><div class="img-wrap"><img data-iwidth="'.$isize[0].'" data-iheight="' . $isize[1] . '" class="myslide" data-lazy="' . get_template_directory_uri() . '/img/slides/' . strtolower($group) . '/' . $image_url . '" alt="' . get_sub_field('title') . '"><div class="slide-caption"><strong>' . get_sub_field('title') . '</strong><hr>' . get_sub_field('location') ? '<em>'$location'</em>' : ''; . get_sub_field('description') ? '<hr><span class="details">Details [+]</span><div class="details-display">'$description'</div>' : ''; . '</div></div></div>';
Here is the full context:
if( have_rows('slides', $frontpage_id) ):
while ( have_rows('slides', $frontpage_id) ) :
the_row();
$group = get_sub_field('group');
$count = 1;
$i = 0;
$nav .= '<ul id="nav_'.$group.'" style="display: none;">';
$content .= '<div class="image-data-container image-container-'. $group .'">';
while( have_rows('images') ) : the_row(); $count++;
$image_url = get_sub_field('image');
$location = get_sub_field('location');
$description = get_sub_field('description');
$isize = #getimagesize(get_template_directory_uri() . '/img/slides/' . strtolower($group) . '/' . $image_url);
$content .= '<div data-order="' . $count . '" data-group="' . $group . '"><div class="img-wrap"><img data-iwidth="'.$isize[0].'" data-iheight="' . $isize[1] . '" class="myslide" data-lazy="' . get_template_directory_uri() . '/img/slides/' . strtolower($group) . '/' . $image_url . '" alt="' . get_sub_field('title') . '"><div class="slide-caption"><strong>' . get_sub_field('title') . '</strong><hr>' . get_sub_field('location') ? '<em>'$location'</em>' : ''; . get_sub_field('description') ? '<hr><span class="details">Details [+]</span><div class="details-display">'$description'</div>' : ''; . '</div></div></div>';
$nav .= '<li >' . get_sub_field('title') . '</li>';
$i++;
endwhile;
$content .= '</div>';
$nav .= '</ul>';
endwhile;
endif;
?>
Other the fact that your $content variable is a formatting nightmare. The ternary operator syntax returns result based on the condition and it should be separated from your $content attribute
$someVariable = (get_sub_field('location')) ? '<em>'.$location.'</em>' : '';
Now use that some variable inside your $content variable instead
Here is your code with comments:
while( have_rows('images') ) : the_row(); $count++;
$image_url = get_sub_field('image');
// you have already defined the location variable here
// It also means and I am assuming they your get_sub_field is returning a string
// If you are receiving a boolean or null value than and than only than you can do your ternary condition call of
// get_sub_field('location') ? '<em>'$location'</em>' : ''
// and if you are receiving a string field then you will have to explicitly check the condition
// something like this (get_sub_field('location') === '') ? '<em>'$location'</em>' : ''
// I am not that familiar with wordpress framework or the ACF plugin but it looks like get_sub_field will return something so you actually wont need the ternary condition
$location = get_sub_field('location');
// Similar case with description
$description = get_sub_field('description');
$isize = #getimagesize(get_template_directory_uri() . '/img/slides/' . strtolower($group) . '/' . $image_url);
// After removing the ternary condition your content variable will look like this
$content .= '<div data-order="' . $count . '" data-group="' . $group . '"><div class="img-wrap"><img data-iwidth="'.$isize[0].'" data-iheight="' . $isize[1] . '" class="myslide" data-lazy="' . get_template_directory_uri() . '/img/slides/' . strtolower($group) . '/' . $image_url . '" alt="' . get_sub_field('title') . '"><div class="slide-caption"><strong>' . get_sub_field('title') . '</strong><hr>' . '<em>' . $location . '</em>' . '<hr><span class="details">Details [+]</span><div class="details-display">' . $description . '</div>' . '</div></div></div>';
$nav .= '<li >' . get_sub_field('title') . '</li>';
$i++;
endwhile;
You know you can always make it more readable
// You know instead of all the concatenation you can do this instead
$templateDirURI = get_template_directory_uri();
$groupLower = strtolower($group);
$title = get_sub_field('title');
$content .= "<div data-order='{$count}' data-group='{$group}'><div class='img-wrap'><img data-iwidth='{$isize[0]}' data-iheight='{$isize[1]}' class='myslide' data-lazy='{$templateDirURI}/img/slides/{$groupLower}/{$image_url}' alt='{$title}'><div class='slide-caption'><strong>{$title}</strong><hr><em>{$location}</em><hr><span class='details'>Details [+]</span><div class='details-display'>{$description}</div></div></div></div>";
Updated Code
$content .= "<div data-order='{$count}' data-group='{$group}'><div class='img-wrap'><img data-iwidth='{$isize[0]}' data-iheight='{$isize[1]}' class='myslide' data-lazy='{$templateDirURI}/img/slides/{$groupLower}/{$image_url}' alt='{$title}'><div class='slide-caption'><strong>{$title}</strong>";
// Assuming the user did not submit location information
if($location !== "")
$content .= "<hr><em>{$location}</em><hr>";
if($description !== "")
$content .= "<span class='details'>Details [+]</span><div class='details-display'>{$description}</div>";
$content .= "</div></div></div>";

Categories