当通过短代码添加新内容时如何自动更新WordPress发布日期(动态内容更改)

问题描述 投票:0回答:1

我正在使用 WordPress 插件短代码在单个帖子中添加特定类别的最近文章的所有列表,并且当通过短代码添加新内容时,我试图更改我的 WP 帖子日期和时间,如下图所示。

我在 2 天前创建了这篇文章,但是这篇文章中的内容通过短代码添加,就像每 10 分钟、20 分钟一样......现在我想根据上次内容(通过短代码添加的帖子文章)的时间来更新这篇文章的日期和时间这是 10 分钟前的事。

我有这种类型的多个帖子,我将在其中添加不同的类别内容并通过不同的短代码添加所有帖子,我想根据其 DOM 内容动态更改或通过短代码更新来更新所有帖子日期和时间。所以我需要一个通用代码或方法来在我的整个 WordPress 网站上实现这一目标。

但是,为了在一篇文章中获得此内容,我尝试通过此 php 代码添加到我的主题中

function.php
,但它仍然不起作用。

    function update_post_date_from_shortcode($post_id) {
if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) {
    return;
}

// Check if the post contains the specific shortcode
$post_content = get_post_field('post_content', $post_id);
if (strpos($post_content, '**[my_shortcode]**') !== false) {
    // Update the post date to the current time
    wp_update_post(array(
        'ID' => $post_id,
        'post_date' => current_time('mysql', true),
        'post_date_gmt' => current_time('mysql', true),
    ));
}
}

编辑:我也尝试过这个,但仍然不起作用:

function update_post_date_on_shortcode($atts) {
global $post;
$post->post_date = date('Y-m-d H:i:s');
$post->post_date_gmt = get_gmt_from_date($post->post_date);
wp_update_post($post);
}
add_shortcode("[my_shortcode]", 'update_post_date_on_shortcode');

有哪位专家知道我如何才能实现这一目标?我需要在这段代码中进行哪些更改?

php wordpress
1个回答
0
投票

很难理解你的目标。特别是为什么每次呈现此短代码时都应更新这些帖子的发布日期。

您似乎正在使用

WP Masonry & Infinite Scroll
,它似乎没有提供自定义挂钩来轻松访问循环中的每个
$post
。相反,您可以使用
shortcode_atts_{$shortcode}
核心 WordPress 过滤器在呈现短代码时执行一些任意操作。

add_filter('shortcode_atts_wmis' function ($atts) {

    // Your logic goes here

    return $atts;

});

但是,在这种情况下,

global $post;
将指代放置短代码的帖子(而不是循环中的帖子)。您可以尝试从短代码属性重建帖子列表,但是考虑到此特定短代码的可用选项数量,这样做会很笨拙且难以维护。

© www.soinside.com 2019 - 2024. All rights reserved.