Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
987 views
in Technique[技术] by (71.8m points)

php - Exclude related products ids in Woocommerce

function woocommerce_output_related_products() {

    $args = array(
        'posts_per_page' => 4,
        'columns'        => 4,
        'orderby'        => 'rand', // @codingStandardsIgnoreLine.
        'post__not_in' => array(502,281)
    );

    woocommerce_related_products( apply_filters( 'woocommerce_output_related_products_args', $args ) );
}

I copied this function from includes/wc-template-functions.phpinto my theme's functions.php

To verify that my changes would work I changed the posts_per_page to 3 and it queried only 3 instead of 4.

I need to exclude a few products, but post__not_in is not working.

Am I doing something wrong? How else can I exclude products using this function?

I'm outputting the products with this function: woocommerce_output_related_products();

such an obnoxious problem. I simply cannot exclude products from here. can anyone help?

I tried this too:

add_filter( 'woocommerce_output_related_products_args', function( $args ) { 
    $args = wp_parse_args( array(  "post__not_in" => array('502','281') ), $args );
    return $args;
});

i did print_r($args) and it showed that my "post__not_in" was being added, but the products are still there. I have the right ID.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the woocommerce_related_products filter hook instead, this way:

add_filter( 'woocommerce_related_products', 'exclude_related_products', 10, 3 );
function exclude_related_products( $related_posts, $product_id, $args ){
    // HERE set your product IDs to exclude
    $exclude_ids = array('502','281');

    return array_diff( $related_posts, $exclude_ids );
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...