Show entries with parameters by GET and custom fields

1

I'm doing a Wordpress loop to find those posts whose value of the custom field 'country' is equal to $ _GET ['s']

$args = array(
    'post_type'=>'post', 
    'meta_query' => array(
        array(
            'key'=> 's',
            'metavalue'   => 'pais',
            'compare' => '='
        )
    )
);  

$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post();

            ?><h2><?php the_title();?></h2><?php                                           
    }
}
    
asked by MarisabelGC 04.07.2017 в 17:38
source

2 answers

1

Instead of $_GET['s'] , I recommend using the following function, which sanitizes the data entered by the user in the search field: get_search_query()

The comparison operator by default is 'meta_compare' => '=' , so it is not necessary to put it.

It would be something like this:

$keyword = get_search_query();

$args = array(
    'post_type' => 'post',
    'meta_key' => 'pais',
    'meta_value' => $keyword
);
    
answered by 08.07.2017 в 02:06
1

To show entries matching a custom field with a $ _GET (or with a variable in general), you have to use as a comparison == != >= <= , as if it were a conditional on PHP.

The key is the name of the custom field, while the value , is the variable that stores, in this case, the data obtained by GET .

$pais = $_GET['pais'];

if( isset($_GET['pais']) ){

$args= array(
    'post_type'=>'post', 
    'meta_query' => array(
        array(
            'key' => 'pais',
            'value' => $pais,
            'compare' => '==',
        )            
    )
);

$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post(); 

        // The Loop

    }
}   
    
answered by 08.07.2017 в 21:47