This is a quick example of a WordPress loop that searches through all posts, of multiple post types including custom post types, to find if a certain shortcode is used within the content, and how many times that shortcode is used.
This is for the random case in which a shortcode may be used multiple times within a post, and you need to know exactly how many times it’s used.
Or if you just need a list of all posts that use a certain shortcode.
To use this example, you must edit:
- Lines 9–11. This example searches through posts, pages, and several custom post types. You can edit these on lines 7–11. In particular, you must edit or remove lines 9–11 because those are just example names for custom post types. Use your own custom post types that you want to search through, or else remove those lines.
- Line 23. This example searches the content for the shortcode named
my_shortcode
. You must changemy_shortcode
to your own shortcode.
$log = array(); $args = array( 'posts_per_page'=> -1, 'offset' => 0, 'post_type' => array( 'post', 'page', 'my_custom_post_type', 'my_custom_product', 'my_custom_book' ) ); $myposts = get_posts( $args ); // Loop through all posts of each post type (and pages). foreach ( $myposts as $post ) { // Find cases where my shortcode is used at least once. $count = substr_count($post->post_content, '[my_shortcode]'); if ( $count >= 1 ) { // Get post name and id. $log[ $post->ID ] = $count . ' , ' . $post->post_title; } } // Log the results. error_log(print_r($log, true));
Output
The example above will log the results in your error log file. The result will be an array of all the posts which have the shortcode in the content. Each array element will have the post ID as the key. The value for each key will be: the number of times the shortcode is found with the post content, followed by a comma, and the post title.
Here is an example of the what will be logged:
Array( [873] => 2 , Some Post Title [863] => 1 , Another Post Title [851] => 2 , Yet Another Post Title [855] => 1 , Random Post Title )
Questions and Comments are Welcome