Shortcode Finder

I’m cleaning up a website with a lot of old shortcodes. Before removing a shortcode, we wanted to be sure all pages that used it were updated.

So I wrote a shortcode to help 🙂

[find_shortcode shortcode="listing"] will display a list of all posts/pages using the [listing] shortcode.

/**
 * Find Shortcode
 *
 */
function be_find_shortcode( $atts = array() ) {

	$atts = shortcode_atts( array(
		'shortcode' => '',
	), $atts, 'find_shortcode' );


	$loop = new WP_Query( array(
		'posts_per_page' => -1,
		'post_type' => array( 'post', 'page' ),
		'orderby' => 'title',
		'order' => 'ASC'
	));

	$found = array();
	if( $loop->have_posts() ): while( $loop->have_posts() ): $loop->the_post();
		global $post;
		if( has_shortcode( $post->post_content, $atts['shortcode'] ) )
			$found[] = '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
	endwhile; endif; wp_reset_postdata();

	if( !empty( $found ) ) {
		$output = '<h3>Pages with the [' . $atts['shortcode'] . '] shortcode</h3><ul>' . join( PHP_EOL, $found ) . '</ul>';
	} else {
		$output = '<h3>No pages found with [' . $atts['shortcode'] . '] shortcode</h3>';
	}

	return $output;
}
add_shortcode( 'find_shortcode', 'be_find_shortcode' );

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk

Reader Interactions

Leave A Reply