如何在 post 上使用短代码调用 post 对象(产品)自定义字段

How do I call post objects (products) custom fields using shortcodes on posts

我正在尝试在博客 post 上显示 'featured products'。这些特色产品将通过每个 post.

后端的自定义字段 post 对象进行选择

我已经写下了我认为 PHP 应该是什么 - 我哪里错了?当我尝试使用简码时,没有出现任何代码(但简码文本未显示,所以肯定是添加了)。谢谢:)

    <?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;
}

您已经在 $html 变量中构建了 HTML,但是您没有对它做任何事情。短代码不会自动知道您要显示 $html 变量,因此您需要在函数结束之前 return (或 echo)它:

add_shortcode('featuredproducts' , 'printfeaturedprod');

function printfeaturedprod(){        
    $html = '';

    /* your code here... */

    return $html;
}

参考:见add_shortcode WP documentation