我试图在自定义查询上设置一个瞬态,但它似乎不起作用。每次我刷新页面时,它仍然会每次显示不同的帖子。
在阅读了transients api之后,我开始相信设置transient会将我的第一个查询存储为与它查询的帖子完全相同的帖子,并在下次再次显示它们,而不必再次执行整个查询。
是我错了还是我做错了什么?
这是我的全部UPDATED 查询:
if(isset($_COOKIE[\'myCookie\']) && $_COOKIE[\'myCookie\'] == $f_a){
// Check for transient. If none, then execute WP_Query
if ( false === ( $akerargs = get_transient( \'county_query\' ) ) ) {
$akerargs = array(
\'posts_per_page\' => 4,
\'nopaging\' => false,
\'order\' => \'ASC\',
\'orderby\' => \'rand\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'Count\',
\'field\' => \'slug\',
\'terms\' => $f_a,
)
)
);
// Put the results in a transient. Expire after 10 minutes.
set_transient( \'county_query\', $akerargs, 10 * MINUTE_IN_SECONDS );
}
ob_start();?>
<div class="container-fluid">
<?php
$akerquery = new WP_Query( $akerargs );
?>
<div class="row">
<?php if ( $akerquery->have_posts() ) {
while ( $akerquery->have_posts() ) {
$akerquery->the_post();
?>
<div class="col-6 mt-4">
<a href="<?php the_field(\'county_link\'); ?> ">
<img src="<?php echo the_field(\'county_img\'); ?>" />
</a>
</div>
<?php
}
$akerquery->wp_reset_postdata();
} else {
echo \'Oops! Something went wrong.\';
}
?>
</div>
</div>
<?php
return ob_get_clean();
UPDATE
我现在已经尝试了多种可能的解决方案,但仍然不起作用。根据WordPress codex,这是如何实现的:
// Check for transient. If none, then execute WP_Query
if ( false === ( $featured = get_transient( \'foo_featured_posts\' ) ) ) {
$featured = new WP_Query(
array(
\'category\' => \'featured\',
\'posts_per_page\' => 5
));
// Put the results in a transient. Expire after 12 hours.
set_transient( \'foo_featured_posts\', $featured, 12 * HOUR_IN_SECONDS );
} ?>
// Run the loop as normal
这就是我现在尝试的:
if(isset($_COOKIE[\'myCookie\']) && $_COOKIE[\'myCookie\'] == $f_a){
// Check for transient. If none, then execute WP_Query
if ( false === ( $akerargs = get_transient( \'county_query\' ) ) ) {
$akerargs = array(
\'posts_per_page\' => 4,
\'nopaging\' => false,
\'order\' => \'ASC\',
\'orderby\' => \'rand\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'Count\',
\'field\' => \'slug\',
\'terms\' => $f_a,
)
)
);
$akerquery = new WP_Query( $akerargs );
// Put the results in a transient. Expire after 10 minutes.
set_transient( \'county_query\', $akerargs, 10 * MINUTE_IN_SECONDS );
}
// Run the loop as normal
但它仍然运行查询并获取新的帖子,而不是保存在瞬态中首先查询到的4篇帖子。