categories - Change post title if post has specific category

admin2025-06-06  8

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?

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?

Share Improve this question edited Mar 8, 2016 at 6:36 Pieter Goosen 55.5k23 gold badges117 silver badges211 bronze badges asked Mar 7, 2016 at 20:20 SimonSimon 1556 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 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

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');
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749203384a317228.html

最新回复(0)