Home > Software design >  How to get information about all WooCommerce products without choosing a category?
How to get information about all WooCommerce products without choosing a category?

Time:08-12

I made a category selection section that can be used to specify the woocommerce product category and then display the products of that category.

$args = array(
    'post_type' => 'product',
    'numberposts' => -1,
    'post_status' => 'publish',
    'fields' => 'ids',
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field' => 'term_id',
            'terms' => intval($_POST['category']),
            'operator' => 'IN'
        )
    ));
$id_posts = get_posts($args);

But I want to display all products when a category is not selected.How do I value 'terms' to achieve my goal?

CodePudding user response:

you can define a function that checks all your categories in order and then gives you the ID of the categories. Now you can put these ideas in terms.

function get_all_ID_category()
{
 $args = array(
    'taxonomy' => "product_cat",
    'number' => 0,
    'orderby' => 'name',
    'order' => 'ASC',
 );
$product_categories = get_terms($args);
$product_cat = [];
foreach ($product_categories as $pc) {
    $int_pc=$pc->term_id;
    $product_cat[] = $int_pc;
}
return $product_cat;
}

function get_all_posts_category()
{
$args = array(
    'post_type' => 'product',
    'numberposts' => -1,
    'post_status' => 'publish',
    'fields' => 'ids',
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'fields' => 'ids',
            'terms' => get_all_ID_category(),
            'operator' => 'IN'
        )
    ));
return get_posts($args);
}
  • Related