是否可以运行一个函数,总是查询相关的帖子,并将该数组保存到Wordpress中的一个变量?
if ( !function_exists( 'the_query_vars' ) ) {
function the_query_vars() {
global $post;
if ($post->post_status == 'publish') {
$args = array(
'post_type' => 'sponsor'
,'posts_per_page' => 1
,'post_belongs' => $post->ID
,'post_status' => 'publish'
,'suppress_filters' => false
);
$sponsor_query = new WP_Query($args);
return $the_query;
}
add_action( 'init', 'the_sponsor_vars' );
} }
然后我只是想使用$the_query
"对象",并使用它,就好像我从模板文件中做了一个常规的new WP_Query()
?用熟悉的钩子调用它,比如:
echo $the_query->post_title
先尝试最简单的方法:<?php print_r($the_query);?>
返回变量数组失败。
我认为这是因为变量没有全局设置,但我认为return
命令的优点是基本上存储结果,以便在激活函数时使用。
函数返回变量,但不将其设为全局。如果你想访问结果,你必须将函数的结果赋值给一个变量。
if (!function_exists('the_query_vars')) {
function the_query_vars()
{
global $post;
if ($post->post_status == 'publish') {
$args = array(
'post_type' => 'sponsor'
, 'posts_per_page' => 1
, 'post_belongs' => $post->ID
, 'post_status' => 'publish'
, 'suppress_filters' => false
);
$sponsor_query = new WP_Query($args);
return $sponsor_query;
}
add_action('init', 'the_sponsor_vars');
}
}
和要使用函数结果的地方:
$the_query = the_query_vars();