0

I'm attempting to query Products in WooCommerce and return their IDs as an array that can be used to filter conditionally. I'm using ACF Pro to add custom fields into the product, for which I'm then using conditional code.

I spoke to my developer friend, who suggested this approach which should store the array in the $ex_id or $inc_id variable;

<?php 

query_posts( $args ); while ( have_posts() ) : the_post(); ?>

<?php if( in_array( 'yes', get_field('exclude') ) ) { ?>

<?php $ex_id[] = the_id() ;?>

<?php } else if( in_array( 'yes', get_field('include') ) ) { ?>

<?php $inc_id[] = the_id() ;?>

<?php } ;?>

<?php endwhile; wp_reset_query(); ?>

This wasn't working, so I simplified the conditional code to find that the return id was that of the front page;

<?php 

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

<?php the_id() ;?>

<?php endwhile; wp_reset_query(); ?>

If I add $args (specially; 'post_type' => 'product', 'showposts' => -1) the query works and the correct IDs are returned, only they are printed on the screen.

Does anyone know how I can query and store as a variable?

1

Couple of things - avoid query_posts, use a new query object or the get_posts function (read all about it). And the_ID() echo's the ID, use get_the_ID() instead.

However, you can save some memory and processing by simply iterating over an array of posts (i.e. not using a proper "loop" and setting up the global post), and just grab the ID directly:

$product_posts = get_posts(
    array(
        'posts_per_page' => -1,
        'post_type' => 'product',
    )
);

$ex_id  = 
$inc_id = array();

foreach ( $product_posts as $product_post ) {
    if ( in_array( 'yes', get_field( 'exclude', $product_post->ID ) ) )
        $ex_id[] = $product_post->ID;
    elseif ( in_array( 'yes', get_field( 'include', $product_post->ID ) ) )
        $inc_id[] = $product_post->ID;
}

Note how I'm passing $product_post-ID as a second argument to get_field. This is because by default ACF will use the current "global" post, so we need to tell it which post we actually want to grab data from.

  • Thank you so much @TheDeadMedic. I'd had a look at get_posts, but clearly my knowledge wasn't/isn't great enough! This looks to work perfectly though :-) Just one follow up question, if I wanted to add more conditional arrays, I would just do this as another row; $ex_id_1 = $ex_id_2 = $imc_id_1 = $inc_id_2 = array(); ...and then add the conditional in the foreach? – user1235285 May 10 '15 at 1:49
  • Yep, sounds fine :) – TheDeadMedic May 10 '15 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.