首页 文章

自定义帖子类型中的WooCommerce产品

提问于
浏览
3

我正在尝试使用Woocommerce类别分类法在页面上显示相关产品 . 自定义帖子类型允许我将产品类别列表添加到自定义页面,但我不知道如何过滤它只显示我为相应页面选择的类别 . 目前它显示我的所有产品,而不是过滤我需要的产品:

$args = array( 'post_type' => 'product', 'posts_per_page' => -1, 'taxonomy' => 'product_cat' );

$loop = new WP_Query( $args );

while ( $loop->have_posts() ) : $loop->the_post();
    global $product; 
    echo '<div class="background-img"><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().'
'.get_the_title().'</a>'; echo $product->get_price_html(); echo '<form class="cart" method="post" enctype="multipart/form-data"> <input type="hidden" name="add-to-cart" value="'; echo esc_attr($product->id); echo '"> <button type="submit">'; echo $product->single_add_to_cart_text(); echo '</button> </form>'; echo '</div>'; endwhile; $attachment_ids = $product->get_gallery_attachment_ids(); foreach( $attachment_ids as $attachment_id ) { echo $image_link = wp_get_attachment_url( $attachment_id ); } wp_reset_query();

这是开发站点的一个版本,它仍然非常原始,需要很多样式,但应该给出一个想法:

http://betamarine.mainboard.com/engine/beta-14-z482/

我正在使用以下插件:

https://wordpress.org/plugins/custom-post-type-ui/

我可以创建一个自定义分类法,但这是一个额外的步骤,并产生相同的结果 . 我想我可能会遗漏一些小东西,但我只是没有得到它 .

2 回答

  • 1

    所以经过多次努力之后,这里是代码片段:

    <?php
    
       //retrieves the term variable from the admin page - replace "product_category" with the name of your post type
    $part_terms = get_the_terms( $post->ID, 'product_category' );
    if( $part_terms && !is_wp_error( $part_terms ) ) {
        foreach( $part_terms as $term ) {
        }
    }
    //create a variable to filter your Wordpress Loop
        $part_args = array( 
    		'post_type' => 'product', 
    		'hierarchical' => true,
    		'posts_per_page' => -1, 
    		'tax_query' => array(array(
    			'taxonomy' => 'product_category',
    			'field' => 'slug',
    			'terms' => array($term->slug),
    			'operator' => 'IN'
    			))
    	);
    
    							
        $loop = new WP_Query( $part_args );
    //the loop
        while ( $loop->have_posts() ) : $loop->the_post(); 
        global $product; 
    //some handy woocommerce coding
    	echo '<div class="background-img"><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().'
    '.get_the_title().'</a>'; echo $product->get_price_html(); echo '<form class="cart" method="post" enctype="multipart/form-data"> <input type="hidden" name="add-to-cart" value="'; echo esc_attr($product->id); echo '"> <button type="submit">'; echo $product->single_add_to_cart_text(); echo '</button> </form>'; echo '</div>'; endwhile; ?>

    感谢JayDeep让我走上正轨!

  • 3

    您需要使用tax_query按使用过滤器进行过滤 .

    检查此链接:https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

相关问题