简体   繁体   中英

Get full products single pages for a product category on a single post in WooCommerce

I am looking for a code to show full product informations (title of the product, buy button, image gallery, description and so on) for all products of a specific product category of my choice on one single post.

There is not actually any shortcode for this and I don't have the skills to write something by myself.

Maybe someone has a solution for this?

Here is a custom shortcode That is using the existing [product_page] woocommerce shortcode in a loop, to output all single product pages for a defined product category (one after the other).

This custom shortcode has 2 arguments:

  • cat for the product category (slug)
  • limit for the number of posts to be displayed (default is all)

The code:

if( !function_exists('single_product_pages_by_category') ) {

    // Add Shortcode
    function single_product_pages_by_category( $atts ) {

        // Attributes
        $atts = shortcode_atts(
            array(
                'cat' => '',
                'limit'   =>'-1'
            ),
            $atts, 'product_pages_cat'
        );

        $posts = get_posts( array(
            'post_type'      => 'product',
            'post_status'    => 'publish',
            'posts_per_page' => $atts['limit'],
            'tax_query'      => array( array(
                'taxonomy'   => 'product_cat',
                'field'      => 'slug',
                'terms'      => $atts['cat'],
            ) )
        ) );

        $output = '<div class="products-in-'.$atts['cat'].'">'; // DIV container html tag (opening)

        // Iterating though each product in the defined category
        foreach( $posts as $post ){
            $post_id = $post->ID; // The Product ID
            // Using WooCommerce [product_page] existing shortcode in the loop
            $output .= '<div class="product-'.$post_id.'">' . do_shortcode ( "[product_page id=$post_id]" ) . '</div>';
        }

        $output .= '</div>'; // DIV container html tag (closing)

        // Always return the output (never echo)
        return $output;
    }

    add_shortcode( 'product_pages_cat', 'single_product_pages_by_category' );
}

Code goes in function.php file of your active child theme (active theme or in any plugin file).

Tested and Works in WooCommerce 3+


USAGE (example for 'posters' product category slug):

[product_pages_cat cat="posters"]

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