wordpress logo

Loading all WordPress posts having or not having a custom meta field

wordpress logo

In a scenario one would like to create a custom meta key value pair for a post and save some value into it. Assume of an existing blog with hundred of posts which you want to add a custom field. Also assume a case in which you can only edit one post at a time and enter custom meta key value one by one.

In such situation, where some of your posts have a custom meta field and some do not have you would want to load all posts irrespective of custom field may exist or may not exist for a post. The following code in such a situation may come handy:

	$wpec_args = array(
		'post_status' => 'publish',
		'meta_query' => array(
		   'relation' => 'OR',
			array(
			 'key' => 'pspc_sort_order'
			 'compare' => 'NOT EXISTS',
			 'value' => '' // This is ignored, but is necessary.
			),
			array(
			 'key' => 'pspc_sort_order',
			 'value!=' => false
			)
		)
	);

In the above code snippet,the only thing worth a brief is meta_query. Hence we want to filter our records based on the optional existence of custom field ‘pspc_sort_order’ we define a relationship for our SQL statement which is ‘OR’. Next we define a ‘compare’ value for our first meta key set with “NOT EXISTS”. Remember even while defining ‘compare’ clause we needed to supply and empty value i.e. ” for the value clause.

We define another set of confuration for our meta key ‘pspc_sort_order’ with ‘conditional’ value clause with a NOT EQUAL TO comparison (!=). We set it’s value to ‘false’ so even an empty value matches. Obviously if you create a custom field you must store some value into it however we must take care of situation where there was an empty string entered into the value of a custom field.

I hope someone find it helpful.

Leave a Reply

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