我已经创建了一个autosuggest数组,希望将其存储在瞬态中。我的代码如下所示:
<?php
// Get any existing copy of our transient data
$suggest = get_transient(\'suggest\');
if ( false === ( $suggest = get_transient( \'suggest\' ) ) ) {
// It wasn\'t there, so regenerate the data and save the transient
$suggest = array();
// We will loop a custom post type and fetch custom meta from each post to be added into the autosuggest array
$query = new WP_Query( array( \'post_type\' => \'my_custom_post_type\', \'posts_per_page\' => -1, ) );
$posts = $query->posts;
foreach($posts as $post) {
$value1 = get_post_meta( get_the_ID() , \'_town\', true );
$value2 = get_post_meta( get_the_ID() , \'_quarteroftown\', true );
$value3 = get_post_meta( get_the_ID() , \'_street_name\', true );
$value4 = get_post_meta( get_the_ID() , \'_supplier_postcode\', true );
if (!in_array($value1, $suggest))
{
$suggest[] = $value1;
}
if (!in_array($value2, $suggest))
{
$suggest[] = $value2;
}
if (!in_array($value3, $suggest))
{
$suggest[] = $value3;
}
if (!in_array($value4, $suggest))
{
$suggest[] = $value4;
}
}
set_transient( \'suggest\', $suggest, HOUR_IN_SECONDS );
}; ?>
如果我没有设置一个瞬态,而只是使用$suggest对象,那么所有值都正确地存在于数组中。当我添加如上所示的瞬态功能时,瞬态中只有$value1和$value2字符串,没有\\u streetname或\\u supplier\\u postcode。
给我的wtf火上浇油:如果我每次都简单地命令删除瞬态,它就会开始工作!请参见下面的代码:
<?php
// Get any existing copy of our transient data
delete_transient(\'suggest\'); // ADDING THIS AND FORCING REGEN OF TRANSIENT EVERY TIME FIXES THE PROBLEM!
$suggest = get_transient(\'suggest\');
我不知所措。到底是什么导致了这种行为?
最合适的回答,由SO网友:Qaisar Feroz 整理而成
你正在使用get_the_id()
template tag 没有适当的loop.
您的代码应该是这样的
<?php
// Get any existing copy of our transient data
$suggest = get_transient(\'suggest\');
if ( false === ( $suggest = get_transient( \'suggest\' ) ) ) {
// It wasn\'t there, so regenerate the data and save the transient
$suggest = array();
// We will loop a custom post type and fetch custom meta from each post to be added into the autosuggest array
$query = new WP_Query( array( \'post_type\' => \'my_custom_post_type\', \'posts_per_page\' => -1, ) );
$posts = $query->posts;
foreach($posts as $the_post) {
$value1 = get_post_meta( $the_post->ID , \'_town\', true );
$value2 = get_post_meta( $the_post->ID , \'_quarteroftown\', true );
$value3 = get_post_meta( $the_post->ID , \'_street_name\', true );
$value4 = get_post_meta( $the_post->ID , \'_supplier_postcode\', true );
if (!in_array($value1, $suggest))
{
$suggest[] = $value1;
}
if (!in_array($value2, $suggest))
{
$suggest[] = $value2;
}
if (!in_array($value3, $suggest))
{
$suggest[] = $value3;
}
if (!in_array($value4, $suggest))
{
$suggest[] = $value4;
}
}
set_transient( \'suggest\', $suggest, HOUR_IN_SECONDS );
}; ?>