首页 > 解决方案 > 从缓存中排除短代码内容 - Wordpress

问题描述

我制作了一个短代码,可以在主页上返回新闻。我必须出示实际日期的相关新闻。如果新闻较旧,它将显示下一个。问题是页面被缓存,我的新闻简码内容也被缓存,用户看到的是过时的新闻。

我的代码在footer.php其中并使用我需要的所有信息创建一个div,然后使用一个小 js 脚本在我的主页中使用它的内容。

有没有办法从缓存中只排除这个函数/短代码?

这是我的代码functions.php

global $news;
$today = date('d-m-Y');

$args = array (
    'posts_per_page' => 100,
    'post_type' => 'news'
);

$query = new WP_Query($args);

$ids = array();
$dates = array();

if($query->have_posts()){
    while ($query->have_posts()) : $query->the_post();
        array_push($dates,get_field('end_date'));
        array_push($ids,get_the_ID());
    endwhile;
}
function getClosestEventID($date, array $dates, $last, $ids) {
    $interval               = array();
    $now                    = strtotime(date('Y-m-d'));

    foreach ($dates as $d) {
        // strtotime often has problems with d/m/y so we use d-m-y
        $d = str_replace("/", "-", $d);
        $dateTime           = strtotime($date);
        $toTime             = strtotime($d);
        if (strtotime($d) < $now) { continue 1; }
        if ($toTime < $dateTime) { continue 1; }
        $interval[$d]       = abs($dateTime - $toTime);
    }

    if (!count($interval)) {
        return $last;
    }

    asort($interval);
    $closest                = key($interval);

    $id_key = array_search(str_replace("-", "/", $closest), $dates);
    return $ids[$id_key];
}

$nearestEventID = getClosestEventID($today, $dates, end($ids), $ids);

echo  '<div class="last-event" style="display: none;">'
    . '<span class="event-title">' . get_the_title($nearestEventID) . '</span>'
    . '<span class="event-content">' . get_the_content($nearestEventID) . '</span>'
    . '<span class="event-place">' . get_field('ort', $nearestEventID) . '</span>'
    . '<span class="event-start-date">' . get_field('start_date', $nearestEventID) . '</span>'
    . '<span class="event-end-date">' . get_field('end_date', $nearestEventID) . '</span>'
    . '<span class="event-discipline">' . get_field('discipline', $nearestEventID) . '</span>'
    . '</div>';
?>

标签: phpwordpresscachingwordpress-theming

解决方案


您可以使用 Ajax 在缓存页面上加载这些动态块。 Ajax 示例 (确保也使用 _nopriv 添加该函数,以便未登录的用户看到该块)。

$( document ).ready(function() {
    loadNews();
});

function loadNews() {
    $.ajax({
        url: ajaxurl, // or example_ajax_obj.ajaxurl if using on frontend
        data: {
            'action': 'load_news',
        },
        success:function(data) {
            // output the response into the newsblock
            $("#newsblock").html(data);
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
    });  
}

您的 ajax 函数基本上可以包含当前代码的复制/粘贴以输出新闻。当用户在页面上时,您甚至可以使用间隔每分钟左右更新块: setInterval


推荐阅读