Make WordPress Core

Opened 8 years ago

Closed 7 years ago

Last modified 7 years ago

#40253 closed defect (bug) (worksforme)

the_content problem

Reported by: tazotodua's profile tazotodua Owned by:
Milestone: Priority: normal
Severity: normal Version:
Component: Posts, Post Types Keywords:
Focuses: Cc:

Description (last modified by SergeyBiryukov)

Hi.
I think it is quite essential problem.

lets say I want to check, if post's custom field "smth" is 1, then I want to set content to "Hello World".

add_filter('the_content', function($content){
    global $post;
    if(get_post_meta($post->ID, 'smth', true ) == 1 ){
      $content = "Hello World";
    }
    return $content;
});

but problem raises, when we access single post, which has set it's custom field to smth to 1, but also, the_content is also changed to Hello World everywhere else (in sidebars, recent posts and etc... everywhere), because in the_content we make comparison for the GLOBAL POST's data. I think there should be some kind of additional parameter with the_content filter, which will indicate if it is the main content of single page.

the same problem (but oppositely) arises, when we want to filter the_content in all areas, but not for the main post-s content..

Change History (3)

#1 in reply to: ↑ description @SergeyBiryukov
8 years ago

  • Description modified (diff)

Replying to tazotodua:

but problem raises, when we access single post, which has set it's custom field to smth to 1, but also, the_content is also changed to Hello World everywhere else (in sidebars, recent posts and etc... everywhere)

You could use is_main_query() to prevent that:

add_filter('the_content', function($content){
    global $post;
    if ( is_main_query() && get_post_meta( $post->ID, 'smth', true ) == 1 ) {
      $content = "Hello World";
    }
    return $content;
});

#2 @tazotodua
7 years ago

  • Resolution set to worksforme
  • Status changed from new to closed

#3 @netweb
7 years ago

  • Milestone Awaiting Review deleted
Note: See TracTickets for help on using tickets.