S
S
shane892015-12-23 17:19:01
PHP
shane89, 2015-12-23 17:19:01

How to search by custom fields in wordpress?

There is a filter that accepts 5 values. I pass them as a getom, these 5 values ​​are in the product, in arbitrary fields.

$query = new WP_Query( array(
    'post_type' => 'post',
    'meta_query' => array(
        array(
            'key' => 'mood1',
            'value' =>$_GET['value1'],
        ),
        array(
            'key' => 'mood2',
            'value' => $_GET['value2'],
        ),
        array(
            'key' => 'mood3',
            'value' => $_GET['value3'],
        ),
        array(
            'key' => 'mood4',
            'value' => $_GET['value4'],
        ),
        array(
            'key' => 'mood5',
            'value' => $_GET['value5'],
        ),
    ),
) );

Everything is looking, but if I pass 1 value, it shows that nothing was found. Then emptiness is transferred to value. How to solve this problem, do search by 1 value?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WP Panda, 2015-12-23
@shane89

$array =array(
    'post_type' => 'post',
    'meta_query' => array()
 );

for ($n = 1; $n <= 5; $n++) {
if( ! empty( $_GET['value' . $n]  )  ) 
  $array['meta_query'][]  = array(
            'key' => 'mood' . $n,
            'value' => $_GET['value' . $n]
        );
  }

$query = new WP_Query( $array );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question