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
2
Answers
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 usingget_field
function outside of theloop without passing post id in if statement.Below is the corrected code:
I hope this helps.
Try to use
get_post_meta()
instead ofget_field()
. As you are already usingACF
then use this code to get value from post metaget_post_meta($menu_product->ID, 'regular_size_price')[0]
For more help on
get_post_meta()
you can check this link