Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kellenmace/cdf60f88e5b07356d992bcdb5439ff25 to your computer and use it in GitHub Desktop.
Save kellenmace/cdf60f88e5b07356d992bcdb5439ff25 to your computer and use it in GitHub Desktop.
Get a list of all WordPress pages that contain a shortcode
<?php
/**
* Get a list of all pages that contain a shortcode.
*
* @param string $shortcode The shortcode to look for without square brackets.
*
* @return array List of pages in the format $post_id => $post_title.
*/
function get_pages_with_shortcode( $shortcode ) {
$all_page_ids = ( new WP_Query( [
'post_type' => 'page',
'posts_per_page' => 1000,
'no_found_rows' => true,
'fields' => 'ids',
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
] ) )->get_posts();
$page_ids_with_shortcode = array_filter( $all_page_ids, function( $page_id ) use ( $shortcode ) {
$post_content = get_post_field( 'post_content', $page_id );
return false !== strpos( $post_content, '[' . $shortcode );
} );
$pages_with_shortcode = array_map( function( $page_id ) {
return get_the_title( $page_id );
}, array_combine( $page_ids_with_shortcode, $page_ids_with_shortcode ) );
asort( $pages_with_shortcode ); // Sort alphabetically by title.
return $pages_with_shortcode;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment