functions - Is possible add icon in title posts only in specific tag?

admin2025-06-06  10

I want to add an icon in title posts only in posts with specific tag.

Is this possible?

I've already tried these codes, but they didn't solve my problem:

Approach #1

if (is_tag('162')) {
    function new_title( $title ) {
        $new_title = 'icon-url' . $title;
        return $new_title;
    }
    add_filter( 'the_title', 'new_title' );
}

Approach #2

add_filter( 'the_title', 'modify_post_title' );
function modify_post_title( $title ) {
    if ( is_tag('162') && $title == 'Existing Title' )
        $title = '<span>Existing</span> Title';
    return $title;
}

I want to add an icon in title posts only in posts with specific tag.

Is this possible?

I've already tried these codes, but they didn't solve my problem:

Approach #1

if (is_tag('162')) {
    function new_title( $title ) {
        $new_title = 'icon-url' . $title;
        return $new_title;
    }
    add_filter( 'the_title', 'new_title' );
}

Approach #2

add_filter( 'the_title', 'modify_post_title' );
function modify_post_title( $title ) {
    if ( is_tag('162') && $title == 'Existing Title' )
        $title = '<span>Existing</span> Title';
    return $title;
}
Share Improve this question edited Nov 18, 2018 at 20:11 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Nov 18, 2018 at 19:11 En Código WPEn Código WP 213 bronze badges 5
  • And what have you tried already? – Krzysiek Dróżdż Commented Nov 18, 2018 at 19:14
  • if(is_tag('162')){ function new_title( $title ) { $new_title = 'icon-url' . $title; return $new_title; } add_filter( 'the_title', 'new_title' ); } – En Código WP Commented Nov 18, 2018 at 19:16
  • add_filter( 'the_title', 'modify_post_title' ); function modify_post_title( $title ) { if ( is_tag('162') && $title == 'Existing Title' ) $title = '<span>Existing</span> Title'; return $title;} – En Código WP Commented Nov 18, 2018 at 19:17
  • OK, and where exactly should that icon be visible? On single post only? On all archive pages? – Krzysiek Dróżdż Commented Nov 18, 2018 at 19:42
  • In single and archive pages. I have some different posts I want mark in these titles – En Código WP Commented Nov 18, 2018 at 20:07
Add a comment  | 

1 Answer 1

Reset to default 0

The problem with your first approach is that you check conditional tags too early. is_tag will work only after the $wp_query is computed, so there is no point in checking it directly in functions.php file.

And there is one more problem with both approaches - you use wrong conditional tag...

is_tag checks if a Tag archive page is being displayed... So it's not what you're looking for.

And here's a solution:

function add_something_to_post_title( $title ) {
    if ( has_tag( 162 ) ) {
        $title = 'something ' . $title;
    }
    return $title;
}
add_filter( 'the_title', 'add_something_to_post_title' );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749171176a316960.html

最新回复(0)