0

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?

2
  • 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, 2018 at 5:24
  • @kero I've shared my solution, now I'm solving how to get the shortcode params. Sep 11, 2018 at 5:39

1 Answer 1

1

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 />;
    }
  }
4
  • 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, 2018 at 5:43
  • @kero Thank you.. but I can get the used params on $matches[3] with that approach. Sep 11, 2018 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, 2018 at 6:22
  • WordPress has a function, has_shortcode() which can be used for checking if a shortcode exists. Sep 11, 2018 at 6:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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