wordpress

Display the post date in title in Wordpress


I am very new in WP, I want to change the title display on the portal to show also the post date in brackets using a filter ? how can I do it ? when I try this (solution of @Dre) ; I get also date with the top menu:

function my_add_date_to_title($title, $id) {
    $date_format = get_option('date_format');
    $date = get_the_date($date_format, $id); // Should return a string
    return $title . ' (' . $date . ')';
}
add_filter('the_title','my_add_date_to_title',10,2);

enter image description here


Solution

  • You'd probably be better off editing your page templates to simply output the date; it's quicker and makes it much more obvious and easier to find later on. Apply content via filters can make it harder to tracker down where content is coming from.

    Having said that, if you're determined to do it via filters, here's what you'd need to add to your functions.php file:

    /* Adds date to end of title 
     * @uses Hooked to 'the_title' filter
     * @args $title(string) - Incoming title
     * @args $id(int) - The post ID
     */
    function my_add_date_to_title($title, $id) {
    
        // Check if we're in the loop or not
        // This should exclude menu items
        if ( !is_admin() && in_the_loop() ) {
    
            // First get the default date format
            // Alternatively, you can specify your 
            // own date format instead
            $date_format = get_option('date_format');
    
            // Now get the date
            $date = get_the_date($date_format, $id); // Should return a string
    
            // Now put our string together and return it
            // You can of course tweak the markup here if you want
            $title .= ' (' . $date . ')';
         }
    
        // Now return the string
        return $title;
    }
    
    // Hook our function to the 'the_title' filter
    // Note the last arg: we specify '2' because we want the filter
    // to pass us both the title AND the ID to our function
    add_filter('the_title','my_add_date_to_title',10,2);
    

    Not tested, but should work.