<?php
/**
 * Template Name: Recherche d’articles
 */
get_header();
// Traitement du formulaire
if(isset($_POST[‘submit’])) {
    // Récupération du texte du formulaire
    $text = sanitize_text_field($_POST[‘text’]);
    // Séparation du texte en mots
    $words = preg_split(‘/s+/’, $text);
    // Suppression des mots de moins de 4 caractères
    $words = array_filter($words, function($word) {
        return strlen($word) > 3;
    });
    // Recherche dans les taxonomies WordPress
    $taxonomy_terms = array();
    $taxonomies = get_taxonomies();
    foreach ($taxonomies as $taxonomy) {
        $terms = get_terms(array(
            ‘taxonomy’ => $taxonomy,
            ‘hide_empty’ => false,
        ));
        foreach ($terms as $term) {
            if (in_array($term->name, $words) || in_array($term->slug, $words)) {
                $taxonomy_terms[] = $term->term_id;
            }
        }
    }
    // Requête pour sélectionner les articles les plus vus qui contiennent les termes de taxonomie trouvés
    $args = array(
        ‘post_type’ => ‘post’,
        ‘post_status’ => ‘publish’,
        ‘tax_query’ => array(
            array(
                ‘taxonomy’ => ‘category’,
                ‘field’ => ‘term_id’,
                ‘terms’ => $taxonomy_terms,
            ),
        ),
        ‘meta_key’ => ‘stevejobs_post_views_count’,
        ‘orderby’ => ‘meta_value_num’,
        ‘order’ => ‘DESC’,
        ‘posts_per_page’ => 10,
    );
    $query = new WP_Query($args);
}
?>
<div class=”container”>
    <div class=”row”>
        <div class=”col-md-6 mx-auto”>
            <h1>Recherche d’articles</h1>
            <form method=”post”>
                <div class=”form-group”>
                    <label for=”text”>Texte</label>
                    <input type=”text” name=”text” id=”text” class=”form-control”>
                </div>
                <button type=”submit” name=”submit” class=”btn btn-primary”>Rechercher</button>
            </form>
        </div>
    </div>
    <?php if(isset($query) && $query->have_posts()): ?>
        <div class=”row”>
            <div class=”col-md-12″>
                <h2>Résultats de la recherche</h2>
                <table class=”table”>
                    <thead>
                        <tr>
                            <th>Titre</th>
                            <th>Contenu</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($query->have_posts()): $query->the_post(); ?>
                            <tr>
                                <td><a href=”<?php the_permalink(); ?>”><?php the_title(); ?></a></td>
                                <td><?php the_excerpt(); ?></td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php endif; ?>
</div>
<?php
get_footer();
?>