Search code examples
phpwordpresswoocommercehook-woocommerce

add_action with "woocommerce_account_dashboard" hook is misplaced


I installed a very simple plugin recently that shows the user avatar in the woocommerce account page, before the navigation menu.

I've been trying to include the function in order to display the avatar inside the account dashboard instead, through the woocommerce_account_dashboard hook, but it's not positioned as I intend.

In the /templates/myaccount/dashboard.php file, I made the following changes:

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

$allowed_html = array(
    'a' => array(
        'href' => array(),
    ),
);
?>

<p class="pix-mb-0">
    <?php
    add_action('woocommerce_account_dashboard', 'uafw_show_avatar_woo', 10, 0 );
    
    printf(
        /* translators: 1: user display name 2: logout url */
        wp_kses( __( 'Hello %1$s!', 'woocommerce' ), $allowed_html ),
        '<strong class="text-yellow">' . esc_html( $current_user->display_name ) . '</strong>',
        esc_url( wc_logout_url() )
    );
    ?>
</p>

<p class="text-xs">
    <?php $current_user = wp_get_current_user();
    $current_user_id = $current_user->ID;
    echo __('Account ID: '), $current_user_id; ?>
</p>
<h1 class="h5 text-heading-default font-weight-bold pix-ready pix-mb-10" style="padding-bottom: 0.3em; border-bottom: 1px solid rgba(255,255,255,0.1)">Recent Orders</h1>
<?php add_action( 'woocommerce_account_dashboard', 'action_rorders_woocommerce_account_dashboard', 30, 0 ); ?>

<?php
    /**
     * My Account dashboard.
     *
     * @since 2.6.0
     */
    do_action( 'woocommerce_account_dashboard' );

the first function call is the avatar I want to display, the second one is a function that displays the last recent orders.

Everything works, but the avatar is not showing before the 'welcome' paragraph, but right above the orders table instead.

I tried to mess with priorities but it's not working either. What am I missing?


Solution

  • "Everything works, but the avatar is not showing before the 'welcome' paragraph, but right above the orders table instead."

    This is because the callback function of your add_action is executed where the do_action is located


    Let's say this is the output of the function you call:

    function uafw_show_avatar_woo() {
        echo '<div>Show avatar woo</div>';
    }
    

    Step 1) Then in the template file, where you want to call and display the function, you only need to use:

    <?php uafw_show_avatar_woo(); ?>
    

    OR

    Step 1) Create your own do_action, add it where you want to display the output from the callback function:

    <?php do_action( 'my_custom_do_action' ); ?>
    

    Step 2) and then execute the do_action via an add_action

    add_action( 'my_custom_do_action', 'uafw_show_avatar_woo' );