I've created a custom field which can have single or multiple products added to it, however i'm struggling to pull the information back out of the field using meta_query. Essentially i'm after a list of product that have product_cat 'challenge-packs' and have the current product ID saved into 'badge_link'.
Custom Field Create
add_action( 'woocommerce_product_options_related', 'ppf_custom_fields_add_linked_badges' );
function ppf_custom_fields_add_linked_badges() {
if(has_term('free-resources' , 'product_cat' , get_queried_object_id())){
?>
<p class="form-field">
<label for="badge_link">Linked Badges</label>
<select class="wc-product-search" style="width: 50%" id="badge_link" name="badge_link[]" multiple="multiple" data-placeholder="Search for a product">
<?php
$badge_link_ids = get_post_meta( $_GET['post'], 'badge_link', true );
$product_ids = ! empty( $badge_link_ids ) ? array_map( 'absint', $badge_link_ids ) : null;
if ( $product_ids ) {
foreach ( $product_ids as $product_id ) {
$product = get_product( $product_id );
$product_name = woocommerce_get_formatted_product_name( $product );
echo '<option value="' . esc_attr( $product_id ) . '" selected="selected">' . esc_html( $product_name ) . '</option>';
}
}
?>
</select>
</p>
<?php
}
}
Custom Field Save
add_action('woocommerce_process_product_meta', 'ppf_custom_fields_save');
function ppf_custom_fields_save( $product ) {
update_post_meta( $product, 'badge_link', $_POST['badge_link'] );
}
Custom Field Query
$challenge_packs = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'challenge-packs'
)
),
'meta_query' => array(
array(
'key' => 'badge_link',
'value' => get_queried_object_id(),
'compare' => 'IN',
)
)
);
$latest = new WP_Query($challenge_packs);
I can definitely get some products to return when I remove value and insert 'EXISTS' into compare so I know the field is populated.
Any help would be appreciated :)