SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict
    Join Date
    May 2010
    Posts
    229
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    wp_query with category and custom post type

    I want to create a wp_query to list the post titles of posts from category X, in ascending order based on a custom field I inputted in each post called "eventdate".

    PHP Code:
    <?php
          $loop 
    = new WP_Query( array(
                
    'showposts' => 5,
                
    'post_type' => array('eventdate'),
                
    'category_name' => X,
                )
                );
          while ( 
    $loop->have_posts() ) : $loop->the_post(); ?>
           <div>
                  <h2><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
            </div>
      <?php endwhile; ?>
    I tried the following code but it didnt work. any idea how to fix? please advise. thanks in advance!

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,082
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi,

    There are a couple of things wrong with your code.
    In the WP_Query, 'post_type' refers to a custom post type, yet if I understand you correctly, you are trying to fetch posts by category instead.
    Also, the parameter 'category_name' expects a string.
    My suggestion would be to fetch the posts by category, then to order them using 'meta_key' and ASC or DESC as appropriate.
    This should do what you want:

    Code PHP:
    <?php 
      $loop = new WP_Query( array( 
        'showposts' => 5, 
        'category_name' => 'X',
        'orderby' => 'meta_value',
        'meta_key' => 'eventdate',
        'order' => ASC) 
      ); 
      while ( $loop->have_posts() ) : $loop->the_post(); ?> 
      <div> 
        <h2><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2> 
      </div> 
    <?php endwhile; ?>

  3. #3
    SitePoint Addict
    Join Date
    May 2010
    Posts
    229
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    bingo! thank you.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •