Support

Account

Home Forums ACF PRO Find posts by related taxonomy field

Solved

Find posts by related taxonomy field

  • I have “projects” (a custom post type), with many custom fields (defined via ACF), one of which relates the project to an “artist” (a custom taxonomy). That field is of type “taxonomy”.

    Finally, I have (woocommerce) “products” that also use the custom taxonomy “artist”, via an ACF Field of type “taxonomy”.

    On a product page, I would like to fetch the latest “project” that was related to that same artist.

    Here is the code that I believe should work, but it returns an empty array (it should return three projects).

    
    $artist = get_field('artist_id');
    
    $projects = get_posts(array(
            'post_type' => 'project',
            'meta_query' => array(
                array(
                    'key' => 'artist', // name of custom field
                    'value' => '"' . $artist->term_id . '"',
                    'compare' => 'LIKE'
                )
            )
        ));

    I’ve double-checked that $artist->term_id returns a correct value: it does. What am I doing wrong ?

  • found the solution: simply needed to remove the double quotes around the value

    
    	// The product's related artist.
    	$artist = get_field('artist_id');
    
    	// The product's most recent related project. If found, get the content of its "Artist" block.
    
    	$project = new WP_Query( array(
    			'post_type' => 'project',
    			'posts_per_page' => 1,
    			'orderby'=> 'date',
    			'order' => 'DESC',
    			'meta_query' => array(
    				array(
    					'key' => 'artist', // name of custom field
    					'value' => $artist->term_id,
    					'compare' => 'LIKE'
    				)
    			)
    		));
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Find posts by related taxonomy field’ is closed to new replies.