I'm storing CPT products' post IDs into CPT companies' post meta (meta_key = prefix_products). As a company can have multiple products, so I'm storing them into a PHP serialized array value.
s:48:"a:3:{i:0;s:3:"334";i:1;s:3:"333";i:2;s:3:"331";}"; Where 334, 333, 331 are three post_ids of post type products.
I need to get the post_id of the CPT companies where the product id (post_id of CTP products) is equal to 331 (dynamic - can be any value). It should compare with meta_value of the meta_key prefix_products.
I can get post_id using a meta_value, but I'm stuck where the data is stored as serialized. :(
What I did so far, can't get to the solution:
function get_company_of_the_product( $product_id ) { global $project_prefix; $prod_meta_key = $project_prefix .'products'; $companies = get_posts( array( 'post_type' => 'companies', 'post_status' => 'publish', 'meta_key' => $prod_meta_key ) ); $products_array = array(); foreach ( $companies as $company ) { $products = get_post_meta( $company->ID, $prod_meta_key, true ); $products_array[$company->ID] = unserialize( $products ); //if( in_array( $product_id, $products_array ) ) return $company->ID; //I know it's wrong } var_dump($products_array); } Is this the way, or am I missing something seriously easy? How can I solve the riddle?
meta_keyfor storing different singe values. I also would considere to use a meta field for each product to store the company ID which the product belongs to, so you can get the product ID based on company ID easily.