How to filter the_content() & include content from template

I am trying to filter the_content() on single page, but it looks like it is creating an infinite loop. I want to know how to fix this. I want to override the_content().

Is there any other way to override single page content from plugin?

add_filter( 'the_content', 'change_single_content' );
function change_single_content($content){
    global $post;

    if ( 'my-CPT' == get_post_type() && is_single() ){
        ob_start();
        include my_plugin_theme('single-template.php'); //include single template content
        return ob_get_clean();
    }

    return $content;
}

Related posts

2 comments

  1. My guess is that single-template.php uses the_content. Now think about what happens:

    1. Your filter causes single-template.php to load
    2. single-template.php uses the_content
    3. So single-template.php loads again
    4. Which uses the_content
    5. Which loads single-template.php
    6. Which uses the_content

    I am not entirely sure how to fix that, as your question is light on detail. It is hard to tell what most of the code does or what your ultimate goal is, but it may be as simple as removing the filter conditionally:

    add_filter( 'the_content', 'change_single_content' );
    function change_single_content($content){
        global $post;
    
        if ( 'my-CPT' == get_post_type() && is_single() ){
            remove_filter( 'the_content', 'change_single_content' ); // this !!
            ob_start();
            include my_plugin_theme('single-template.php'); //include single template content
            return ob_get_clean();
        }
    
        return $content;
    }
    

    I am also pretty sure that what you are doing is the wrong way, or at least a less-right way, to do what you are trying to do. I can’t prove that, but my spider sense is tingling something awful.

  2. add_filter( 'the_content', 'filter_content' );
    function filter_content( $content ){
        if ( is_single() ){
            $new_content = str_replace( 'for', 'FOR', $content );
            return $new_content;
        }
        else
        {
            return $content;
        }
    }
    

    Try this. I have tried replacing the_content on single post. It’s replacing but not on index page because of is_single() condition.

    You can tweak it that suits your need.

    The problem with you code is that you are accepting $content as parameter and returning ob_get_clean(). You should return $content after tweaking it, in this scenario.

    As in the code above, I have accepted $content, tweaked it and returned $new_content.

Comments are closed.