相关产品 WooCommerce 3.0+ 由帖子作者



我正在尝试显示与帖子作者相关的相关产品,因为我只想显示产品或由同一用户创建的产品

global $post;
$authorid = $post->post_author;
      foreach ( $related_products as $related_product ) :       
      $post_object = get_post( $related_product->$authorid );
      setup_postdata( $GLOBALS['post'] =& $post_object );
      wc_get_template_part( 'content', 'product' ); 
      endforeach; 

但是它没有显示任何内容

您可以执行类似操作,从相关产品数组中删除任何不是由产品作者创建的产品。 将此代码放在函数.php文件中。

add_filter('woocommerce_related_products', 'show_related_products_post_author', 10, 3 );
function show_related_products_post_author( $related_posts, $product_id, $filters ) {
    $author_id = get_post_field( 'post_author', $product_id );
    $query = new WC_Product_Query( array(
        'limit' => -1,
        'return' => 'ids',
    ) );
    $products = $query->get_products();
    foreach( $products as $loop_product_id ) {
        $product_author_id = get_post_field( 'post_author', $loop_product_id );
        if( $product_author_id !== $author_id ) {
            $key = array_search($loop_product_id, $related_posts);
            unset($related_posts[$key]);
        }
    }
    return $related_posts;
}

最新更新