web-dev-qa-db-fra.com

Rechercher terme taxonomie personnalisée par nom

J'ai une taxonomie personnalisée, appelée albums.

Je dois pouvoir effectuer une recherche textuelle dans le titre du terme de taxonomie. Évidemment, ce n'est pas le cas par défaut WP Search. Je me demandais comment je pourrais mieux m'y attaquer?

Dis qu'il y a un album appelé 'Football Hits',

Je commence à taper du pied et cherche que tout ce dont j'ai besoin pour apparaître est le titre de l'album et le permalien.

Merci!

3
DIM3NSION
// We get a list taxonomies on the search box
function get_tax_by_search($search_text){

$args = array(
    'taxonomy'      => array( 'my_tax' ), // taxonomy name
    'orderby'       => 'id', 
    'order'         => 'ASC',
    'hide_empty'    => true,
    'fields'        => 'all',
    'name__like'    => $search_text
); 

$terms = get_terms( $args );

 $count = count($terms);
 if($count > 0){
     echo "<ul>";
     foreach ($terms as $term) {
       echo "<li><a href='".get_term_link( $term )."'>".$term->name."</a></li>";

     }
     echo "</ul>";
 }

}

// sample
get_tax_by_search('Foo');
5
TrubinE

Vous pouvez donc rechercher des publications par titre de taxonomie - personnalisé ou non. La réponse sera dans la partie " tax_query " de WP_Query. Voici un exemple du Codex, adapté à vos besoins:

<ul>
<?php

global $post;
$album_title = $_GET['album-title'];
$args = array(
    'post_type' => 'post',
    'posts_per_page' => 5,
    'tax_query' => array( // NOTE: array of arrays!
        array(
            'taxonomy' => 'albums',
            'field'    => 'name',
            'terms'    => $album_title
        )
    )
);

$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
    <li>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </li>
<?php endforeach; 
wp_reset_postdata();?>

</ul>

UPDATE

Je n'ai pas testé cela, mais en théorie, je pense que cela pourrait fonctionner. Pour faire correspondre tout ce qui contient "pied":

<ul>
<?php

global $post;
$album_title = $_GET['album-title']; // say the user entered 'foot'
$args = array(
    'post_type' => 'post',
    'posts_per_page' => 5,
    'tax_query' => array( // NOTE: array of arrays!
        array(
            'taxonomy' => 'albums',
            'field'    => 'name',
            'terms'    => $album_title,
            'operator'    => 'LIKE'
        )
    )
);

$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
    <li>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </li>
<?php endforeach; 
wp_reset_postdata();?>

</ul>

J'espère que cela pourra aider!

1
MacPrawn