Search code examples
phpwordpressloopswoocommercecustom-taxonomy

Add a divider between subcategories and products in WooCommerce loop


I need to add divider line or Elementor template between products and subcategories in main category WooCommerce.

I separated it but I cannot add divider

I used this code with Elementor template short code, but it was separated by white space

add_action( 'init', 'move_subcat_lis' );
function move_subcat_lis() {
    // Remove the subcat <li>s from the old location.
    remove_filter( 'woocommerce_product_loop_start', 'woocommerce_maybe_show_product_subcategories' );

    add_action( 'woocommerce_before_shop_loop', 'msc_product_loop_start', 40 );
    add_action( 'woocommerce_before_shop_loop', 'msc_maybe_show_product_subcategories', 50 );
    add_action( 'woocommerce_before_shop_loop', 'msc_product_loop_end', 60 );
}

/**
* Conditonally start the product loop with a <ul> contaner if subcats exist.
*/
function msc_product_loop_start() {
    $subcategories = woocommerce_maybe_show_product_subcategories();

    if ( $subcategories ) {
        woocommerce_product_loop_start();
    }
}

/**
* Print the subcat <li>s in our new location.
*/
function msc_maybe_show_product_subcategories() {
    echo woocommerce_maybe_show_product_subcategories();
}

/**
* Conditonally end the product loop with a </ul> if subcats exist.
*/
function msc_product_loop_end() {
    get_header();

    echo do_shortcode('[elementor-template id="2808"]'); 

    $subcategories = woocommerce_maybe_show_product_subcategories();

    if ( $subcategories ) {
        woocommerce_product_loop_end();
    }
}

Solution

  • Based on this Wordpress StackExchange answer, you can use the following simplified version:

    // Remove displayed subcategories from product loop
    remove_filter( 'woocommerce_product_loop_start', 'woocommerce_maybe_show_product_subcategories' );
    
    // Display subcategories before the product loop
    add_action( 'woocommerce_before_shop_loop', 'display_product_subcategories', 50 );
    
    function display_product_subcategories() {
        $categories = woocommerce_maybe_show_product_subcategories();
    
        if ( $categories ) {
            printf('<ul class="products categories columns-%d">%s</ul>',
                esc_attr( wc_get_loop_prop( 'columns' ) ), $categories );
    
            echo '<hr>'; // <== Divider 
        }
    }
    

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

    Now you can replace the <hr> separator from:

    echo '<hr>'; // <== Divider 
    

    with your shortcode, like:

    echo do_shortcode('[elementor-template id="2808"]');