WordPress.org

Make WordPress Core

Opened 3 years ago

Closed 2 years ago

Last modified 2 years ago

#40253 closed defect (bug) (worksforme)

the_content problem

Reported by: tazotodua Owned by:
Milestone: Priority: normal
Severity: normal Version:
Component: Posts, Post Types Keywords:
Focuses: Cc:
PR Number:

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
3 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
2 years ago

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

#3 @netweb
2 years ago

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