繁体   English   中英

通过WP_Query中的自定义分类术语值获取Woocommerce产品

[英]Get Woocommerce products by custom taxonomy term values in a WP_Query

我正在开发一个插件,该插件将放置在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中使用它?

您应该尝试使用以下WP_Query $args ,它们将允许从相同的“ collane”自定义分类中获得另外两个产品,这些产品的条款与当前产品相同。

我正在使用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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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