How to Get Your Own Post Type in WordPress by Filtering by the Right Taxonomy

How to Get Your Own Post Type in WordPress by Filtering by the Right Taxonomy

To retrieve a specific post type in WordPress filtered by a custom (or built-in) taxonomy, use the following snippet:

$Posts = get_posts(array(
	'post_type' => 'my-post-type',
	'order' => 'ASC',
	'tax_query' => array(
	array(
			'taxonomy' => 'my-taxonomy',
			'field' => 'slug',
			'terms' => 'event'
		)
	),
	'meta_query' => array(
		'AND',
		array(
			'type' => 'NUMERIC',
			'key' => 'event_date',
			'compare' => '<', 'value' => time()
		),
		array(
			'type' => 'NUMERIC',
			'key' => 'is_archive',
			'compare' => '==',
			'value' => 0
		)
	)
));

What do we have here? First:

	'post_type' => 'my-post-type',
	'order' => 'ASC',

we query the database for posts of type "my-post-type".

Second:

	'tax_query' => array(
	array(
			'taxonomy' => 'my-taxonomy',
			'field' => 'slug',
			'terms' => 'event'
		)
	),

in the same query, we add a filter for taxonomy "my-taxonomy", where the slug equals "event".

Third:

	'meta_query' => array(
		'AND',
		array(
			'type' => 'NUMERIC',
			'key' => 'event_date',
			'compare' => '<', 'value' => time()
		),
		array(
			'type' => 'NUMERIC',
			'key' => 'is_archive',
			'compare' => '==',
			'value' => 0
		)
	)

We add meta field filtering: the event date "event_date" must be less than the current date, and the post must not be archived:

'is_archive == 0'
Posts on similar topics

Are you having problems with your WordPress site? Do you need additional functionality? A custom plugin or a new page?
Then write to me via the feedback form, and I will try to help you.

Write a comment

Your email address will not be published. Required fields are marked *