Richard
Richard

Reputation: 14625

Modify global wp_query to return latest of custom post type

I have developed a theme with custom post types. One of those post_types is called events.

I wan't to display the latest event in a "page" called "upcoming event". So i created this template file called "Events". Now i need to modify the global wp_query so that i return this last event.

This is how my single.php looks like:

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

Works fine when viewing event as custom posts types "normal". And this is my template file which should contain the latest event:

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

<?php

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

include 'single.php';

?>

However this does not work as expected since i have other parts of my template depending on properies like "is_single()" which is this case returns false, since the query is called from a page. I somehow need to set the query so those properies are changed. Anyone knows how or how i should solve this?

Thanks!! :D

Upvotes: 1

Views: 6263

Answers (1)

Santosh S
Santosh S

Reputation: 4345

Put below code in your template file.

<?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(); ?>

Upvotes: 1

Related Questions