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
$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!
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:
<?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; ?>