WordPress.org

Ready to get started?Download WordPress

Forums

add_action and do_action - code confusion (2 posts)

  1. ocset
    Member
    Posted 1 year ago #

    Hi

    I am just cutting my teeth on WordPress and have stumbled on something that I don't understand.

    function twentyeleven_enqueue_color_scheme() {
            $options = twentyeleven_get_theme_options();
            $color_scheme = $options['color_scheme'];
    
            if ( 'dark' == $color_scheme )
                    wp_enqueue_style( 'dark', get_template_directory_uri() . '/colors/dark.css', array(), null );
    
            do_action( 'twentyeleven_enqueue_color_scheme', $color_scheme );
    }
    add_action( 'wp_enqueue_scripts', 'twentyeleven_enqueue_color_scheme' );

    Why is the do_action() function called inside the function of the same name - its calling itself. It obviously works but my brain thinks that would be an infinite loop?

    Also:
    Why would one create an action
    add_action( 'wp_enqueue_scripts', 'twentyeleven_enqueue_color_scheme' );

    but then call it by the function name (twentyeleven_enqueue_color_scheme) not the tag name (wp_enqueue_scripts)?

    do_action( 'twentyeleven_enqueue_color_scheme', $color_scheme );

    Thanks in advance
    O

  2. Rebecca Schaefer
    Member
    Posted 1 year ago #

    This is a really good question. =) I'll first direct you to the WP documentation on the matter, before trying to offer a different way of explaining it.

    wp_enqueue_scripts is an action hook. It executes at the end of a function. When that happens, you'll see do_action used.

    do_action('the name of the action', 'a variable with what the action needs');

    When do_action is called, WP executes all functions assigned to that action by add_action. add_action is WP's way of registering which functions happen when.

    add_action('the name of the action', 'the name of the function to execute');

    In this case, execute twentyeleven_enqueue_color_scheme when it's enqueueing the scripts. Now, twentyeleven_enqueue_color_scheme has it's own action hook. Before that's done processing, it calls do_action to execute any functions that may have been hooked to it.

    In the case above, we're telling WP
    - When you load the scripts, also call this twentyeleven function.
    - At the end of the twentyeleven function, call any other functions that may have been hooked to it (by plugins, child themes, custom functions, etc.).

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.