WordPress.org

Ready to get started?Download WordPress

Forums

merging meta_query into archive pages (1 post)

  1. theMikeD
    Member
    Posted 7 months ago #

    The backstory:

    I have created a custom field named meta_city that lists all tags in a drop down, and allows the user to select one. So for example, the existing tag “Toronto” can be assigned to the meta_city field while also remaining available as a standard tag. This is all fine.

    On the tag archive page though, only posts that have been tagged are being shown; the meta_city assignments are being ignored. Again, expected. But I want the posts with the meta_city assignment to show up for a given tag too.

    So after reading the docs, I created code to modify the main query object via the pre_get_posts filter, like so:

    add_action( 'pre_get_posts', 'md_modify_tag_archive_to_include_acf_fields' );
    function md_modify_tag_archive_to_include_acf_fields( $query ) {
    	if( $query->is_main_query() && $query->is_tag ) {
    		$term_name = $query->query[tag];
    		$term = get_term_by('name',$term_name, 'post_tag');
    
    		$meta_query = array(
    			'relation' => 'OR',
    			array(
    				'key' => 'meta_city', // name of custom field
    				'value' => $term->term_id,
    				'compare' => 'LIKE'
    			)
    		);
    
    		$query->meta_query = $meta_query;
    		$query->tax_query->relation = 'OR';
    	}
    
    }

    So now the tag archive page displays posts with the term:

    • tagged;
    • tagged + assigned to meta_city

    but not, crucially, untagged and assigned to meta_city (or IOW assigned only).

    Is there a way to achieve what I'm after?

Reply

You must log in to post.

About this Topic