【发布时间】:2015-07-20 07:03:21
【问题描述】:
希望你能帮我解决这个问题:
我在简码函数中有几个不同帖子类型的查询。 现在我正在尝试将这些查询与瞬态一起存储。 但是这些瞬态需要为调用短代码的每个页面有一个唯一的名称。
$trans_posts_golfcourse_ = 'trans_posts_golfcourse_'.$landingpage;
if( false === ( $$trans_posts_golfcourse_ = get_transient( 'trans_posts_golfcourse_' ) ) ) {
$args = array (
'posts_per_page'=> 5,
'post__in' => $posts_golfcourse,
'post_type' => 'golfcourse',
'post_status' => 'publish',
'cache_results' => false,
);
$$trans_posts_golfcourse_ = new WP_Query( $args );
set_transient( 'trans_posts_golfcourse_', $$trans_posts_golfcourse_, 60*60*4 );
}
动态生成的变量名是
$$trans_posts_golfcourse_
但是作为参数,这看起来如何呢?:
get_transient( 'trans_posts_golfcourse_' )
提前致谢!
编辑:找到动态变量作为参数的解决方案 参数(字符串)的生成方式必须与变量名相同:
get_transient( 'trans_posts_golfcourse_'.$landingpage )
完整代码:
$trans_posts_golfcourse_ = 'trans_posts_golfcourse_'.$landingpage;
if( false === ( ${$trans_posts_golfcourse_} = get_transient( 'trans_posts_golfcourse_'.$landingpage ) ) ) {
$args = array (
'posts_per_page'=> 5,
'post__in' => $posts_golfcourse,
'post_type' => 'golfcourse',
'post_status' => 'publish',
'cache_results' => false,
);
${$trans_posts_golfcourse_} = new WP_Query( $args );
set_transient( 'trans_posts_golfcourse_'.$landingpage, ${$trans_posts_golfcourse_}, 60*60*4 );
}
编辑:瞬态并没有减少查询,尽管瞬态似乎被正确调用。有人有想法吗?
【问题讨论】:
-
添加你的完整循环和瞬态中的所有内容。查看this post 我已经完成了WordPress Development。请注意,您应该构建一个字符串,而不是示例中的数组,因为短代码不能返回数组,只是字符串
-
谢谢彼得!这完全正确。我昨晚通过以下方式管理它:' $transient_key = 'trans_markers_' 。 $page_id; $transient = get_transient($transient_key); if( !empty( $transient ) ) { return $transient; } ... 进行查询 ... set_transient( $out, $transient_key, $transient_time );返回 $out;'
-
您应该将其发布为答案。在 cmets 中相当无用,因为 cmets 中的代码完全不可读。 ;-)
-
是的,正如你所见,我是堆栈新手 ;)
标签: php wordpress dynamic variable-names