【问题标题】:Get Woocommerce products by custom taxonomy term values in a WP_Query通过 WP_Query 中的自定义分类术语值获取 Woocommerce 产品
【发布时间】:2018-09-27 16:41:39
【问题描述】:

我正在开发一个插件,该插件将放置在我的 woocommerce 产品侧边栏中。 我需要它,给定产品 ID/对象,它会找到 2 个具有我之前创建的自定义分类的产品。

通过这段代码,我得到了我的产品中使用的术语列表,其中“collane”是自定义分类法

get_the_term_list( $product->id, 'collane', '<div style="direction:rtl;">', '</div>', '' ); 

问题是我不知道如何获取自定义分类 id,以及如何通过我的自定义分类对其进行过滤。

我已经使用 WP_Query 用此代码查找同一类别的产品:

$args = array(
'post_type'             => 'product',
'post_status'           => 'publish',
'ignore_sticky_posts'   => 1,
'posts_per_page'        => $atts['limit'],
'tax_query'             => array(
    array(
        'taxonomy'      => 'product_cat',
        'field' => 'term_id', //This is optional, as it defaults to 'term_id'
        'terms'         => $cat_id,
        'operator'      => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
    ),
    array(
        'taxonomy'      => 'product_visibility',
        'field'         => 'slug',
        'terms'         => 'exclude-from-catalog', // Possibly 'exclude-from-search' too
        'operator'      => 'NOT IN'
    )
)
);

如何更改我的代码以获得所需的分类 ID/对象,然后在我的 WP_Query 中使用它?

【问题讨论】:

    标签: php wordpress woocommerce product custom-taxonomy


    【解决方案1】:

    您应该尝试以下WP_Query$args,这将允许从同一个“collane”自定义分类中获得与当前产品具有相同术语的其他 2 个产品。

    我正在使用wp_get_post_terms() WordPress 函数从特定的自定义分类中获取帖子中的术语 ID(此处为“产品”自定义帖子类型)

    代码:

    $taxonomy = 'collane'; // The targeted custom taxonomy
    
    // Get the terms IDs for the current product related to 'collane' custom taxonomy
    $term_ids = wp_get_post_terms( get_the_id(), $taxonomy, array('fields' => 'ids') ); // array
    
    $query = new WP_Query( $args = array(
        'post_type'             => 'product',
        'post_status'           => 'publish',
        'ignore_sticky_posts'   => 1,
        'posts_per_page'        => 2, // Limit: two products
        'post__not_in'          => array( get_the_id() ), // Excluding current product
        'tax_query'             => array( array(
            'taxonomy'      => $taxonomy,
            'field'         => 'term_id', // can be 'term_id', 'slug' or 'name'
            'terms'         => $term_ids,
        ), ),
    );
    
    // Test count post output
    echo '<p>Posts count: ' . $query->post_count . '</p>';
    
    // The WP_Query loop
    if ( $query->have_posts() ): 
        while( $query->have_posts() ): 
            $query->the_post();
    
            // Test output
            echo '<p>' . $query->post->post_title . ' (' . $query->post->ID . ')</p>';
    
        endwhile;
        wp_reset_postdata();
    endif;
    

    【讨论】:

    • 谢谢,我正在测试它。现在我可以告诉您,在您的代码中,缺少一个括号并且代码无法运行。
    猜你喜欢
    • 2021-06-16
    • 2017-01-12
    • 2018-12-24
    • 2020-11-10
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    • 2020-11-02
    相关资源
    最近更新 更多