1
votes

I want to apply a filter to the title of a post type, but only on its single page. So I made this function:

function title_filter( $title, $post_id = null ) {
    if ( ! empty( wp_get_associated_nav_menu_items( $post_id ) ) && is_singular( 'review' ) ) {
        $title = sprintf( '%1$s %2$s', $title, __( 'Review', 'stackoverflow' ) );
    }

    return $title;
}
add_filter( 'the_title', 'title_filter', 10, 2 );

But the problem is that the filter is also applied to the nav menu items that have a post of that type. I tried to exclude the filter from nav items using wp_get_associated_nav_menu_items() but that doesn't seem to work. Also tried checking the post type using get_post_type() but since the menu items respond to the post type when the item is added using the post type options on the menu editor, they always match and the filter is applied anyway.

The solution given on this question didn't work for me.

Any ideas?

1

1 Answers

2
votes

You can check to make sure you're only filtering titles in the loop by comparing with the in_the_loop() boolean function:

function mithc_title_filter( $title, $post_id = null ) {
    if( in_the_loop() && is_singular( 'review' ) ){
        $title = sprintf( '%1$s %2$s', $title, __( 'Review', 'stackoverflow' ) );
    }
    return $title;
}
add_filter( 'the_title', 'mithc_title_filter', 10, 2 );