是否将日期添加到最近发布的小工具?

时间:2015-10-01 作者:AndrettiMilas

我很难找到合适的方法在最近发布的小部件链接下面添加日期。如果有人有代码,我将不胜感激!

1 个回复
最合适的回答,由SO网友:Pieter Goosen 整理而成

This is a default feature which by default is set not to show the post date. Here is the part of the code responsible to show/hide the post date

<?php if ( $show_date ) : ?>
    <span class="post-date"><?php echo get_the_date(); ?></span>
<?php endif; ?>

To enable the post date, just check the Display post date? checkbox

enter image description here

EDIT

Here is an idea how to change the post date format (or for that matter changing the post date to anything) for only the recent post widget

Here we will run a filter function on the get_the_date filter inside the widget_display_callback filter. We will use the parameters passed to the widget_display_callback filter to target only the recent post widget only when the show_date instance is set to true

add_filter( \'widget_display_callback\', function ( $instance, $widget_instance )
{
    if (    $widget_instance->id_base === \'recent-posts\'
         && $instance[\'show_date\']    === true
    ) {

        add_filter( \'get_the_date\', function ( $the_date, $d, $post )
        {
            // Set new date format
            $d = \'Y-m-d\';
            // Set new value format to $the_date
            $the_date = mysql2date( $d, $post->post_date );

            return $the_date;   
        }, 10, 3 );

    }
    return $instance;
}, 10, 2 );

You can use the idea above to target the post title and permalink of the post via the the_title and the post_link filters respectively in the recent posts widget. The above idea is also not just restricted to the recent post widget.

If you need anymore control over the output, I would suggest that you copy the recent posts widget to your custom plugin and then modifying it as necessary

相关推荐