Change the page title using a short code

I am coding a plugin and I use a short code to render a page content. I want to change the page title. I used this:

// Change the title of the page of the charts to add the current month. 
add_filter('the_title', 'charts_title', 10, 2);
function charts_title($title, $id) { 
  $title .= ' ' . date('F Y');
  return $title;
}

But it does that for all the posts and pages. Can I do that only for the pages that contains the short code I created ? I tried to do that, but it doesn’t work.

Read More
add_shortcode('charts-vote', 'charts_vote');
function charts_vote($atts) {
    // Add the filter only in the short code function callback.
    add_filter('the_title', 'charts_title', 10, 2);   

    // ... // 
    return $content;
}

Can someone please help me ?

Related posts

Leave a Reply

1 comment

  1. I understand that the specifics of your set up may require checking for the Shortcode, but maybe a Custom Field could be used for that:

    add_filter( 'the_title', 'charts_title_so_15312385', 10, 2 );
    
    function charts_title_so_15312385( $title, $post_id ) 
    { 
        // Admin area, bail out
        if( is_admin() )
            return $title;
    
        // Custom field not set, bail out
        $mod_title = get_post_meta( $post_id, 'mod_title', true );
        if( !$mod_title )
            return $title;
    
        // Ok, modify title
        $title .= ' ' . date( 'F Y' );
        return $title;
    }
    

    The Shortcode could even “talk” with the Custom Field for extended configurations.

    For ease of use, you could make a Custom Meta Box or use a plugin like Advanced Custom Fields.