Support

Account

Home Forums General Issues Searching by taxonomy custom field

Solving

Searching by taxonomy custom field

  • Prepare to have your minds blown.

    I have a post type called retailers that uses a custom field called manufacturers. Manufacturers is a ‘Taxonomy’ custom field. However it does not assign taxonomies to the retailer itself. The Manufacturers taxonomy is a taxonomy attached to Products. I cannot share the taxonomy for many technical reasons but if I can get this to work I do not need to.

    So… A Product has a single Manufacturer. A Retailer can have many Manufacturers. On the products page, I grab the manufacturer as it is one of the product taxonomies. I then need to show which Retailers carry that manufacturer. Normally one would just do:

    		$args = array(
    			'post_type' => 'retailers',
    			'meta_key' => 'manufacturers',
    			'meta_value' => $manufacturer
    		);
        $retailers_query = new WP_Query($args);
    

    However that wont work because each retailer has multiple Manufacturers and ACF stores them as a serialized array in the post meta table as follows:

    meta_key: manufacturers
    meta_value: a:5:{i:0;s:2:"21";i:1;s:2:"44";i:2;s:2:"23";i:3;s:2:"24";i:4;s:2:"16";}

    So when running the query above will obviously not work. Any thoughts how I could do a query, that looks through a custom post type that uses the taxonomy field from ACF?

    Thanks in advance.

  • Solved it. Here is how:

    $myrows = $wpdb->get_results( "SELECT * FROM wp_postmeta WHERE meta_key = 'manufacturers' AND meta_value LIKE '%$manufacturer_id%'" );
    	
    foreach($myrows as $row){
      $retailer_ids[] = $row->post_id;
    }
    

    Then run a WP_query with the post ids

    $args = array(
      'post_type' => 'where',
      'post__in' => $retailer_ids
    );
    $retailers_query = new WP_Query($args);

    The only reason I can see this having issues is if one of the serialized pointers is the same as a manufacturer ID. But there are ways to start them high so this workaround should be good for now.

  • Hi @stueynet

    I would advise that you checkout the relationship field documentation. It too saves an array of IDs as the value.

    In the docs you will find an article which talks about a get_posts query using a LIKE search to find selected posts.

    You can use the same technique to load posts with a selected term.

    Thanks
    E

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Searching by taxonomy custom field’ is closed to new replies.