将新的 WP 查询保存到数组以供 single.php 使用的函数

Function that saves new WP Query to array for use on single.php

是否可以 运行 始终查询相关 post 并将该数组保存到 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 "object?" 并像我在模板文件中完成常规 new WP_Query() 一样使用它?使用熟悉的钩子调用它,例如:

echo $the_query->post_title

先尝试最简单的: <?php print_r($the_query);?>

返回变量数组失败。

我认为这是因为变量不是全局设置的,但我认为 return 命令的优点是本质上是存储结果,以便在功能被激活时使用。

函数returns变量而不是全局变量。 如果要访问结果,则必须将函数的结果分配给变量。

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();