Products dropdown from same category inside Woocommerce product short description

前端 未结 2 829
醉酒成梦
醉酒成梦 2021-01-23 17:37

In Woocommerce, I would like to add a drop down in product short description that shows all products that have the same category(ies). It will be even better if it was possible

2条回答
  •  迷失自我
    2021-01-23 17:56

    2020 Update 4 - Added product_id as argument, allowing the shortcode to be used for a defined product ID (for example on a page).

    The following will make a custom shortcode that you can use in your product short description (or even in the product description) and will display a dropdown from same product category than the current product.

    The code:

    add_shortcode( 'products_dropdown', 'wc_products_from_cat_dropdown' );
    function wc_products_from_cat_dropdown( $atts ) {
            // Shortcode Attributes
            $atts = shortcode_atts( array(
                'product_id' => '', 
            ), $atts, 'products_dropdown' );
            
        $product_id = is_product() ? get_the_id() : $atts['product_id'];
        
        if ( empty($product_id) )
            return;
    
        ob_start();
    
        $query = new WP_Query( array(
            'post_type'      => 'product',
            'post_status'    => 'publish',
            'posts_per_page' => '-1',
            'post__not_in'     => array( $product_id ),
            'tax_query' => array( array(
                    'taxonomy' => 'product_cat',
                    'field'    => 'ids',
                    'terms'    => wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'ids' ) ) ,
            ) ),
        ) );
    
        if ( $query->have_posts() ) :
    
        echo '
    '; wp_reset_postdata(); endif; ?>

    Code goes in functions.php file of your active child theme (or active theme). Tested and works.


    USAGE

    1). For single product pages: Just paste the following shortcode in the product short description (or descrition):

    [products_dropdown]
    

    2). For single product pages, inside php code:

    echo do_shortcode("[products_dropdown]");
    

    3). on any post or page within the text editor, define the product_id argument (below the defined product id is **37**):

    [products_dropdown product_id="37"]
    

提交回复
热议问题