Вопрос:

WordPress: Custom SELECT query that prints meta_values based on INPUT (JSON)

php json wordpress

210 просмотра

2 ответа

1 Репутация автора

I'm getting problems with a custom query of Wordpress.
I'd like to query meta_values from a $_POST and prints values that contains the input text, but right now i'm retrieving just the whole column.

That's my code:

    $gets = '%'.$_REQUEST['s'].'%'; // Sets meta value from input
    $meta_key = 'ricerca'; // Sets meta key

    global $wpdb;

    $metas = $wpdb->get_results(
        "SELECT DISTINCT meta_value
        FROM $wpdb->postmeta
        WHERE meta_key = '{$meta_key}'
        AND meta_value LIKE '{$gets}'"
    );

    $response = array(); // Initialize array

    if (!empty($gets))
    {
        foreach ($metas as $meta)
        {
            $response[] = $meta->meta_value; // Set single meta as array
        }
    }

    echo json_encode( $response ); // Prints values.
    exit();
}

What am I doing wrong?

Автор: Badzlol Источник Размещён: 07.03.2017 09:53

Ответы (2)


0 плюса

1 Репутация автора

That's the table screen: WP_POSTMETA Table IMG

That's the Input form:

<form method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">

<?php if( mfn_opts_get('header-search') == 'shop' ): ?>
    <input type="hidden" name="post_type" value="product" />
<?php endif;?>

<i class="icon_search icon-search-fine"></i>
<a href="#" class="icon_close"><i class="icon-cancel-fine"></i></a>

<input type="text" class="field" name="s" id="s" placeholder="<?php echo $translate['search-placeholder']; ?>" />           
<input type="submit" class="submit" value="" style="display:none;" />

That's the result: Search form IMG

Even if i type unknown words, it pops me up all meta_values.

Автор: Badzlol Размещён: 07.03.2017 10:16

0 плюса

2335 Репутация автора

You just need to modify the query :

$sql = "SELECT DISTINCT meta_value
        FROM $wpdb->postmeta
        WHERE meta_key = '{$meta_key}'";

if(isset($_REQUEST['s']) && !empty($_REQUEST['s']))
    $sql .= " AND meta_value LIKE '{$gets}'";

$metas = $wpdb->get_results($sql);
Автор: Happy Coding Размещён: 07.03.2017 12:05
Вопросы из категории :
32x32