• Resolved owhited

    (@owhited)


    I want to store an array of term ids to a variable. The terms are selected such that a certain meta_key != certain meta_value.

    I used this code, and always I get “Fatal error: Memory exhausted”.

    $args = array( 'taxonomy' => array( 'category', 'post_tag' ),
                     'meta_query' => array(
                       array(
                        'key'     => 'meta_key',
                        'value'   => 'meta_value',
                        'compare' => '!=',
                       ),
                       ),
    		);
    $term_query = new WP_Term_Query($args);

    Is this code correct?
    If it is correct, how can I remove the memory error?

Viewing 1 replies (of 1 total)
  • This sounds like a server issue and something you would need to address with your host. The code is right but the default number of terms it’s going to return is all of them. If you have thousands for categories and post tags then it’s absolutely possible that it’s having a rough time processing that many items.

    What you can do is pass the number parameter to the query and limit the results ( or combine number with offset and loop through multiple times to get full results ). You can also pass in the fields parameter which may help since you only needs IDs. A final thing you could do is use the raw SQL and query the terms yourself instead which may be faster.

    Limit by number, only grab IDs

    $term_query = new WP_Term_Query( array(
    	'taxonomy'		=> array( 'category', 'post_tag' ),
    	'number'		=> 200,
    	'fields'		=> 'ids',
    	'meta_query'	=> array( array(
    		'key'     => 'meta_key',
    		'value'   => 'meta_value',
    		'compare' => '!=',
    	) ),
    ) );

    Grab the SQL and run it directly, skip the WordPress PHP processing:

    // Only grab 1 since we just need the generated SQL
    $term_query = new WP_Term_Query( array(
    	'taxonomy'		=> array( 'category', 'post_tag' ),
    	'number'		=> 1,
    	'fields'		=> 'ids',
    	'meta_query'	=> array( array(
    		'key'     => 'meta_key',
    		'value'   => 'meta_value',
    		'compare' => '!=',
    	) ),
    ) );
    
    $sql = $term_query->request;
Viewing 1 replies (of 1 total)
  • The topic ‘WP_Term_Query exclude by meta value’ is closed to new replies.