PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

[FIXED] How to only apply a (Wordpress) meta query if it exists

 July 08, 2022     mysql, php, posts, wordpress     No comments   

Issue

I am trying to apply filters in a list of products. Users will use select boxes on the front end and click a button to filter the products.

Every product is it's own post, so I use WP_Query to get the posts. For example, I want all products with the color "red", the material "plastic" and the brand "Bikon". So I use;

$color = "red";
$material = "plastic";
$brand = "Bikon";
$query = new WP_Query(array(
    'post_type'         => 'products',
    'posts_per_page'    =>  6,
    'post_status'       => 'publish',
    'meta_query'    => array(
        'relation'      => 'AND',
        array(
            'key'       => 'color',
            'value'     => $color,
            'compare'   => '='
        ),
        array(
            'key'       => 'material',
            'value'     => $material,
            'compare'   => '='
        ),
        array(
            'key'       => 'brand',
            'value'     => $brand,
            'compare'   => '='
        )
    )
));

And this will work fine if every value get's set. But if only one of the select boxes is used, the other two values will be empty and the query will not return any posts. Is there any way to say "only use this array in the meta query if this value is set"?


Solution

You can check for definition of variable and add additional filtering if it exists

$query_args = array(
    'post_type'      => 'products',
    'posts_per_page' => 6,
    'post_status'    => 'publish',
    'meta_query'     => array(
        'relation' => 'AND',
        array(
            'key'     => 'product_check',
            'compare' => 'EXISTS',
        ),
    ),
);

if(isset($color) && $color) {
    $query_args['meta_query'][] = array('key' => 'color', 'value' => $color, 'compare' => '=');
}

if(isset($material ) && $material ) {
    $query_args['meta_query'][] = array('key' => 'material ', 'value' => $material , 'compare' => '=');
}

if(isset($brand ) && $brand ) {
    $query_args['meta_query'][] = array('key' => 'brand ', 'value' => $brand , 'compare' => '=');
}

$query = new WP_Query($query_args);


Answered By - Alexey Svidentsov
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing