Custom theme hooks / filters – passing arguments

I’m getting confused trying to implement these custom theme hooks. Trying to wrap my head around that.

I thought i understood this. but now after reading code for several hours; it’s made it worst.

Read More

How do i modify the argument being passed in the following?

functions.php

function theme_content() {
   do_action('theme_content'); // Initialize my custom hook
}


function theme_content_alter($arg) {
   // Do processing
   if (!$arg) {
     echo '<h2>default</h2>';
   }
   if ($arg == 'foo')  {
     echo '<div class="content">bar</div>';
   }

   echo apply_filters('theme_content','theme_content_alter', $arg);
} add_action('theme_content', 'theme_content_alter');

index.php

theme_content($arg = 'foo');

What i’m trying to achieve

Being able to override hooks and handle contextual processing inside a functions or a separate file from a require.

An example: on a front page i want theme_content() to have no sidebar but on a subpage it’ll contain a sidebar, etc. This could be expressed like so:

Is this the proper way to do this? I’ve tried to write it in my theme and haven’t been able to figure out why it’s not working. My arguments are not being passed in the parameters.

What i have done

Reviewed several threads on this SE and found them not very helpful for my context:

Related posts

Leave a Reply

2 comments

  1. If you want theme_content hook to run with arguments that you pass to theme_content() function you need to write it like this:

    function theme_content($args) {
    
       do_action('theme_content', $args);
    }
    
  2. Very good answer by Rarst. I’ve been doing it the hard wrong way without the $args in the hook initialization function and called global $post in the processing function to make it work.

    I also wanted to expand on Rarst’s answer and mention that instead of echoing the values out you should assign them to the $arg variable or else the arg “foo” will also get output in the content. You also don’t need to put the hook name in apply_filters.

    Here is your code updated (this was tested and works)

    function theme_content( $arg ) {
       do_action('theme_content', $arg ); // Initialize my custom hook
    }
    
    
    function theme_content_alter( $arg ) {
        if( !$arg ) {
        $arg = '<h2>default</h2>';
        } elseif ( $arg == 'foo' ) {
        $arg = '<div class="content">bar</div>';
        }
    
        echo apply_filters( 'theme_content_alter', $arg );
    
    }
    add_action( 'theme_content', 'theme_content_alter' );