• Hey guys,

    i try to work a little bit with meta_query on the pre_get_posts action and i have a little Problem.

    I have a custom Post-Type “news”. On the edit-page i had added a custom meta box. Here the user can select the visibility of the news. For example:
    Metabox Screenshot

    Options (postmeta and usermeta) will be stored as Array (serialized) in the metadata, like:
    PMA – Postmeta
    PMA – Usermeta

    But how i can combine the meta-querys with Arrays?

    add_action('pre_get_posts',						array($this, 'pre_get_posts'));
    
    function pre_get_posts($query) {
    			if($query->query_vars['post_type'] == 'news') {
    				$user				= wp_get_current_user();
    				$user_company		= get_user_meta($user->ID, '_user_company', true);
    				$user_company		= empty($user_company) ? array() : (array) $user_company;
    				$user_company[]		= 'all';
    				$user_company[]		= 'front';
    
    				$query->set('meta_query', (array(array(
    					'key'		=> '_news_visibility',
    					'value'		=> $user_company,
    					'type'		=> 'array'
    				))));
    			}
    
    			return $query;
    		}

    Data – The _news_visibility is an array. For example:
    array( 'all', 1 )

    _user_company from the userdata is an array like:
    array( 1, 2 )

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    You combine meta queries by adding an additional inner array for each additional meta value to use in the query. Each inner array is logically ANDed with the next by default. To use an OR relationship, add 'relationship'=>'OR'. to the main meta_query array.

    As for arrays as meta values, you cannot supply ‘array’ as a type. If you cannot specify a serialized array as a value and string as type, it’s probably not going to work and you’ll need to rethink how data is stored for this to work.

    Thread Starter Patrick

    (@hovida)

    I have create an little workaround. Its not great, but it works.

    On the Frontend i can check the data in the Loop. If the ID not in the Array, the post will ignored.

    The Backend was a little tricky. Here i have disabled the Menu-Entry with show_in_menu = false. Here i create an own Post-Overview to check that.

    I think this is not the best way but it solve the problem.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘WP_Query – Meta with Arrays’ is closed to new replies.