我正在尝试在页面模板上显示自定义帖子类型列表。当我查看页面时,我看到实际页面重复,而不是看到不同的帖子。例如,如果我有5个帖子,则实际页面(头部内容页脚)将显示五次。似乎查询工作......在某种程度上但我不确定是什么问题。这是模板代码:
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class('page'); ?>>
<h1><?php the_title(); ?></h1>
<article>
<div class="post-content page-content">
<?php the_content(); ?>
<?php wp_link_pages('before=<div class="pagination">&after=</div>'); ?>
</div><!--.post-content .page-content -->
</article>
</div><!--#post-# .post-->
<?php endwhile; ?>
<!-- Start search result code -->
<?php
//query_posts('post_type=listing&orderby=title&order=ASC&posts_per_page=9999');
?>
<?php
$querystr = "
SELECT *
FROM $wpdb->posts, $wpdb->postsmeta
WHERE wp_posts.ID = wp_postmeta.post_id
AND wp_postmeta.meta_key = 'listing_open'
AND wp_postmeta.meta_value = 'YES'
AND wp_posts.post_status = 'publish'
AND wp_posts.post_type = 'listing'
ORDER BY post_title
";
$pageposts = $wpdb->get_results($querystr, OBJECT);
if ($pageposts):
foreach ($pageposts as $postdata):
setup_postdata($postdata);
?>
<?php //if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php include_once(get_bloginfo('template_url')."/layout-listings.php?id=".$postdata->ID); ?>
<?php //endwhile; endif; rewind_posts(); wp_reset_query(); ?>
<?php
endforeach;
endif;
?>
<?php
$querystr = "
SELECT *
FROM $wpdb->posts, $wpdb->postmeta
WHERE wp_posts.ID = wp_postmeta.post_id
AND wp_postmeta.meta_key = 'listing_open'
AND wp_postmeta.meta_value = 'NO'
AND wp_posts.post_status = 'publish'
AND wp_posts.post_type = 'listing'
ORDER BY post_title
";
$pageposts2 = $wpdb->get_results($querystr, OBJECT);
if ($pageposts2):
foreach ($pageposts2 as $postdata2):
setup_postdata($postdata2);
?>
<?php //if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php include_once(get_bloginfo('template_url')."/layout-listings.php?id=".$postdata2->ID); ?>
<?php //endwhile; endif; rewind_posts(); wp_reset_query(); ?>
<?php
endforeach;
endif;
?>
<!-- End search result code -->
答案 0 :(得分:0)
该代码中有几件事要参与。
include_once
用法您必须在磁盘中包含文件的路由,而不是公共URL。类似的东西:
include_once(get_stylesheet_directory() . "/layout-listings.php");
或者更好的是,使用get_template_part
:
get_template_part('layout', 'listings');
get_posts
or new WP_Query
而不是进行显式查询您应该尝试仅在没有其他选择时使用查询,而是使用get_posts:
$pageposts2 = new WP_Query(array(
'meta_key' => 'listing_open',
'meta_value' => 'NO'
));
上面的代码将获得您需要的结果。
使用wordpress功能的优点:
如果查询过于复杂WP_Query,您还应该考虑阅读protecting queries against SQL injection attacks
**小心使用query_posts
您已对if
,while
,the_post
,rewind_posts
和wp_reset_query
函数进行了评论。