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/>";
    }
}

About

Greg is a longtime WordPress enthusiast ho remembers the old days ... that is WP version 2.5. On a day to day basis he is lucky enough to work on various WordPress plugins. In the free time he blogs at wplingo.com.

2 thoughts on “Find Pages using given WordPress shortcode

  1. 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

    add_filter("the_content", "my_content_filter", 0, 1000);
    function my_content_filter() {
    foreach(pages_with_shortcode("some-shortcode") as $p) {
    $content .= $p->post_title." <br/>";
    }
    
  2. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *