如何在WordPress中实现自定义文章时间戳功能?

玖比肆 WordPress 38

描述如何使用WordPress代码实现自定义文章时间戳功能的方法和注意事项。

回复

共1条回复 我来回复
  • 玖比肆的头像
    玖比肆 评论

    要在WordPress中实现自定义文章时间戳功能,需要进行以下几个步骤:

    1. 添加自定义字段:在文章编辑页面的右侧可以添加自定义字段,可以把自定义的时间戳以指定名称(例如my_custom_timestamp)添加到文章中。在文章中添加自定义时间戳可以使用add_post_meta()函数。

    2. 修改显示文章时间戳的模板代码:修改模板文件single.php中用于显示文章时间的PHP代码,现在需要获取自定义时间戳作为输入,并将其格式化为时间。

    3. 添加CSS样式(可选):对于自定义时间戳,可以使用CSS样式进行修饰。

    值得注意的是,在添加自定义时间戳之前,最好备份文件,以便可以轻松地恢复更改(建议使用版本控制系统)。引入代码时,需要注意与主题的兼容性和不影响其他的功能。同时,务必列出使用的任何外部库的许可证。

    下面是一个简单的代码示例,可以从functions.php文件中获取自定义时间戳并将其显示在文章的页面模板中:

    ~~~ php
    //获取自定义时间戳
    function get_custom_timestamp($post_id) {
    $custom_timestamp = get_post_meta($post_id, 'my_custom_timestamp', true);
    if (empty($custom_timestamp)) {
    return false;
    }
    return intval($custom_timestamp);
    }

    //替换时间戳
    function replace_post_date_with_custom($time, $format, $timezone) {
    if (!is_single()) {
    return $time;
    }
    global $post;
    $custom_timestamp = get_custom_timestamp($post->ID);
    if (!$custom_timestamp) {
    return $time;
    }
    $date = date_i18n($format, $custom_timestamp);
    return $date;
    }

    //替换时间格式
    function replace_post_date_format_with_custom($date_format) {
    global $post;
    $custom_timestamp = get_custom_timestamp($post->ID);
    if (!$custom_timestamp) {
    return $date_format;
    }
    $new_format = 'M, j Y g:i a';
    return $new_format;
    }

    //添加样式
    function add_custom_css() {
    echo '

    ';
    }

    add_action('wp_head', 'add_custom_css');

    //替换时间戳
    add_filter('get_post_time', 'replace_post_date_with_custom', 10, 3);
    add_filter('get_post_modified_time', 'replace_post_date_with_custom', 10, 3);
    add_filter('get_the_date', 'replace_post_date_with_custom', 10, 3);
    add_filter('get_the_time', 'replace_post_date_with_custom', 10, 3);

    //替换时间格式
    add_filter('pre_get_posts', 'replace_post_date_format_with_custom');
    ~~~

    此代码使用四个过滤器来替换文章页面上显示的时间戳,还添加了自定义CSS样式以将其与其他文章元素区分开来。

    2023年 5月 10日 上午9:28 0条评论
微信客服
分享本页
返回顶部
玖比肆(9Bi4)专注于帮助企业实现数字化转型,提供全方位的网站建设、网络运营、网络推广、网络营销和SEO优化等一系列数字化营销服务。