Search code examples
phpwordpressfiltercustom-taxonomyalphabetical

Listing custom taxonomy terms by first letter using “name_like" does not work even after filtering query using “term_clauses” hook


I have a custom taxonomy for book authors. I need to create an index with the letters of the alphabet and when the user clicks on a letter a list appears underneath the index with all the book author whose last name starts with that letter. I got everything to work nicely except that it would list all terms where the letter was found anywhere within the term, not only the first letter:

<?php global $product;

$name_like = isset($_GET['character']) ? $_GET['character'] : '';
$letters = range('A', 'Z');
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); 
   $slug = $term->slug;
?>

<div id="content-small">
    <div class="list-terms">

        <div class="alphanav">
            <?php foreach ($letters as $letter): ?>
                <?php if (strtoupper($name_like) == strtoupper($letter)):?>
                    <a class='selected' href="<?php bloginfo('url'); ?>/auteurs/<?php echo $slug ?>?character=<?php echo strtoupper($letter)?>"><?php echo strtoupper($letter)?></a>
                <?php else: ?>
                    <a href="<?php bloginfo('url'); ?>/auteurs/<?php echo $slug ?>?character=<?php echo strtoupper($letter)?>"><?php echo strtoupper($letter)?></a>
                <?php endif;?>
            <?php endforeach;?>
            <a class="selected set-height" href="<?php bloginfo('url'); ?>/auteurs/<?php echo $slug ?>?character=#">#</a>
        </div>
<?php

$taxonomy = 'auteurs';
$queried_term = get_query_var($taxonomy);
$args = array(
'name__like' => $name_like,
   'orderby'   => 'name',
   'order' => 'ASC',
   );

$terms = get_terms($taxonomy, $args, 'slug='.$queried_term);

if ($terms) {
   $count = count($terms);
            $i=0;
            $term_list = '<div class="tab-auteur">
   <input id="tab-one-auteur" type="checkbox" name="tabs-auteur">
                          <label for="tab-one-auteur">La Liste</label>
                          <ul class="bio-list tab-content-auteur">';
            //echo '<h2 class="term-letter">'. strtoupper($name_like) . '</h2>';

 foreach($terms as $term) {
   $names = $term->name;
   $unwanted_array = array(    'Š'=>'S', 'š'=>'s', 'Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
                        'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U',
                        'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c',
                        'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',
                        'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y' );
$firstname = substr($names, strpos($names, ",") + 1); 
$arr = explode(",", $names, 2);
$lastname = $arr[0]; 
$lastname = strtr( $lastname, $unwanted_array );  
$lastname = strtoupper( $lastname );
$comma   = ',';
$whichname = strpos($names, $comma);

if ($whichname === false) {
$full = strtoupper( $names );
} else {
$full = $lastname . ', ' . $firstname;
}

$i++;
                $term_list .= '<li><a href="'.get_term_link($term->slug, 
$taxonomy).'?character='. $name_like .'">' . $full . '</a></li>';
            if ($count != $i) {
                    $term_list .= '';
                }
            else {
                    $term_list .= '</ul></div>';
                }
            }
            echo $term_list;

 }
else {
    echo '<ul class="bio-list">PAS DE AUTEURS</ul>';
 }
 ?>
 </div> 

I researched a lot and found the behaviour of “name_like” changed in the newer versions of Wordpress. With the help of this post I used the term_clauses hook to filter the query in my functions.php file:

function llps_filter_term_clauses( $clauses ) {
  remove_filter('term_clauses','llps_filter_term_clauses');
  $pattern = '|(name LIKE )\'%(.+%)\'|';
  $clauses['where'] = preg_replace($pattern,'$1 \'$2\'',$clauses['where']);
  return $clauses;
}

add_filter('terms_clauses','llps_filter_term_clauses');

and it worked - I’m sure it did… until the next time I logged onto the project. It’s not working anymore and I can’t for the life of me figure out why!


Solution

  • I had the same issue. Probably something changed in latest WP versions. I've the issue in 4.9.1

    This is how I fixed it, I changed this:

    $pattern = '|(name LIKE )\'%(.+%)\'|';
    

    into this:

    $pattern = '|(name LIKE )\'{.*?}(.+{.*?})\'|';
    

    If you want to see why I did that, I suggest to temporary print out $clauses before and after the preg_replace. I mean something like this in your code:

    function llps_filter_term_clauses( $clauses ) {
      echo '<pre>';print_r($clauses);echo "\n";
      remove_filter('term_clauses','llps_filter_term_clauses');
      $pattern = '|(name LIKE )\'%(.+%)\'|';
      $clauses['where'] = preg_replace($pattern,'$1 \'$2\'',$clauses['where']);
      print_r($clauses);die();
      return $clauses;
    }
    

    You should see that the typical "%" in the sql LIKE operator is transformed by WP into something like:

    {be8aacdf46dd49d9036fd16c13613bf3036378f188b3535c3416ae7d88844d20}your letter here{be8aacdf46dd49d9036fd16c13613bf3036378f188b3535c3416ae7d88844d20}

    i.e. a string inside {} and that's why I changed the regexp in the filter. Hope this helps.