I'm working on a shortcode to show my authors list on WordPress; I managed to make the social networks fields work, but I can't hide them, if the field is empty.
I imagine I need the if statement, but I can't seem to find a way to make it works.
Here is the code I am currently using:
function pippin_list_authors() {
$authors = get_users(array(
'orderby' => 'display_name',
'count_totals' => false,
'who' => 'authors',
'id' => ''
)
);
$list = '';
if($authors) :
$list .= '<div class="author-list">';
foreach($authors as $author) :
$list .= '<table>';
$archive_url = get_author_posts_url($author->ID);
$list .= '<tr>' . get_avatar($author->user_email, 100);
$list .= '<br><br><a class="author-list-name" href="'. $archive_url . '" title="' . __('Vedi tutti i post ', 'pippin') . $author->display_name . '">' . $author->display_name . '</a><br>';
$list.= '<br><br><div class="author-social"><i class="fa fa-facebook"><p style="font-size: 0; color: transparent;">'.A.'</p></i>';
$list .= '<i class="fa fa-twitter"><p style="font-size: 0; color: transparent;">'.A.'</p></i>';
$list .= '<p class="author-bio" style="max-height: 103px; overflow: hidden; ">' . get_user_meta($author->ID, 'description', true) . '</p>';
$list .= '<div class="author-archive" style="text-align: center;">' . __('Vedi tutti i post', 'pippin') . '</div>';
$list .= '</tr></table>';
endforeach;
$list .= '</div>';
endif;
return $list;
}
add_shortcode('authors', 'pippin_list_authors');
If you want to check if the variable $authors is empty use the empty() function.
Try this:
if(!empty($authors)) {
...
}
I would suggest you change your functions if possible.
Create function for every social link and other user metas like this:
$facebook_link = get_user_meta( $author->ID, 'facebook', true);
then call it in this way:
<?php if ($facebook_link !=='') { ?>
<p><i class="fa fa-facebook"></p>
<?php } ?>
If get_user_meta exist in DB, but isn't value, it still return no empty array so empty($our_meta) - will not help.
Bcz return array( [0] => string("") );
Empty string, but this empty value is in the array, so it will show
that the array is not empty.
Use get_user_meta($id, $key, true) it return '' and empty() will work as it should.
get_user_meta( $user_id, $key, $single );
$single(boolean) If set to true, the function will return the value of the meta field, if left false, then the value of the meta
field will be returned in an array. This parameter has no meaning if
the $key parameter has not been specified.
Default: false
- If $single = true
string/array - if the meta field exists.
'' - when the metafield does not exist.
If $single = false
an array of all metafield values - when the metafield exists.
array() - when the meta field does not exist.
Related
I am using ACF and CPT cooperatively. I created a shortcode to be placed in a text module in my theme. It works well. Yet, when I call ACF get_field(), it's not returning any value. I tried looking into this question and also this one, but neither works.
I double-checked ACF fields name. Also tried to change the input type from text to number but still no hope.
Development Environment
WordPress Version: 5.2.2 (Latest at the moment)
Theme/Child Theme Version: Divi 3.25.3
The shortcode I created:
<?php
add_shortcode('RESTAURANT_MENU', 'fetch_menu_products');
function fetch_menu_products($atts)
{
$atts = shortcode_atts(array(
'category_name' => ''
), $atts);
$category_name = $atts['category_name'];
$args = array(
'category_name' => $category_name,
'post_type' => 'menu',
'numberposts' => -1,
'post_status' => 'publish'
);
$output = '';
$menu_products = get_posts($args);
foreach ($menu_products as $menu_product) {
setup_postdata($menu_product);
$output .= '<section class="menu-item-wrapper">';
$output .= '<h3 class="menu-item__title">' . $menu_product->post_title . '</h3>';
$output .= '<div class="menu-item">';
$output .= '<div class="menu-item-description">';
$output .= '<p class="menu-item-description__text">' . $menu_product->post_content . '</p>';
$output .= '</div>';
$output .= '<ul class="menu-prices-list">';
if (get_field("regular_size_price") || get_field("large_size_price")) {
$output .= '<li class="menu-prices-list--item">R ' . get_field("regular_size_price", $menu_product->ID) . ' Currency</li>';
$output .= '<li class="menu-prices-list--item">L ' . get_field("large_size_price", $menu_product->ID) . ' Currency</li>';
}
if (get_field("price")) {
$output .= '<li class="menu-prices-list--item">' . get_field("price", $menu_product->ID) . ' Currency</li>';
}
$output .= '</ul>';
$output .= '</div>';
$output .= '</section>';
}
wp_reset_postdata();
return $output;
}
Can any help me find out why isn't it returning any value, please? Thank you.
Update: The ACF Location Rules
Try to use get_post_meta() instead of get_field(). As you are already using ACF then use this code to get value from post meta
get_post_meta($menu_product->ID, 'regular_size_price')[0]
For more help on get_post_meta() you can check this link
If my assumption is correct, your li elements are not being printed when you return the $output variable. That should be the case since you are using get_field function outside of theloop without passing post id in if statement.
Below is the corrected code:
if (get_field("regular_size_price", $menu_product->ID) || get_field("large_size_price", $menu_product->ID)) {
$output .= '<li class="menu-prices-list--item">R ' . get_field("regular_size_price", $menu_product->ID) . ' Currency</li>';
$output .= '<li class="menu-prices-list--item">L ' . get_field("large_size_price", $menu_product->ID) . ' Currency</li>';
}
I hope this helps.
EDIT: I've simplified my code considerably to see if I can actually get HTML to ouput, but no luck.
Here is the simplified version, removing all my custom HTML and only adding <div class="test"></div> to see if I can get my shortcode to output HTML, which it does not.
//custom shortcodes
function product_snippet( $atts ) {
// Attributes
$atts = shortcode_atts(
array(
'id' => '',
'snippet' => '',
),
$atts,
'product_snippet'
);
return $product = wc_get_product($atts['id']);
return $product_img = $product->get_image();
return $product_title = $product->get_title();
return $product_link = get_permalink($atts['id']);
return $children = $product->get_children();
return $children_array = array();
echo "<div class='test'></div>";
}
add_shortcode( 'product_snippet', 'product_snippet' );
This stops the site from crashing, but not HTML is outputted.
ORIGINAL POST:
I am trying to write a custom shortcode so that my client will be more easily able to edit their website. I've added the following code to my WordPress's functions.php file and I can't determine why it isn't working.
The idea is to input a grouped product's ID into the short code, and it will pull up the product's Title, Image, and all child products.
function product_snippet( $atts ) {
$a = shortcode_atts( array (
'id',
'snippet',
), $atts);
$product = wc_get_product($a['id']);
$product_img = $product->get_image();
$product_title = $product->get_title();
$product_link = get_permalink($a['id']);
$children = $product->get_children();
//initialize array so that child products can be sorted by price.
$children_array = array();
//Assign each child product to its price in array so that child products can be sorted by price in HTML.
foreach ($children as $key => $value) {
$children_array[$value] = wc_get_product($value)->get_price();
};
asort($children_array);
return '<div class="main_pro">
<div class="left-sd">' . do_shortcode('[product id="' . $a['id'] . '"]') . '</div>
<div class="right-sd">
<div class="info">
<h2>'. $product_title . '</h2>
<p>' . $a['snippet'] . ' More Info >></p>
</div>
<ul>
' . foreach ($children_array as $key => $value) {
$option = wc_get_product($key);
$option_title = $option->post->post_title;
. '
<li>
<div id="outer-bar">
<div class="bar-l">
' . $option_title;
if ($option->get_attribute('pa_pack-size')) {
strval(wc_get_product($key)->get_attribute('pa_pack-size'));
.'<br/>
<span class="small_pz">
' . "$" . strval(round(($option->get_price() / intval($option->get_attribute('pa_pack-size'))), 2)) . " per tray - SAVE $" . strval(round(($product->get_price() * $option->get_price() - $option->get_price()), 2)); . '
</span>
' . }
. '</div>
<div class="bar-r">' . do_shortcode('[add_to_cart id="' . $key . '"]'); . '</div>
</div>
</li>
' . }
. ' </ul>
</div>
</div>';
};
add_shortcode( 'product_snippet', 'product_snippet' );
Assume I have my opening and closing <?php ?> tags. I don't write in PHP a lot so I apologize if my code is janky. If I can get this closer to best practices (I don't think my concatenation looks right) I'm open to feedback.
There was a bunch of errors in the code. Try this.
function product_snippet($atts)
{
$a = shortcode_atts(array(
'id',
'snippet',
), $atts);
$product = wc_get_product($a['id']);
$product_img = $product->get_image();
$product_title = $product->get_title();
$product_link = get_permalink($a['id']);
$children = $product->get_children();
//initialize array so that child products can be sorted by price.
$children_array = array();
//Assign each child product to its price in array so that child products can be sorted by price in HTML.
foreach ($children as $key => $value) {
$children_array[$value] = wc_get_product($value)->get_price();
};
asort($children_array);
$string = '<div class="main_pro">
<div class="left-sd">' . do_shortcode('[product id="' . $a['id'] . '"]') . '</div>
<div class="right-sd">
<div class="info">
<h2>' . $product_title . '</h2>
<p>' . $a['snippet'] . ' More Info >></p>
</div>
<ul>';
foreach ($children_array as $key => $value) {
$option = wc_get_product($key);
$option_title = $option->post->post_title;
$string .= '
<li>
<div id="outer-bar">
<div class="bar-l">
' . $option_title;
if ($option->get_attribute('pa_pack-size')) {
strval(wc_get_product($key)->get_attribute('pa_pack-size'));
$string .= '<br/>
<span class="small_pz">
' . "$" . strval(round(($option->get_price() / intval($option->get_attribute('pa_pack-size'))), 2)) . " per tray - SAVE $" . strval(round(($product->get_price() * $option->get_price() - $option->get_price()), 2)) .
'</span>';
}
$string .= '</div>
<div class="bar-r">' . do_shortcode('[add_to_cart id="' . $key . '"]') . '</div>
</div>
</li>
';
}
$string .= ' </ul>
</div>
</div>';
return $string;
}
add_shortcode('product_snippet', 'product_snippet');
I have changed a little your code to make it work. This is just an example that you can complete. Try it and let me know:
//custom shortcodes
if( !function_exists('product_snippet') ) {
function product_snippet( $atts ) {
// Attributes
extract( shortcode_atts(
array(
'id' => '', // You will use $id to get the value of this attribute
'snippet' => '' // You will use $snippet to get the value of this attribute
),
$atts
));
// Get an instance of the product object
$product = wc_get_product( $id );
// Displays go here
return '<div class="test">'.$product->get_image().''.$product->get_title().'</div>';
}
add_shortcode( 'product_snippet', 'product_snippet' );
}
You should get an html output this time …
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
I have a function in my wordpress theme:
function ajax_get_videoposts () {
$args = array(
'numberposts' => 5,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters' => true
);
//get 5 posts which are published
$recent_posts = wp_get_recent_posts($args);
$append .= '<div id="recommended-videos" class="recommended-videos rec-vid rec-vid2">';
$append .= '<div class="rec-title">Check These Out Next:</div>';
$append .= '<div class="rec-videos">';
foreach ($recent_posts as $recent) {
$thumb_id = get_post_thumbnail_id($recent['ID']);
$url = wp_get_attachment_url($thumb_id);
$append .= '<div class="videos">';
//a hrefs
$append .= '<a href="' . get_permalink($recent["ID"]) . '">';
$append .= '<div class="videoinfo">' . (__($recent["post_title"])) . '</div>' . '</a>';
//img tag
$append .= '<img align="top"' . 'src="' . $url . '"' . 'alt="' . (__($recent["post_title"])) . '">';
//looping 6 times
$append .= '</div>';
}
$append .= '<div class="rec-btns">';
$append .= print_r(get_permalink());
echo $append;
}
add_action( 'wp_ajax_ajax_get_videoposts', 'ajax_get_videoposts' ); // If called from admin panel
add_action( 'wp_ajax_nopriv_ajax_get_videoposts', 'ajax_get_videoposts' ); // If called from front end
Then I call this function i call this function via AJAX. The problem is
$append .= print_r(get_permalink());
Printing me the number '1' instead of the post URL because it is used in the functions.php instead of for example single.php how would i get the post URL inside functions.php?
Why using print_r ?
Isn't
$append = get_permalink();
what you really want?
Just in case, if you want to store print_r inside a variable, then you must pass TRUE as a second parameter. That will give us :
$append = print_r(get_permalink(),TRUE);
I wouldn't expect get_permalink() to return anything useful, given that you're calling this function via Ajax, and from what can be seen of your code a loop isn't in play. It's not clear from looking at this code which page or post you were hoping get_permalink() would be referring to; perhaps sharing your reason for doing this will help in providing a better answer.
Also, the '1' output you see is because of how print_r works:
When the return parameter is TRUE, this function will return a string. Otherwise, the return value is TRUE.
Your $append .= print_r(get_permalink()); effectively resolves to $append .= TRUE; (which in being string-concatenated will be cast to the string representation '1').
I have this php code used for a milestone wordpress shortcode :
function rocknrolla_milestone_box_shortcode( $atts, $content = null ){
extract( shortcode_atts(array(
"count" => '90%',
"title" => ''
), $atts) );
echo htmlentities($count);
$rnr_milestone_box = '<div class="milestone-counter" data-perc="'. $count .'">';
$rnr_milestone_box .= '<span class="milestone-count highlight">'. $count .'</span>';
$rnr_milestone_box .= '<h6 class="milestone-details">'. $title .'</h6>';
$rnr_milestone_box .= '</div>';
return $rnr_milestone_box;
}
add_shortcode('milestone_box', 'rocknrolla_milestone_box_shortcode');
Now, when I add on "data-perc" attribute 99% for example this is displaying a weird text like:
<span class="milestone-count highlight">NaN</span>
If I add just the number like 99 the output is correct:
<span class="milestone-count highlight">99</span>
How can I append the % sign after the count variable here:
$rnr_milestone_box .= '<span class="milestone-count highlight">'. $count .'</span>';
?
Thanks!
Try this optimal option:
<?php
$count = "99%";
echo htmlentities($count);
// output: 99%
?>
Thanks.
I have a shortcode for a CSS accordion. One of the attributes is $open for the checkbox's "checked" value. Right now, if they type open=checked, it will pass checked="checked" and that div will be visible by default. Is there anyway to replace a custom value with the actual html value? For instance, I want the user to be able to use "open=yes" and have it pass "checked=checked" in the HTML.
// TOGGLE BOXES
function sc_tog_boxes( $attr, $content = null ) {
return '<ul class="togboxes">' . $content . '</ul>';
}
add_shortcode('togboxes', 'sc_tog_boxes');
function sc_tog_box( $atts , $content = null ) {
// Attributes
extract( shortcode_atts(
array(
'number' => '1',
'heading' => 'you forgot the heading tag: heading="your heading"',
'open' => '',
), $atts )
);
// Code
return '<li><label for="' . $number . '">' . $heading . ' <span class="toggle-icon">[+/-]</span></label><input type="checkbox" name="a" id="' . $number . '" checked="' . $open . '"><div class="togbox">' . do_shortcode($content) . '</div></li>';
}
add_shortcode( 'togbox', 'sc_tog_box' );
UPDATE: Okay, I need to rephrase this because the presence of the "checked" attribute means "checked" without any parameter anyway. So I need to be able to add "checked" in the html if they just type "open" in the shortcode, but have no checked attribute if they don't type open.
Found the answer:
if($open === 'yes'){
$open = 'checked';
}
else {
$open = '';
}