简体   繁体   中英

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.php into 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM