Adding content after “Default” shortcode items.

The “Default” shortcode comes with twelve different action hooks that you can use to customize displayed content on the page.

They are all listed below, and hopefully they are self explanatory.

template_posts_before_title
template_posts_after_title
template_posts_before_item
template_posts_before_featured_image
template_posts_after_featured_image
template_posts_before_item_title
template_posts_after_item_title
template_posts_before_excerpt
template_posts_after_excerpt
template_posts_after_item
template_posts_before_pagination
template_posts_after_shortcode

For this tutorial, I am going to show you how you can use the “template_posts_after_item” hook to add custom field data to each listing on the screen.

Creating a callback.

The first thing we need to do is create a function to be used as a callback for the hook. We are going to place it in our current theme’s functions.php file.

function pluginize_after_post_content( $attributes, $post_id ) {

}
add_action( 'template_posts_after_excerpt', 'pluginize_after_post_content' );

Gaining access to the custom fields.

For our example here, imagine that you have a list of movies being displayed on screen, and each has a custom field that holds the calendar year that it was released in. We want to display that at the end of each movie.

function pluginize_after_post_content( $attributes, $post_id ) {
	echo '<p>Release year: ' . get_post_meta( $post_id, 'release_year', true ) . '</p>';
}
add_action( 'template_posts_after_excerpt', 'pluginize_after_post_content' );

With this code in place, we would grab the custom field from the current post being displayed, and echo the content after the post’s excerpt data.

Feel free to tinker with the other template hooks listed above and see what you can achieve with your content. If you need to see the template code that will be used, open the /cptui-extended/templates/posts.php file to see where the hooks are in greater detail.

Updated Dec 12, 2022 8:39 PM