Author.php上的WordPress查询无法正常工作

时间:2012-10-29 02:23:02

标签: wordpress

以下查询不适用于我的主题的WordPress author.php模板。它包含在页脚中,所有页面都是相同的页脚,查询在每个其他页面上都可以正常工作,除了author.php

  <?php if(have_posts()):?>
  <?php query_posts( array( 'post_type' => 'connect' ) ); while (have_posts()) : the_post(); ?>
  <div class="title"><?php the_title();?></div>
  <div class="logos">  
  <?php the_content();?>
  </div>
  <?php endwhile;?>
  <?php wp_reset_query(); ?>
  <?php endif;?>

我花了一个多小时试图弄清楚发生了什么,以及为什么这不起作用,但我现在感觉我正在敲打我的反对具体。为什么不工作?!

2 个答案:

答案 0 :(得分:8)

为了让我解释为什么它只在某些页面上工作,你需要了解query_posts()实际上做了什么。

query_posts()修改默认的Wordpress循环。无论你在哪个页面,总是有一个由Core初始化的默认循环。除非您打算修改该循环,否则完全停止使用query_posts()是非常不可能的。

有很多原因可以解释为什么query_posts()经常被滥用,并且它们已在许多论坛以及Wordpress Codex本身中详细说明。但那进入了一个与你的问题无关的领域。

首先,让我们来看看你的代码在做什么:

<?php if(have_posts()):?> //If the default loop finds posts....
<?php query_posts( array( 'post_type' => 'connect' ) );?> //Modify the loop to fit these new parameters

基本上,只有默认循环能够返回一组结果时,才会运行新查询。这适用于其他页面,因为默认循环通常适用于大多数情况。

它不适用于您的Author.php模板,因为无论出于何种原因,它都无法返回一组结果,然后运行修改后的查询。

那你怎么解决它?

您需要更改结构以及调用查询的方式。我不知道你的项目有多深,如果这是一个与客户相当紧张的截止日期,但我的建议是废弃所有的query_posts()调用,转而支持{{3} }

它看起来有点复杂吗?当然。但是,将它作为当前和未来任何Wordpress主题的面包和黄油,最终将为您节省大量时间和麻烦。

糟糕的方式

<?php
query_posts( array( 'post_type' => 'connect' ) );
if(have_posts()): while (have_posts()) : the_post();
?>
<div class="title"><?php the_title();?></div>
<div class="logos">  
<?php the_content();?>
</div>
<?php
endwhile;
wp_reset_query();
endif;
?>

正确的方法

<?php
$q = new WP_Query( array( 'post_type' => 'connect' ) );
if($q->have_posts()) : while($q->have_posts()) : $q->the_post;
?>
<div class="title"><?php the_title();?></div>
<div class="logos">  
<?php the_content();?>
</div>
<?php
endwhile;
wp_reset_postdata();
endif;
?>

希望这会有所帮助,祝你好运。

<强>更新

WP_Query允许您按作者查询帖子,并且您认为新WP_Query对象中提供的默认值通常会反映给定页面上的默认查询似乎是有意义的,并且可以解释您所看到的行为

由于WP_Query文档并没有真正提供一种明确搜索作者类型“any”的方法,我们可能不得不在这一点上弄脏我们的手:

$user_ids = get_users(array('who'=>'author', 'fields'=>'ID'));
$q = new WP_Query( array( 'post_type' => 'connect', 'author'=>implode(',', $user_ids) ) );

如果有帮助,请告诉我。

答案 1 :(得分:1)

尝试使用wp查询

$the_query = new WP_Query();
$the_query->query(array( 'post_type' => 'connect' ));
if ($the_query->have_posts()) : 
while($the_query->have_posts()) : $the_query->the_post();

endwhile; 
endif; 
wp_reset_postdata();

或者,如果wp_query不起作用,您也可以尝试使用 get_posts 。我很确定这可以在author.php

中使用
global $post;
$args = array( 'post_type' => 'connect' );
$posts = get_posts( $args );
foreach( $posts as $post ): setup_postdata($post); 
   //you can call the_title the_content and any other method that runs under query_posts and WP_Query
endforeach; 
相关问题