Wordpress,短代码刷新页面后获得旧值

时间:2018-06-04 06:41:53

标签: php wordpress plugins shortcode

我有打印最新消息的短代码。

add_shortcode('latest_news', 'news_articles');

function news_articles($atts){

    $options = get_option('my_settings');

    var_dump(date('Y m d H:i:s', $options['last_update']));

    ob_start();

    if($options['articles'] != ''){
        include 'includes/list-shortcode.php';
    }

    $content = ob_get_clean();

    return $content;
}

我希望每x分钟自动更新最新消息。所以我创建了js文件,在jquery之后使用动作updateNews

进入头部
jQuery(document).ready(function($){
    var data = {
        action: 'updateNews'
    };

    $.post(window.news.ajax_url, data, function (res) {}, 'json');

});

动作本身在php文件中

add_action('wp_ajax_updateNews', 'updateNews_ajax');
add_action('wp_ajax_nopriv_updateNews', 'updateNews_ajax');
function updateNews_ajax(){

    $options = get_option('my_settings');
    $time_now = time();
    $time_diff = $time_now - $options['last_update'];

    if($time_diff > $options['update']){    // $options['update'] - update after x minutes
        $articles = get_results();

        $optionsNew['last_update'] = time();
        $optionsNew['articles'] = $articles;
        $optionsNew['update'] = $options['update'];

        update_option('my_settings', $optionsNew);
    }

    echo json_encode(['res'=>'ok']);
    wp_die();
}

x分钟后,我刷新页面,页面中没有任何更改。只有在单击两次刷新按钮后,才会在页面中更新信息。刷新一次后,它会在db中更新信息,但短代码仍在使用旧值。

1 个答案:

答案 0 :(得分:0)

试试这个

update_option('my_settings', $optionsNew);

由于代码中存在typeo mistale。