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

我正在尝试在博客文章中展示“特色产品”。这些特色产品将通过每个帖子后端的自定义字段帖子对象进行选择。


我已经写下了我认为 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;

}


翻翻过去那场雪
浏览 41回答 1
1回答

Helenr

您已在变量中构建了 HTML $html,但您没有对其执行任何操作。短代码不会自动知道您想要显示 $html 变量,因此您需要在函数完成之前在末尾添加return( 或) 它:echoadd_shortcode('featuredproducts' , 'printfeaturedprod');function printfeaturedprod(){            $html = '';    /* your code here... */    return $html;}
打开App,查看更多内容
随时随地看视频慕课网APP