Quite difficult to explain this one but I will do my best.

Let's assume we have the theme T and plugin P.

T has a bunch of custom taxonomies and so does P, the plugin.

What I am trying to achieve is display content from the custom taxonomies in P in the T template/single files, without modifying any of the files in T. Basically, I want to "hijack" the single views from the theme by writing the code in P. Is that achievable? And if so, how?

I just couldn't find a better word than "hijack". It's just adding different sections in the single view, based on the content that is saved in the custom taxonomies in the plugin.

Thank you in advance!


Yes, it's possible. You'll need to use the template_include filter.

To return a different template for a custom post type of "my_custom_post_type", you could do something like this:

add_filter( 'template_include', 'wpse_272261_template_include', 100 );
function wpse_272261_template_include( $template ) {
  if ( is_singular( [ 'my_custom_post_type' ] ) ) return PATH_TO . 'template.php';
  return $template;

You can use the the_content filter to add your own code to the output of the the_content() function.

It would work like this:

function my_add_to_content( $current_content ) {

    Add code here to output what you need to append to the content.
    Since this is between ob_start() and ob_get_clean() you can treat it like a
    template and echo the content/markup you need.

    $additional_content = ob_get_clean();

    $new_content = $current_content . $additional_content;

    return $new_content;
add_filter( 'the_content', 'my_add_to_content', 99 );

Hard to be more specific without knowing exactly what you need, but where I put that comment is where you'll need to do things like check if this is the post type/template you want to 'hijack` (use get_post_type() or is_page_template() for that sort of thing) and check if values exist for what you want to output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.