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/>"; } }
Hey Greg,
great snippet. I was trying to add this to content filter and was getting this error
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\site3\wp-content\themes\expound\functions.php on line 322
here is the code i was using
Hi Jerry,
in your case the pages_with_shortcode function returns null, this means that the shortcode does not exist or was not registered yet.
You can the function to always return array with (array)pages_with_shortcode(“some-shortcode”), this will fix the error you are having, however if you are using the function before the shortcode is registered it will always return empty array (or rather null).
Hope this helps.