Show group by alphabet posts with shortcode using WP_Query

Create an array of posts group by alphabet with WP_Query.

Use below to create the list of posts array with the group by alphabet.

Note: I have used post type. You can change this post type with your own. Also, you can modify the WP_Query parameters.

Now we can show the posts with the group by alphabet with a shortcode.

In below code we have created a shortcode prefix_alphabetic_posts to show the result in the post.

NOTE: Below short code is created only for demo purpose. So, Added inline CSS. You need to use wp_enqueue_scripts to enqueue your scripts.

Get all posts which contain specific shortcode

While working on some project, I was stuck on one issue.

The issue was, User was multiple posts and he was use my shortcode on some of them.

And I was trying to figure out which are the posts which content have my shortcode.


The answer is in my question. To do this I need to search the shortcode from all the post content.

To achieve this I have used SELECT query. E.g.

My shortcode was something like myshortcode (Not exactly this shortcode, I have use this shortcode for example purpose.)

Example 1: Search shortcode myshortcodein all the posts. (Including posts, pages, custom post types)

global $wpdb;
$ids = $wpdb->get_row("SELECT ID FROM {$wpdb->postmeta} WHERE meta_value LIKE '%myshortcode%'", ARRAY_A);

// print_r( $ids ); // Print all the IDs.

Above SELECT query return the array of IDs of all the posts, pages, custom post types which post content contain myshortcode.


Example 2: Search shortcode myshortcode ONLY in PAGES.

global $wpdb;
$ids = $wpdb->get_row("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%[myshortcode AND post_type='page'", ARRAY_A);

// print_r( $ids ); // Print all the IDs.

Create a simple shortcode in WordPress

Use code snippet to create a simple WordPress shortcode. I have created a sample shortcode prefix-portfolio with 2 attributes.

Before use change:

  • Change the Prefix with your own unique prefix.
  • Change the prefix with your own unique prefix.

How to use?

  1. Create a new page and add shortcode.
  2. Open the page. It’ll show the output of the shortcode like below:

Code Snippet