Eric Brockman
Eric Brockman

Reputation: 854

Having trouble displaying posts from only one category in Wordpress

I'm having difficulty pulling only the desired category into an archive page on Wordpress. My code is below, I thought by defining get-category-by-slug this would work, but instead its pulling all of the post from every category into the page.

<?php
    $category = get_category_by_slug('weddings');
    $args = array(
                 'post_type' => 'elp_projects',
                 'posts_per_page' => 12,
                 'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1)
                 );
    query_posts($args);
    $x = 0;

    while (have_posts()) : the_post();
?>

Any ideas on how to fix this would be appreciated.

I've also tried these combinations with no luck.

<?php
    $category = get_category_by_slug('weddings');
    $args = array(
                 'post_type' => 'elp_projects',
                 'posts_per_page' => 12,
                 'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1)
                 );
    $query = new WP_Query( 'category_name=weddings' );
    $x = 0;

    while (have_posts()) : the_post();
?>

and

<?php $query = new WP_Query( 'category_name=weddings' ); ?>

and

<?php
    $args = array(
                 'post_type' => 'elp_projects',
                 'posts_per_page' => 12,
                 'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1)
                 );
    $query = new WP_Query( 'category_name=weddings' );
    $x = 0;

    while (have_posts()) : the_post();
?>

Upvotes: 0

Views: 5200

Answers (1)

David Chase
David Chase

Reputation: 2073

Please do not use query_posts its not the best way to query data its a last resort if you will.

Instead use WP_Query to get posts from one category just do $query = new WP_Query( 'category_name=staff' ); refer to this page for more information on how to get posts from one category using WP_Query.

EDITED Try this

$the_query = new WP_Query( array( 
  'post_type' => 'page',
  'orderby' => 'date',
  'category_name' => 'wedding', //name of category by slug
  'order' => 'DESC',
  'posts_per_page' => )); // how many posts to show

  // Put into the loop
  while ( $the_query->have_posts() ) :
   $the_query->the_post();
   echo '<li>' . get_the_title() . '</li>';
  endwhile;

  // Restore original Post Data if needed
  wp_reset_postdata();

Upvotes: 2

Related Questions