1

I try to get the value of WooCommerce custom field from an array of product ID. No luck, I'm on the custom page not on the woocommerce loop.

tried this: $productArray1 is a list of product ID (and it's working)

global $wpdb;
global $product;

foreach ($productArray1 as $value)
{
    $querystr = "
    SELECT meta_value
    FROM $wpdb->postmeta.meta_key
    WHERE $wpdb->postmeta.meta_key = 'product_cip'
    AND $wpdb->posts.$product->ID=$value
    ORDER BY meta_value DESC
    ";

    $productsCIP = $wpdb->get_results($querystr, OBJECT);

    if ( ! $productsCIP ) {
        $wpdb->print_error();
    }
    else {
        echo $productsCIP;
    }
};

I can get all product with the same customfield like this :

$products = wc_get_products( array( 'product_cip' => '3337875548519' ) );
echo 'PRODUCT WITH SAME CIP (TOTAL : '.count($products).')<br>';

But I need to find 'product_cip' by product ID. Any clue?

Thanks for the help.

2 Answers 2

1

If you look for all products with same 'product_cip' value try this:

$a=array(
    'post_type'      => 'product',
    'post_status'    => 'publish',
    'posts_per_page' => - 1,
    'meta_query'     => array(
        array(
            'key'    => 'product_cip',
            'value'  => 'some value',
            'compare'=> '='
        )
    ),
    'fields' => 'ids'
);
$b=get_posts($a);
echo count($b);

if you have get all products data

$products_array=array();
foreach($b as $v){
    $_product=wc_get_product($v);
    echo $_product->get_name().',';
    $products_array[]=$_product;
}
1
  • Perfect blanck ! I really appreciated your help, there is lot of way to do on wp...
    – ilanb
    Commented Jan 13, 2018 at 22:46
1

Try this:

$product_obj=array();
foreach ($productArray1 as $value)
   {
    $product_obj['id']=$value;
    $product_obj['product_cip']=get_post_meta($value,'product_cip');
   }

or

foreach ($productArray1 as $value)
   {
    $product_obj['id']=$value;
    $product_obj['product_cip']=get_post_meta($value,'product_cip',true);
   }
echo 'PRODUCT WITH SAME CIP (TOTAL : '.count( $product_obj).')
';

if meta value not array.

3
  • Yes! works fine: array(2) { ["id"]=> string(5) "58240" ["product_cip"]=> array(1) { [0]=> string(13) "3323034408701" } } just last question, $productArray1 have more than one ID, how to loop over all ? and get all product_cip ? Thanks a lot blanck !
    – ilanb
    Commented Jan 13, 2018 at 16:30
  • foreach loop do it this.echo will be set after foreach(...){ } echo...
    – blanck
    Commented Jan 13, 2018 at 16:38
  • oups my mistake... thanks again blanck !! past some hours to figure out how accomplish this...
    – ilanb
    Commented Jan 13, 2018 at 16:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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