WordPress.org

Ready to get started?Download WordPress

Forums

WP Query doesn't show custom posts in custom template (5 posts)

  1. lxm7
    Member
    Posted 1 year ago #

    So I've read that WP_query is a better option to use than query_posts in using to query a list of posts.

    But I'm unable to get it to work with the code below

    <?php $args = array('post-type' => 'sermons', 'meta_query' => array(array('key' => '_wp_page_template', 'value' => 'my_template.php'))); ?>
    <?php $sermonposts = new WP_Query( $args ); ?>
    	<?php while ( $sermonposts->have_posts() ) : $sermonposts->the_post(); ?>
    		  <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
        		<p><?php echo get_the_excerpt(); ?></p>
    <?php endwhile; ?>

    But the 2nd block of code does work:

    <?php query_posts(array( 'post_type' => 'sermons') ); ?>
    <?php while (have_posts()) : the_post(); ?>
        <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
        <p><?php echo get_the_excerpt(); ?></p>
    <?php endwhile;?>

    These blocks of code reside in a custom template thats not currently being selected in the CMS on the right hand side drop down(when it is the WP_query still doesnt work) and this is pulled in from the default page.php with conditional if(is_page) underneath the default code with the following line

    <?php get_template_part('page-posts-display-template', get_post_format() );?>

    Any ideas why the recommended option isn't working in this case?
    Thanks in advance.

  2. Ravinder Kumar
    Member
    Posted 1 year ago #

    <?php $args = array('post_type' => 'sermons'); ?>
    <?php $sermonposts = new WP_Query( $args ); ?>
    	<?php while ( $sermonposts->have_posts() ) : $sermonposts->the_post(); ?>
    		  <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
        		<p><?php echo get_the_excerpt(); ?></p>
    <?php endwhile; ?>

    try it

  3. lxm7
    Member
    Posted 1 year ago #

    I tried this before i added meta querys, and template values and didnt work.

  4. Ravinder Kumar
    Member
    Posted 1 year ago #

    just check ('post-type') in your code and mine ('post_type')
    try it

  5. lxm7
    Member
    Posted 1 year ago #

    Aaaah shit!. Sorry. Thanks for your reply buddy.

Topic Closed

This topic has been closed to new replies.

About this Topic