Related Products Woocommerce 3.0+ By Post Author

2019-08-29 15:16发布

问题:

I am trying to display the related product which is related to the post author since I only want to show products or the product that was created by the same user

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; 

however it doesn't show anything

回答1:

You could do something like this which will remove any products not created by the product's author from the related products array. Place this code in your functions.php file.

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