I’m using example code for a templating system.
Page at this address: http://project.test/my_cpt/hello-post/
.
Cannot understand why is_singular( 'my_cpt' )
is true
while in_the_loop()
is false
.
Within the page template, it seems like The Loop “works”:
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
?>
<h2><a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<?php
}
}
I guess my question is when are is_singular() && in_the_loop()
both true?
And when I run if ( have_posts() ) { while ( have_posts()...
is that in the loop or is it creating the loop?
Update
Partly it has to do with which filter is being hooked in the function/method which performs the if &&
test.
The example above is being used with the template_include
hook, which is getting run for pages, posts and maybe even links, menus, media, etc. So that would be why both tests are necessary.
The filter looks like:
add_filter( 'template_include', array( __CLASS__, 'my_template_include_method' ) );
or if it was not calling a class method would just be:
add_filter( 'template_include', 'my_template_include_function' );
The full method/function looks like:
public static function my_template_include_function( $original_template ) {
if ( is_singular( 'my_cpt' ) && in_the_loop() ) {
return wpbp_get_template_part( MMC_TEXTDOMAIN, 'content', 'my_template', false );
}
return $original_template;
}
The wpbp_get_template_part
is from a plugin boilerplate I recently discovered called WordPress Plugin Boiler Plate.
Since I’m looking, at the moment, a singular post, I can hook into single_template
like this:
add_filter( 'single_template', array( __CLASS__, 'my_single_include_function' ) );
It looks like this:
public static function my_single_include_function( $single_template ) {
global $post;
if ( 'my_cpt' === $post->post_type ) {
return wpbp_get_template_part( MMC_TEXTDOMAIN, 'single', 'my_template', false );
}
return $single_template;
}
The templates themselves look like: templates/content-my_template
and templates/single-my_template
.