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;
}
My guess is that
single-template.php
usesthe_content
. Now think about what happens:single-template.php
to loadsingle-template.php
usesthe_content
single-template.php
loads againthe_content
single-template.php
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:
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.
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 returningob_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
.