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 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化