I want to add a title above a loop of posts, but only if there are posts.
In my project I’m using the genesis_custom_loop because I want to output a custom post type by author, but the issue, and solution, is the same if you are using the genesis_standard_loop.
My usual process is to check out the Genesis Visual Hook Guide for available hooks to add my title into. It gives me a couple of choices to try:
- genesis_loop – but that will add the title regardless of whether there are posts or not
- genesis_before_entry – but it then outputs the title above every post in the loop!
It appeared that my only solution was to create my own custom loop with a WP_Query but in this case I didn’t really want to do that.
When I get stuck like this I find it useful to open up the Genesis Framework files. And I’m always surprised that I didn’t think of it sooner because the answer is usually there as it shows you what hooks have been added for you to use.
A quick look in genesis/lib/structure/loops.php reveals that genesis_custom_loop in fact calls genesis_standard_loop (line 214). And on line 85 you will see the magical do_action( ‘genesis_before_while’ ); which is executed only after it is checked that there are posts, and before the loop starts (so will only run the once). This is the hook I want to add my function too!
In my case my genesis_custom_loop is in custom page template so I add this function to that file. You may wish to add it to an archive.php file.
You can also see this code on github.
add_action( 'genesis_before_while', 'custom_add_title_before_loop' );
/*
* Echo out the title
* The genesis_before_while runs after the if( have_posts() )
* and before while( have_posts() ) : the_post();
*/
function custom_add_title_before_loop() {
echo '<h2>My Title</h2>';
}
Featured Image: Photo by Nick Fewings on Unsplash
Robin
Nice little trick, Jo! I often fail to check the source files for answers, too. Thanks for sharing!