0

Basically what I am trying to achieve is to have title changed of posts which are in category number 30.

My code is:

function adddd($title) {

if(has_category('30',$post->ID)){
$title = 'Prefix '.$title;
}

return $title;
}
add_action('the_title','adddd');

The code works, but has one issue. When I am inside the post which has that category, title is being changed for all other pages (which are called through the_title) too.

How can I change the title only to post titles which has that category, no matter what page I am on?

1

$post is undefined in your filter. You need to explicitely invoke the $post global inside your filter function to have it available. You must remember that variables (even global variables) outside a function will not be available inside a function, that is how PHP works.

You actually do not need to use the $post global, the post ID is passed by reference as second parameter to the the_title filter.

You can use the following:

add_action( 'the_title', 'adddd', 10, 2 );
function adddd( $title, $post_id ) 
{
    if( has_category( 30, $post_id ) ) {
        $title = 'Prefix ' . $title;
    }

    return $title;
}

If you need to target only the titles of posts in the main query/loop, you can wrap your contional in an extra in_the_loop() condition

| improve this answer | |
0

Why not use javascript/jquery?

if your use <?php post_class(); ?> you can find a different class for each category.

    $('.post.category-one').find('h2.item-title').prepend('Prefix ');

Use .find() to the selector title

Edit

With php try this

function adddd($title) {
    global $post;

    if(has_category('30',$post->ID)) {
        $title = 'Prefix '.$post->post_title;
    }

    return $title;
}
add_action('the_title','adddd');
| improve this answer | |
  • I want to achieve this with php, because I will use it for another scripts, where js won't help. Thanks anyway – Simon Mar 7 '16 at 20:33
  • @Simon I updated my answer – nicogaldo Mar 7 '16 at 20:50

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.