Skip to content

Using Action Hooks To Output Markup

Jim Reevior edited this page Aug 14, 2018 · 1 revision

Using Action Hooks to Output Markup

With the introduction of action hooks in Responsive Framework 2.0, markup can now be inserted in various places on a page without having to override the page template in a child theme. For a comprehensive list, check out the action hooks list.

Examples

Using a Template Part

The best way to insert markup using an action hook is to load a template part.

In this example, let's assume we want to insert a sub-navigation menu after the opening outer container, but only on the home page.

<?php
/**
 * Load the additional sub nav on the home page.
 */
function mytheme_r_after_opening_container_outer() {
	if ( is_front_page() ) {
		get_template_part( 'template-parts/additional-nav' );
	}
}
add_action( 'r_after_opening_container_outer', 'mytheme_r_after_opening_container_outer' );

This method allows you to keep all of your markup in a re-usable template part.

As another example, say we wanted to display the three most recent news posts at the bottom of all single blog posts.

<?php
/**
 * Display 3 recent blog posts at the bottom of single posts.
 */
function mytheme_r_before_closing_container_inner() {
	if ( ! is_single() ) {
		return;
	}

	$recent_posts = new WP_Query( array(
		'post_type'      => 'post',
		'posts_per_page' => 4,
		'orderby'        => 'date',
		'order'          => 'DESC',
		'no_found_rows'  => true,
	) );

	if ( ! $recent_posts->nhave_posts() ) {
		return;
	}

	while ( $recent_posts->have_posts() ) : $recent_posts->the_post();
		if ( get_the_ID() !== get_queried_object_id() ) {
			r_get_template_part( 'post', 'recent' );
		}
	endwhile;
}
add_action( 'r_before_closing_container_inner', 'mytheme_r_before_closing_container_inner' );

The above function will get the 4 most recent posts (just in case the user is on one of the most recent posts), and use the template-parts/post-recent.php or template-parts/post.php template to display the post.

Using a Function for Direct Output

Another way to output markup is directly in the function. This should be avoided whenever possible. Separating markup out of functions is preferred.

<?php
/**
 * Load the additional sub nav on the home page.
 */
function mytheme_r_after_opening_container_outer() {
	?>
	<div class="mytheme-custom-menu">
		<ul>
			<li></li>
			etc.....
		</ul>
	</div>
	<?php
}
add_action( 'r_after_opening_container_outer', 'mytheme_r_after_opening_container_outer' );

Welcome to Responsive!

Get started

Configuration

Build child themes

Sass

Javascript

PHP

Shortcodes

Templates

GitHub

Tasks

Contribute to the framework

Code Examples

BU Developer Resources

Clone this wiki locally