Find Pages using given WordPress shortcode
In WordPress it is quite easy to find all Pages or Post using given shortcode, below is a function that will do this, one important thing to keep in mind is that the shortcode you will be looking for needs to be registered (using add_shortcode) before using this function, otherwise the function will return NULL.
What i find cool about the has_shortcode() function is that it will find shortcodes regardless of how they are being used, with or without attributes.
function pages_with_shortcode($shortcode, $args = array()) {
if(!shortcode_exists($shortcode)) {
// shortcode was not registered (yet?)
return null;
}
// replace get_pages with get_posts
// if you want to search in posts
$pages = get_pages($args);
$list = array();
foreach($pages as $page) {
if(has_shortcode($page->post_content, $shortcode)) {
$list[] = $page;
}
}
return $list;
}
// quick usage guide
// adding filter with low priority
add_filter("init", "_my_init_test", 0, 1000);
function _my_init_test() {
foreach(pages_with_shortcode("my_super_shortcode") as $p) {
echo $p->post_title." <br/>";
}
}