Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have the following piece of abridged code:

<?php 
class New_Walker_Nav_Menu extends Walker_Nav_Menu {


function start_el(&$output, $item, $depth, $args) {
    $attributes  = ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
    $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';
    $output .= '<li><a'. $attributes .'>';
    $output .= apply_filters( 'the_title', 'modifyTitle', $item->ID );
    $output .= '</a></li>';
}
function modifyTitle($title){
    return $title . asd;
}
}
?>

Is this the right way to do it?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

apply_filters() applies a set of registered (with add_filter()) callbacks.

When you apply a filter make sure its name is not one of the reserved ones, the_title looks dangerously "collissible" with other filters.

Your filter application is almost correct, but the 'modifyTitle' bit is not required...

// apply the filter
apply_filters( 'wpse31787_the_title', $item->ID );

...instead you have to register a filter for wpse31787_the_title during your initialization

function __construct() {
    add_filter( 'wpse31787_the_title', array($this, 'modifyTitle') );
}

And your function definition would be

function modifyTitle( $item_id ) {
    // ...your code goes here
}

If you're going to pass more than 1 parameter you will have to extend your filter addition like so:

// 2 arguments are expected
add_filter(  'wpse31787_the_title', array($this, 'modifyTitle'), null, 2 );

So, if I put the all the bits together I would have something like this:

class New_Walker_Nav_Menu extends Walker_Nav_Menu {
    function __construct() {
        add_filter(  'wpse31787_the_title', array($this, 'modifyTitle'), null, 2 );
    }

    function start_el( &$output, $item, $depth, $args ) {
        $output .= apply_filters( 'wpse31787_the_title', $item->title );
    }

    function modifyTitle( $title ){
        return $title . ' << ';
    }
}
share|improve this answer
    
Thanks alot! But just one question, why is the apply_filter's hook different from the add_filter? –  mitsukare Oct 22 '11 at 7:36
    
Mistake on my part, copied the line from your code and forgot to change the filter name, I edited the post; filter name must be the same throughout. Thanks for noticing. –  soulseekah Oct 22 '11 at 7:51
    
It's okay I wasn't even sure if it was a mistake! thanks again! –  mitsukare Oct 22 '11 at 8:44

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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