For example my example.com/sample-page/ is using [my_shortcode param="1"].

How can I get all the URLs of the pages that uses [my_shortcode]?

Is there an approach to achieve that?

  • I don't think there is already an implementation for this. You'd probably need to get all posts and check if the shortcode exists in each individually – kero Sep 11 at 5:24
  • @kero I've shared my solution, now I'm solving how to get the shortcode params. – 5ervant Sep 11 at 5:39
up vote 1 down vote accepted

Solution that I've found:

  $pages = get_pages();
  $pattern = get_shortcode_regex();

  foreach($pages as $page) {
    if ( preg_match_all( '/'. $pattern .'/s', $page->post_content, $matches )
      && array_key_exists( 2, $matches )
      && in_array( 'my_shortcode', $matches[2] ) )
    {
      echo $page->post_title . <br />;
    }
  }
  • 1
    According to the docs, you should be able to simply use get_shortcode_regex(array('my_shortcode')) and save yourself the trouble of comparing the $matches – kero Sep 11 at 5:43
  • @kero Thank you.. but I can get the used params on $matches[3] with that approach. – 5ervant Sep 11 at 6:06
  • Yeah, but your regex is really expensive if you check for all shortcodes. preg_match_all() might take a long time to execute, so using a simpler regex will probably make it alot faster – kero Sep 11 at 6:22
  • WordPress has a function, has_shortcode() which can be used for checking if a shortcode exists. – Jacob Peattie Sep 11 at 6:39

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.