I’m trying to show ‘featured products’ on blog posts. These featured products are to be selected with custom fields post objects on the back end for each post.
I have written up what I think the PHP should be – where am I going wrong? When I try to use the shortcode no code appears (but the shortcode text doesn’t show so it’s definitely added). Thanks 🙂
    <?php
add_shortcode('featuredproducts' , 'printfeaturedprod');
function printfeaturedprod(){
    
    $html = '';
$instruments = get_field('featuredprod');
if( $instruments ):
    
    $html .=   '<div class="featuredproducts">';
    $html .=   '<h2 style="font-size:18px; font-family:poppins;">Featured in this video</h2>';
    
    foreach( $instruments as $instruments ): 
        $permalink = get_permalink( $instruments->ID );
        $title = get_the_title( $instruments->ID );
        $product = wc_get_product( $instruments->ID );
        $price = $product->get_price();
        $featured_img_url = get_the_post_thumbnail_url($instruments->ID, 'full');
        
        $html .=   '<div class="featuredproduct">';
        $html .=   '<img class="featuredproductimg" src="' . $featured_img_url . '">';
        $html .=   '<div class="proddetails">';
        $html .=   '<a class="producttitle" href="' . $permalink . '"><?php echo esc_html( $title ); ?></a>';
        $html .=   '<br><span class="productprice">ÂŁ' . $price . '</span>';
        $html .=   '</div>';
        $html .=   '</div>';
    
    endforeach;
        
    $html .=   '</div>';
    endif;
}
Advertisement
Answer
You have built your HTML in the $html variable but then you don’t do anything with it. The shortcode doesn’t automatically know that you want to display the $html variable so you need to return ( or echo) it at the end before the function finishes:
add_shortcode('featuredproducts' , 'printfeaturedprod');
function printfeaturedprod(){        
    $html = '';
    /* your code here... */
    return $html;
}
Reference: See the add_shortcode WP documentation