Skip to content

Actions and filters

scribu edited this page Apr 25, 2012 · 11 revisions

Widgets and shortcodes

You can control the output of widgets and shortcodes with a pair of similar hooks. Here's an example of how you can make widgets and shortcodes use template files from your theme:

<?php
add_filter( 'p2p_widget_html', 'my_p2p_template_handling', 10, 4 );
add_filter( 'p2p_shortcode_html', 'my_p2p_template_handling', 10, 4 );

function my_p2p_template_handling( $html, $connected, $ctype, $mode ) {
	$template = locate_template( "p2p-{$mode}-{$ctype->name}.php" );

	if ( !$template )
		return $html;

	ob_start();

	$_post = $GLOBALS['post'];

	foreach ( $connected->items as $item ) {
		$GLOBALS['post'] = $item;

		load_template( $template, false );
	}

	$GLOBALS['post'] = $_post;

	return ob_get_clean();
}

Now, say you have a posts_to_pages connection type and you've set up a widget for it. If you create a p2p-ul-posts_to_pages.php file in your theme, the widget will load that file to render the list of connected items.

Here's what that file might look like:

<div>
  <?php the_post_thumbnail(); ?>
  <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</div>

The same will happen if you use a shortcode, such as [p2p_connected type=posts_to_pages mode=ul].

Clone this wiki locally