Many to many relationship for variable products

a. If your fine with a plugin dependency, ACF has this kind of functionality built in with the “Relationship” field.

Relationship: https://www.advancedcustomfields.com/resources/relationship/

Reverse Query: https://www.advancedcustomfields.com/resources/querying-relationship-fields/


b. If you want to do this with just WP core, you would use custom fields.

First, on the child product, store the IDs of the product pages it should show on:

enter image description here

Next, on the “Parent” product pages, make a wordpress meta_query, looking for ‘show_on’:

<?php 
$args = array
(
    'post_type'  => 'page',
    'meta_query' => array
    (
        array
        (
            'key'     => 'show_on',
            'value'   => get_the_ID(),
            'compare' => '=',
        ),
    ),
);

$product_query = new WP_Query( $args );
if($product_query->have_posts()):
    while($product_query->have_posts()): $product_query->the_post();
        echo get_the_title();
    endwhile; wp_reset_postdata();
endif;

WP_Query: https://codex.wordpress.org/Class_Reference/WP_Query

Meta_Query: https://codex.wordpress.org/Class_Reference/WP_Meta_Query