函数,用于将新的WP查询保存到数组,以便在single.php上使用
是否可以运行一个始终查询相关帖子并将该数组保存到Wordpress中的变量的函数函数,用于将新的WP查询保存到数组,以便在single.php上使用,php,wordpress,function,object,return,Php,Wordpress,Function,Object,Return,是否可以运行一个始终查询相关帖子并将该数组保存到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
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' );
} }
然后我只想使用$thew_query
“object?”并像在模板文件中执行常规newwp_query()
一样使用它?用熟悉的钩子喊出来,比如:
echo$the\u query->post\u title
先尝试最简单的事情:
未能返回变量数组
我认为这是因为变量没有全局设置,但我认为
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();
函数返回变量,但不使其成为全局变量。 如果要访问结果,必须将函数的结果指定给变量
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();
谢谢你的及时回复。当我执行:
print\r(\u查询)
时,我发现它是有效的,但是当我尝试从数组中获取一些东西时,比如:echo$the\u query->post\u title,它什么都不做。我在这里做错了什么?你用得像文件一样吗!?包括循环等等!?谢谢你的及时回复。当我执行:print\r(\u查询)
时,我发现它是有效的,但是当我尝试从数组中获取一些东西时,比如:echo$the\u query->post\u title,它什么都不做。我在这里做错了什么?你用得像文件一样吗!?包括循环等等!?