NB: Make sure you do a back up of your theme, files and database before attempting the tutorials
Last modified : Oct 01 2022
Estimated reading time : 1 minute, 30 seconds - 131 words
Share the post "Count of attached files – Post Type"
In this tutorial, we will display the count of attached media files like images corresponding to a post type.
So, we will create a shortcode to display the media count. We need to make a wp query.
You can read our article about the WP Query shortcode.
Bill Erickson offers us the whole list of arguments we can make in our WP Query (Arguments)
Knowing the name parameter of your post type, you will, therefore, set up this shortcode.
Shortcode to display the count of the attached files - Post Type
add_shortcode( 'addocountattachementsposttype', 'addo_count_attachementsposttype' ); function addo_count_attachementsposttype(){ global $post; //Get all attachments $attachments = get_posts( array( 'post_type' => 'attachment', 'posts_per_page' => -1 ) ); $att_count = 0; if ( $attachments ) { foreach ( $attachments as $attachment ) { // Check for the post type based on inpidual attachment's parent if ( 'crasyphotosgalleries' == get_post_type($attachment->post_parent) ) { $att_count = $att_count + 1; } } echo $att_count; } }
Then, replace crasyphotosgalleries with the name of your post type.
Here in our example (addocountattachmentsposttype) you can change the name of your WordPress shortcode.
[addocountattachementsposttype]