Home / Widgets / Dynamic Copyright Date
Duplicate Snippet

Embed Snippet on Your Site

Dynamic Copyright Date

Code Preview
php
<?php
if ( ! function_exists( 'wpb_copyright' ) ) {
    function wpb_copyright() {
        // Cache the output so we don't have to run the query on every page load.
        $output = get_transient( 'wpb_copyright_text' );
        if ( false !== $output ) {
            // Return the cached output.
            return $output;
        }
        global $wpdb;
        $copyright_dates = $wpdb->get_results(
            "SELECT YEAR(min(post_date_gmt)) AS firstdate, YEAR(max(post_date_gmt)) AS lastdate FROM $wpdb->posts WHERE post_status = 'publish'"
        );
        $output          = '';
        if ( $copyright_dates ) {
            $output = '© ' . $copyright_dates[0]->firstdate;
            if ( $copyright_dates[0]->firstdate !== $copyright_dates[0]->lastdate ) {
                $output .= '-' . $copyright_dates[0]->lastdate;
            }
            // Set the value as a transient so we only run the query 1x per day.
            set_transient( 'wpb_copyright_text', $output, DAY_IN_SECONDS );
        }
 
        return $output;
    }
}
 
echo wpb_copyright();

Comments

Add a Comment