1

I have two custom post types, one is products, the other is vendors. The vendors CPT has things like name, address, and which products are sold there. The products CPT has the product name, description of the product and which vendors carry each product.

Is there a way to have each CPT update the other? So say, if I put that this vendor sells this product it will automatically update the product to say that it is sold by that vendor?

1

I would recommend against updating both custom post types in this way. Ultimately, you would be storing the same information in the database in two different ways.

Instead, pick one to be the master of this information. For example, let's pick the vendor type. For each vendor, you could store (as post metadata) the product post IDs of each product sold by that vendor. Then if you need to look up which vendors sell a particular product, you would construct a query that would search the vendors for those that sell the product.

For example, let's say that the vendor with post ID 123 sells the product with post ID 234. You would add the metadata like this:

add_post_meta(123, 'product', 234);

To find all vendors selling a particular product, your query might look like this:

global $wpdb;
$selling_vendors = $wpdb->get_col( 
    $wpdb->prepare( 
        "SELECT post_id 
        FROM $wpdb->postmeta 
        WHERE meta_key = 'product' 
        AND meta_value = %d", 
        $product_post_id
    ) 
);

$product_post_id would contain the post ID of the product you are inquiring about. $selling_vendors would give you an array of the post IDs of the vendors selling that product.

|improve this answer|||||

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.