deepak
deepak

Reputation: 31

Want to get posts from category slug

I'm working on a project and getting same results in different category slug. Please help what I'm doing wrong here.

$act = $_POST['act'];
$args = array(
    'posts_per_page'   => 100,
    'offset'           => 0,
    'category'         => $act,
    'orderby'          => 'post_date',
    'order'            => 'DESC',
    'post_type'        => 'product',
    'taxnomy'          => 'product_cat',
    'post_status'      => 'publish'); 
$myposts = get_posts( $args );
global $product;
global $wpdb;               
foreach ($myposts as $key => $value) {
    $id = $value->ID;
echo '<li class="product type-product status-publish has-post-thumbnail first grid with-hover add-hover open-on-mobile with-border span3 featured shipping-taxable product-type-simple product-cat-accommodation-durban product-cat-accommodation-battlefields product-cat-battlefields product-cat-comfortable-accommodation-durban product-cat-comfortable-accommodation-battlefields product-cat-durban instock">';
echo '<div class="product-wrapper">';
echo '<a class="thumb" href="'.get_permalink( $id  ).'">';
$post_thumbnail_id = get_post_thumbnail_id($id);
$post_thumbnail_url = wp_get_attachment_url( $post_thumbnail_id );
echo '<img src="'.$post_thumbnail_url.'" />';
echo '</a>';
echo '<h3>'.get_the_title( $id ).'</h3>';
echo '</div></li>';

}

Upvotes: 0

Views: 2845

Answers (2)

deepak
deepak

Reputation: 31

<?php 
$slug = "category-b";
$args = array(
    'posts_per_page' => -1, 
    'tax_query' => array( 
        'relation' => 'AND', 
         array( 
            'taxonomy' => 'product_cat', 
            'field' => 'slug', 
            'terms' => $slug 
         ) 
    ), 
    'post_type' => 'product', 
    'orderby' => 'title', 
); 
$the_query = new WP_Query( $args ); 

foreach ($the_query->posts as $key => $value) {
     print_r($value->ID); 
} 
?>

Upvotes: 1

nunorbatista
nunorbatista

Reputation: 875

After careful consideration, I found the root of the problem:

  1. The category needs to be an ID, quoting Wordpress:

Note: The category parameter needs to be the ID of the category, and not the category name.

Note: The category parameter can be a comma separated list of categories, as the get_posts() function passes the 'category' parameter directly into WP_Query as 'cat'.

Note: The category_name parameter needs to be a string, in this case, the category name.

  1. Taxonomy is not well written, is "taxonomy" and not "taxnomy". Also, you can remove it from there as it's not filtering anything.

Upvotes: 0

Related Questions