web-dev-qa-db-fra.com

Enregistrer le paramètre args de requête personnalisé pour WP_Query ()

J'ai écrit un plugin qui peut stocker une table de spécifications techniques pour chaque article (produit) dans une table de base de données propre. Pour la fonction de recherche du site, je souhaite ajouter un paramètre personnalisé au tableau transmis à WP_Query(). Je ne sais pas où enregistrer ce paramètre personnalisé afin qu'il soit géré par le plug-in dès que WP_Query() exécute la recherche.

Y a-t-il un crochet que je peux utiliser dans le plugin pour restreindre les publications trouvées par WP_Query() à un certain ensemble correspondant aux spécifications données? Ou dois-je éventuellement créer l'intégralité de la requête à l'aide de SQL?

Voir l'exemple suivant: à côté des paramètres "standard", j'ai un paramètre personnalisé _spec et sa valeur, je veux être analysé d'une manière ou d'une autre par le plugin.

<?php

new WP_Query(
    array(

        's' => 'some keyword', //keyword criterion
        'category' => 'some category', //taxonomy criterion

        '_spec' => 'year_min=1980;year_max=2010', //custom criterion to be handled by the plugin

    )
);

?>
6
Andre

Après des recherches plus poussées, j'ai trouvé une solution. Étant donné le WP_Query suivant:

<?php

new WP_Query(
    array(

        's' => 'some keyword', //keyword criterion
        'category' => 'some category', //taxonomy criterion

        '_spec' => 'some value', //custom criterion to be handled by the plugin

    )
);

?>

Vous pouvez gérer des paramètres personnalisés à l'aide de pre_get_posts en combinaison avec posts_where:

<?php

add_action( 'pre_get_posts', 'my_pre_get_posts' ); //hook into the query before it is executed

$custom_where_string = ''; //used to save the generated where string between filter functions

function my_pre_get_posts( $query )
{
    global $custom_where_string;

    //if the custom parameter is used
    if(isset($query->query_vars['_spec'])){

        //here you can parse the contents of $query->query_vars['_spec'] to modify the query
        //even the first WHERE starts with AND, because WP adds a "WHERE 1=1" in front of every WHERE section
        $custom_where_string = 'AND ...';

        //only if the custom parameter is used, hook into the generation of the query
        add_filter('posts_where', 'my_posts_where'));
    }
}

function my_posts_where( $where )
{
    global $custom_where_string;

    //append our custom where expression(s)
    $where .= $custom_where_string;

    //clean up to avoid unexpected things on other queries
    remove_filter('posts_where', 'my_posts_where'));
    $custom_where_string = '';

    return $where;
}


?>

PS: Consultez http://codex.wordpress.org/Class_Reference/WP_Query#Filters pour manipuler d'autres parties de la requête SQL (par exemple, JOIN)

6
Andre