How to add your own loop

Ivan sent a message over Twitter and asked how to get breadcrumbs to work with tags. As you may know from the How to use Loops to iterate over items tutorial, it’s pretty simple with categories because they’re hierarchical. That’s not the case with tags. So it lead me to this blog post which shows how you can create your own loop.

Add a new field to the select box

The following code shows how you can add a new value to the loop select box. It uses the wpbuddy/rich_snippets/fields/loop_subselect/values filter.

<?php
/*
Plugin Name: SNIP Custom Loop
Version: 0.1.0
Description: Example that shows how to create custom loops.
*/

add_filter( 'wpbuddy/rich_snippets/fields/loop_subselect/values', 'csnip_loop_values', 10, 1 );

/**
 * Adds a custom value to the loop select box.
 *
 * @param array $values
 *
 * @return array
 */
function csnip_loop_values( $values ) {

	$values['csnip_custom_loop'] = __( 'Custom Loop', 'csnip-loops' );

	return $values;
}

After installing and activating the above sample WordPress plugin you’ll have a new option in the select box dropdown:

Structured Data Generator with new field in the loop select box.

Add a functionality

After saving your Global Snippet nothing happens. This is because SNIP does not know what do when “Custom Loop” was selected. We need to add a functionality to the loop we’ve just created.

The following code uses the wpbuddy/rich_snippets/rich_snippet/loop/items filter which allows you to return the items you want to loop through.

<?php
/*
Plugin Name: SNIP Custom Loop
Version: 0.1.0
Description: Example that shows how to create custom loops.
*/

add_filter( 'wpbuddy/rich_snippets/fields/loop_subselect/values', 'csnip_loop_values', 10, 1 );

/**
 * Adds a custom value to the loop select box.
 *
 * @param array $values
 *
 * @return array
 */
function csnip_loop_values( $values ) {

	$values['csnip_custom_loop'] = __( 'Custom Loop', 'csnip-loops' );

	return $values;
}

add_filter( 'wpbuddy/rich_snippets/rich_snippet/loop/items', 'csnip_loop_items', 10, 3 );


/**
 * The items to choose.
 *
 * @param array                               $items
 * @param \wpbuddy\rich_snippets\Rich_Snippet $snippet
 * @param int                                 $post_id
 *
 * @return array
 */
function csnip_loop_items( $items, $snippet, $post_id ) {

	if ( 'csnip_custom_loop' !== $snippet->get_loop_type() ) {
		return $items;
	}

	/**
	 * Do your custom code here.
	 * Make sure that the key is the ITEM ID.
	 */
	$my_items = [
		'item_id_1' => new stdClass(),
		'item_id_2' => new stdClass(),
	];

	return $my_items;
}

Full example code

You can download the full example code here as a ZIP file. Note that it’s an example and needs customization.