Meta Query Filter by Tag Wordpress

2019-06-13 01:00发布

I currently have multiple pages, and in each page is a custom field which is named 'country'.

In the 'country' field I have this value 'uk, usa, brazil'.

What I'm wanting to do is display posts on the page which have the tags I have listed in the custom field 'country' (In this case show posts which has any of the tags 'uk', 'usa' and 'brazil').

I have the following code, but I don't know how to manipulate it to do the above?

$args = array (
    'post_type'              => array( 'post' ),  // YOUR POST TYPE
    'meta_query'             => array(
        array(
            'key'       => 'country',  
            'value'     => $your_country,  // THE COUNTRY TO SEARCH
            'compare'   => 'LIKE',  // TO SEARCH THIS COUNTRY IN YOUR COMMA SEPERATED STRING
            'type'      => 'CHAR',
        ),
    ),
);

// The Query
$query = new WP_Query( $args );

It seems to just be filtering for a single value?

Any help to achieve the above would be greatly appreciated.

1条回答
干净又极端
2楼-- · 2019-06-13 01:46

I'd setup a custom taxonomy to create another version of 'tags' called 'country', then you can do a taxonomy query instead.

See 'Custom Post Type UI' for an easy interface to create a custom taxonomy.

https://wordpress.org/plugins/custom-post-type-ui/
  1. Install the CPT UI (plugin above).
  2. Goto ‘Add / Edit Taxonomies’ in the menu. Add ‘Country’ as a taxonomy. Attach that to your ‘post’ post_type and 'page'.
  3. Tag the pages (used to show the posts), and the 'posts' with your country tags.

You can then use the custom wp_query in a page template, to show the posts, tagged with the country tag.

To grab the ID's of the country terms, associated with your page:

$countryTerms = wp_get_post_terms($post->ID, 'country', array("fields" => "ids"));

Then change your Query arguments to gather the posts, tagged with the country.

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
            'taxonomy' => 'country',
            'field'    => 'term_id',
            'terms'    => $countryTerms
        ),
    ),
);

If you want to stick to a meta field, try changing your 'TYPE' value to 'NUMERIC'.

查看更多
登录 后发表回答