Search code examples
phpwordpresswoocommercehook-woocommerceshortcode

Display related products using a shortcode on WooCommerce My account Dashboard


I'm trying to display related products in My account Dashboard page. I followed this WooCommerce Shortcodes documentation.

I tried to use the following code:

add_action( 'woocommerce_account_content', 'output_shortcode_on_child_pages');
function output_shortcode_on_child_pages() {
    $post = get_post();
    
    if ( is_page() AND $post->post_parent ) {
        echo do_shortcode( '[related_products limit=”3″]' );
    }
}

This does not display the related products. But when I try to display products in specific category like following, it works:

add_action( 'woocommerce_account_content', 'output_shortcode_on_child_pages');
function output_shortcode_on_child_pages() {
    $post = get_post();
    
    if ( is_page() AND $post->post_parent ) {
        echo do_shortcode( '[products limit="3" columns="3" orderby="rand" category=”presets-and-actions” ]' );
    }  
}

Kindly any help to resolve this?


Solution

  • Note that related products shortcode need to be used on single product pages, as related products are always linked to a product, that's why [related_products limit="3"] shortcode doesn't work on My account dashboard.

    Now to target my account dashboard, replace in your function this code lines:

    $post = get_post();
    
    if ( is_page() AND $post->post_parent ) {
    

    by this unique code line:

    if ( is_account_page() && ! is_wc_endpoint_url() ) {
    

    It's much better. See WooCommerce Conditional Tags