This scenario explains a different use of a shortcode from both a developer's perspective as well as a content creator's perspective. Here, we need to display the list of posts with at least one attachment. Unlike the previous scenario, we are not retrieving and modifying the content. Instead, we are generating dynamic content based on the shortcode attributes. Let’s take a look at the shortcode needed for this scenario:
[wpquick_attachment_posts/]
As you can see, there is no closing tag, and the closing part is done within the opening tag. These types of shortcodes are called as self-enclosing shortcodes. We don’t use any content in such shortcodes. In this case, we are displaying all the posts with attachments, and hence shortcode attributes are not required. If we were displaying posts with attachments for a specific category, the shortcode would have looked as follows:
[wpquick_attachment_posts category='1' /]
Now we can implement the previous shortcode by matching it with the syntax we used in our shortcode diagrams:
add_shortcode( 'wpquick_attachment_posts', 'wpquick_attachment_posts_display' );
function wpquick_attachment_posts_display( $atts, $content ){
global $wpdb;
$post_attachments_table = $wpdb->prefix.'wpqpa_post_attachments';
$sql = "SELECT P.post_title,P.guid from $post_attachments_table as PA inner join $wpdb->posts as P on P.ID=PA.post_id group by PA.post_id ";
$result = $wpdb->get_results($sql);
$html = '';
if($result){
foreach ( $result as $key => $value ) {
$html .= '<a href="'. $value->guid .'">'. $value->post_title .'</a><br/>';
}
}
return $html;
}
In this case, we have no attributes, and hence we query the custom table by joining it with a posts table to generate the result. The $content variable will be empty, as we are not passing any data by using opening and closing tags. Finally, we return the HTML string to display the list of posts.