Shaik
Shaik

Reputation: 930

Wordpress Get Post by its category tried wordpress article

I am trying get the post by its category in WordPress i have category section in my panel and i have added the category as English but when i try to supply that in the array is see no change when added category attribute when category_name is added it return nothing

$book = array(
    'post_type' => 'book',
    'paged'=> $paged,
     'category'         => 'English',
    'category_name'    => 'English',
     'posts_per_page'         => '12'
);

Upvotes: 0

Views: 35

Answers (3)

Wakar Ahmad Khan
Wakar Ahmad Khan

Reputation: 507

Try this

$custom_terms = get_terms('english');

foreach($custom_terms as $custom_term) {
    wp_reset_query();
    $args = array('post_type' => 'book',
        'tax_query' => array(
            array(
                'taxonomy' => 'english',  //The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces). 
                'field' => 'slug',
                'terms' => $custom_term->slug,
            ),
        ),
     );

     $loop = new WP_Query($args);
	 print_r($loop);die;
     if($loop->have_posts()) {
        echo '<h2>'.$custom_term->name.'</h2>';

        while($loop->have_posts()) : $loop->the_post();
            echo '<a href="'.get_permalink().'">'.get_the_title().'</a><br>';
        endwhile; 
     }
}

Note that The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces).

Upvotes: 0

Anatol Bivol
Anatol Bivol

Reputation: 993

Category parameters work only for default WordPress posts. With custom post types you must use tax_query.

new WP_Query( array(
    'post_type' => 'book',
    'tax_query' => array(
        array (
            'taxonomy' => 'your_custom_taxonomy_slug_here',
            'field' => 'slug',
            'terms' => 'english',
        )
    ),
) );

https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

Upvotes: 1

Alexander Z
Alexander Z

Reputation: 604

Try to use this code:

$book = array(
  'post_type'      => 'book',
  'paged'          => $paged,
  'category_name'  => 'english',
  'posts_per_page' => 12,
);
$query = new WP_Query( $book );

There is no parameter called 'category'. All category parameters:

  • cat (int) - use category id.
  • category_name (string) - use category slug.
  • category__and (array) - use category id.
  • category__in (array) - use category id.
  • category__not_in (array) - use category id.

So, if you use 'category name' query get the posts that have these categories, using category slug.

For more details see this link to Wordpress Codex

Upvotes: 0

Related Questions