【问题标题】:How to get all products from current WooCommerce product category?如何从当前 WooCommerce 产品类别中获取所有产品?
【发布时间】:2020-08-08 12:48:49
【问题描述】:

自定义我的archive-product.php。如何在自定义循环中仅显示特定类别中的产品? This similar question,没有解决我的问题。我尝试single_cat_title() 根据this 问题获取当前类别,但出现错误。我想我需要基于此documentation 使用get_queried_object(),但我不断收到错误。

我试过了:

<?php 
$category = single_cat_title('', false); // this returns your current category ?>

<?php
// Setup your custom query
$args = array( 
    'post_type' => 'product', 
    'product_cat' => $category,
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>

    <?php the_post_thumbnail(); ?>
        <br>
<?php endwhile; wp_reset_query(); // Remember to reset ?>

我也试过了:

`$term_name = get_queried_object()->name;`
    // Setup your custom query
    $args = array( 
        'post_type' => 'product', 
        'product_cat' => $term_name, );

【问题讨论】:

    标签: php wordpress loops woocommerce taxonomy-terms


    【解决方案1】:

    更新

    在产品类别存档页面上,获取您将使用的当前产品类别术语:

    自 WordPress 3.1 起,不推荐在 WP_Query 中直接使用分类参数。相反,您将使用 税务查询,如下所示:

    <?php
    // Get The queried object ( a WP_Term or a WP_Post Object)
    $term = get_queried_object();
    
    // To be sure that is a WP_Term Object to avoid errors
    if( is_a($term, 'WP_Term') ) :
    
    // Setup your custom query
    $loop = new WP_Query( array(
        'post_type'      => 'product',
        'posts_per_page' => -1,
        'post_status'    => 'publish',
        'tax_query'      => array( array(
            'taxonomy' => 'product_cat', // The taxonomy name
            'field'    => 'term_id', // Type of field ('term_id', 'slug', 'name' or 'term_taxonomy_id')
            'terms'    => $term->term_id, // can be an integer, a string or an array
        ) ),
    ) );
    
    if ( $loop->have_posts() ) :
    while ( $loop->have_posts() ) : $loop->the_post();
    echo '<div style="margin:8px; text-align:center;">
        <a href="'.get_the_permalink().'">';
    the_post_thumbnail();
    the_title();
    echo '</a></div>';
    endwhile;
    wp_reset_postdata(); // Remember to reset
    endif; endif;
    ?>
    

    经过测试并且有效。

    文档:WP_Query and Taxonomy Parameters

    【讨论】:

    • 谢谢。我添加了您的代码,但我现在收到“您的网站出现严重错误”?
    • 是否可以将the_post_thumbnail ( 'thumbnail' ); 仅包含在 the_permalink 中?我无法通过 echo `'' 将缩略图缩小为“缩略图”; the_post_thumbnail();回声'';
    • @newbieneedshelp 把echo '&lt;/a&gt;&lt;/div&gt;';移到the_title();之前
    • 我试过这个,但它不会将图像显示为“缩略图”,而是图像变得特别大。这仅在包含在永久链接中时才会发生。这是我尝试过的:echo '&lt;div style="margin:8px; text-align:center;"&gt; &lt;a href="'.get_the_permalink().'"&gt;'; the_post_thumbnail( 'thumbnail'); echo '&lt;/a&gt;&lt;/div&gt;';
    • 你试过了吗:&lt;a href="'.get_the_permalink().'"&gt;'; the_post_thumbnail('thumbnail'); echo '&lt;/a&gt;'; the_title(); echo '&lt;/div&gt;';
    猜你喜欢
    • 1970-01-01
    • 2020-08-21
    • 2019-09-03
    • 2019-01-08
    • 2017-04-01
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    相关资源
    最近更新 更多