duanbeng1923 2015-10-21 13:33
浏览 48
已采纳

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

Is it possible to run a function that always queries for a related post and saves that array to a variable in 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' );
} }

Then I just wanted to use the $the_query "object?" and use it as if I had done a regular new WP_Query() from within the template file? Calling it out with familiar hook like:

echo $the_query->post_title

Tried the simplest thing first: <?php print_r($the_query);?>

Been unsuccessful in returning the array of variables.

I considered that it was because the variable wasn't globally set, but I thought the advantage of the return command was to essentially store the results for use if the function is activated.

  • 写回答

1条回答 默认 最新

  • dqybeh2884 2015-10-21 13:59
    关注

    The function returns the Variable and not make it global. If you want to access the result you have to assign the result of the function to a variable.

    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');
        }
    }
    

    and where you want to use the result of the function:

    $the_query = the_query_vars();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试