NB: Make sure you do a back up of your theme, files and database before attempting the tutorials

Intermediate
Web Hosting Canada

Last modified : Aug 20 2023

Estimated reading time : 1 minute, 48 seconds - 96 words

Number of WordPress Media Query

With this tutorial, we will create a query that will return the number of media (i.e. images) that have been uploaded in WordPress.

Let’s start with image type. In our query below, we will create an SQL query that will fetch the number of images uploaded today. Le post mime type

.Here’s the SQL query inside a shortcode:

/**************************** Count des images telechargees aujourd'hui ********************************/

function count_attachments_today() {
    global $wpdb;

    $today = getdate();
    $year = $today['year'];
    $month = $today['mon'];
    $day = $today['mday'];

    $count = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COUNT(ID) FROM $wpdb->posts
            WHERE post_type = 'attachment'
            AND post_mime_type LIKE 'image%%'
            AND YEAR(post_date) = %d
            AND MONTH(post_date) = %d
            AND DAY(post_date) = %d",
            $year, $month, $day
        )
    );

    return '<div class="addo40px addocenter">' . $count . '</div>';
}
add_shortcode( 'attachmentcounttoday', 'count_attachments_today' );

Number of WordPress Media Query

We will now do the same query, but this type for the video format. Once again, here’s the SQL query inside a shortcode:

/**************************** Count des videos telechargees aujourd'hui ********************************/

function count_videos_attachments_today() {
    global $wpdb;

    $today = getdate();
    $year = $today['year'];
    $month = $today['mon'];
    $day = $today['mday'];

    $count = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COUNT(ID) FROM $wpdb->posts
            WHERE post_type = 'attachment'
            AND post_mime_type LIKE 'video%%'
            AND YEAR(post_date) = %d
            AND MONTH(post_date) = %d
            AND DAY(post_date) = %d",
            $year, $month, $day
        )
    );

    return '<div class="addo40px addocenter">' . $count . '</div>';
}
add_shortcode( 'videoattachmentcounttoday', 'count_videos_attachments_today' );

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>