I have a custom post type ‘properties’ that I’d like to control the HTML output for. For simplicity, let’s focus on the archive view.
As a basic example, here is what a loop looks like in an archive.php
file:
<?php while ( have_posts() ) : the_post(); ?>
<h2><?php the_title(); ?></h2>
<div><?php the_content(); ?></div>
<?php endwhile; ?>
I’d like to be able to modify the output of the loop with my custom ‘properties’ HTML without adding a new template or using a shortcode – basically, without user intervention. Just to be clear, I’d like to replace the <h2>
and <div>
in the above example, and nothing before/after it.
Note: The above is only an example. I would like to control the loop output regardless of theme.
Right now I am using output buffering to capture the output from loop_start
to loop_end
and replacing it with my own, but this potentially can create conflicts with other plugins.
Is there an accepted/better way to do this?
There’re two very often forgotten action ref arrays:
loop_start/_end()
.Just turn on output buffering and you’re ready to go.
Note: I wouldn’t do it like this, but as you said, you want exactly that level of overriding, here you go.
You can change the loop via hook, like this for cpt ‘my_post_type ‘
If remembering well, I derived this technique from here: Use template_include with custom post types.
We use a plugin that will generate a “Virtual Template” for a given Post Type. The filter
template_include
will render a template file that resides in the plugin folder.You have to refine the function
custom_template
and the template file to suit your needs. Hope this helps 😉Plugin File
adjust the
post_type
name in the class instantiationTemplate file
single-virtual-cpt.php
put in the same folder as the plugin file
Result
click to enlarge ⤴
I’ve been trying to figure out a solution for this too – I have a plugin with custom post types, those custom post types require a custom archive but creating a specific template file means it wouldn’t work with every theme.
The closest alternative I can think of that hasn’t been mentioned above is to read the archive/index.php file on plugin activation (and theme change) and to copy the archive.php file to your plugin folder with the relevant name change to be specific for your custom post type.
Then, have your plugin automatically modify the custom template file to inject your own loop code.
e.g. in above little snippet from an index.php file, scan for while(have_posts()…) line and corresponding line and replace everything in between with your custom loop html code.
I’ve not tried this, it’s just another potential solution and I’d appreciate comments if anyone else has used this approach.