0

I'm new to wordpress plugin development, I read the whole documentation this afternoon http://codex.wordpress.org/Plugin_API/Filter_Reference, I tried to write some code, like this in plugin file:

add_filter('the_title', 'my_own_function', 10, 2);

Function is:

function my_own_function($title, $post_id){
    return $title. $post_id;
}    

This plugin really worked, but the documentation doesn't tell the filter API the_title has two arguments, and what those arguments are. That's the problem! If it doesn't tell, how would I know?

Here I just quote the official documentation relevant excerpt:

the_title 
applied to the post title retrieved from the database, prior to printing on the screen (also used in some other operations, such as trackbacks).

So, my question is: How can I find a full explanation of filter API such as the_title? Please help.

0

There's only one answer: You always go and read the source code.

There are some online tools that help you with this, specifically Adam Brown's Hooks List, which contains links to the source code where you can read what arguments filters and actions take.

Be aware that a single filter can have variable amounts of arguments depending on where it is being used. For example, in class-wp-posts-list-table.php the_title filter sends out one argument only, instead of two like in post-template.php

So, again, always read the source specifically on where the filter is being applied.

0

How-to add the filter

As a rule of thumb:

If the filter has more than one var, then you have to add priority & num_args to the filter

# Example:
// RIGHT
add_filter( 'the_title', 'your_callback_fn', 20, 2 );
// WRONG
add_filter( 'the_title', 'your_callback_fn' );

How-to to return in the callback

Another rule of thumb (might not be always true, but I haven't found the opposite so far):

Always return the first argument

// Example
function your_callback_fn( $var_A, $var_B, $var_C )
{
    // do stuff - the other vars (B-C) are here for your help

    // ! important: return the 1st var
    return $var_A;
}
add_action( 'the_funk', 'your_callback_fn', 10, 3 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.