I have a page where, with shortcode, I queried multiple posts from a CPT – so the page is one kind of archive page to the general users.

Page Title
  - CPT Post Title #1
  - CPT Post Title #2
  - CPT Post Title #3

In certain condition I want to alter only the Page Title, not CPT Post Title. I tried:

function wpse_change_page_title( $title ) {
   //if( condition matched ) {
       return 'Test ' . $title;
   //}
}
add_filter( 'the_title', 'wpse_change_page_title' );

But it’s altering the CPT Post Titles.

Page Title
  - Test CPT Post Title #1
  - Test CPT Post Title #2
  - Test CPT Post Title #3

How can I alter only the Page title, not those CPT Post Titles?

Test Page Title

3 Answers
3

I believe that the page title you are talking about is the title from the page from the main query. the_title() filter (and the_content() filter for that matter) targets all the respective template tags regardless of query.

To avoid this, target only the main query and the specific page.

You can try the following inside your filter

if ( in_the_loop() && is_page( 'specific page' ) ) {

    // Do what you need to do

}

EDIT

I just thought of this, haven’t tested it, but you can check your title inside the filter against a known static title and then do something according to that

Example:

if ( $title == 'My known title' ) {

    // Do something with the title

}

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *