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 the co-founder and lead developer at CultivateWP, a WordPress agency focusing on high performance sites for web publishers.

About Me
Ready to upgrade your website?

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

Let's Talk

Comments are closed. Continue the conversation with me on Twitter: @billerickson