在Wordpress中显示标题中的发布日期

时间:2016-12-07 19:47:48

标签: wordpress

我是WP的新手,我想更改门户网站上的标题显示以使用过滤器在括号中显示帖子日期?我该怎么做 ? 当我尝试这个(@Dre的解决方案);我也可以通过顶级菜单约会:

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

1 个答案:

答案 0 :(得分:1)

编辑页面模板以简单输出日期可能会更好;它更快,并使其更加明显,以后更容易找到。通过过滤器应用内容可能会更难跟踪 内容的来源。

话虽如此,如果您决定通过过滤器执行此操作,那么您需要添加到functions.php文件中:

/* 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);

未经测试,但应该可以使用。