修改全局wp_query以返回最新的自定义帖子类型

时间:2011-07-07 11:22:04

标签: wordpress

我开发了一个自定义帖子类型的主题。其中一个post_types称为事件。

我不想在名为“即将发生的事件”的“页面”中显示最新事件。所以我创建了这个名为“Events”的模板文件。现在我需要修改全局wp_query,以便我返回最后一个事件。

这就是我的single.php的样子:

<?php
get_header();
setup_postdata($post);
get_page_post_content();
get_footer();
?>

在查看事件时工作正常,因为自定义帖子类型为“普通”。这是我的模板文件,应该包含最新的事件:

<?php
/*
 * Template Name: Event
*/
?>

<?php

global $wp_query;
$wp_query = new WP_Query('post_type=event&posts_per_page=1');

include 'single.php';

?>

然而,这不能按预期工作,因为我的模板的其他部分取决于“is_single()”等属性,这种情况返回false,因为查询是从页面调用的。我不知何故需要设置查询,以便更改这些属性。任何人都知道如何或如何解决这个问题?

谢谢! :d

1 个答案:

答案 0 :(得分:1)

将以下代码放在模板文件中。

<?php
/**
Template Name: Event
 */

get_header();
?>
    <div id="content" >
    <?php

    $paged = get_query_var('paged') ? get_query_var('paged') : 1;
    query_posts('post_type=event&paged='.$paged.'&posts_per_page=10');


    if (have_posts ()) :
        while (have_posts ()) : the_post(); ?>
            <div <?php post_class() ?>>
                <div class="post-title">
                    <h2 class="alignleft"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
                </div><!-- .post-title -->

                <div class="post-content">
                        <?php the_excerpt('read more');?>
                </div>
            </div><!--end of .post_class -->

            <div class="post-meta">
                <p class="alignright"><a class="readmore" title="<?php get_the_title();?>" href="<?php echo get_permalink( $post->ID );?>" rel="nofollow">Read</a></p>
                <span class="alignright comment-cnt"><?php comments_popup_link( 'No Comments', '1 Comment', '% Comments' ); ?></span>
                <div class="clear"></div>
            </div><!-- end of .post-meta -->

        <?php
        endwhile;
    endif;
    ?>
    </div>
<div class="clear"></div>
</div>
<?php get_footer(); ?>
相关问题