0

I want to create a page that lists tags that begin with a specific letter. So for example I want a page that lists all tags that begin with the letter 'A'. This is the code I got so far

<?php $args = array('name__like' => "a", 'order' => 'ASC');
    $terms = get_terms('post_tag', $args);
    if ( !empty( $terms ) && !is_wp_error( $terms ) ) {
        $count = count($terms);
        $i=0;
        $term_list = '<ul class="my_term-archive">';
        echo '<h2 class="term-letter">A</h2>';
        foreach ($terms as $term) {
            $i++;
            $term_list .= '<li><a href="' . get_term_link( $term ) . '" title="' . sprintf(__('View all post filed under %s', 'my_localization_domain'), $term->name) . '">' . $term->name . '</a></li>';
            if ($count != $i) {
                $term_list .= '';
            }
            else {
                $term_list .= '</ul>';
            }
        }
        echo $term_list;
    }
    ?>

The problem is it's not listing all tags that begin with the letter A instead it lists anything that contains the letter 'A'. How can I fix this?

Another question: Is there a more effective way to create separate pages for all 27 alphabetical letters? cause I don't want to manually create them

0

First Question's Answer:

For filtering based on your terms first letter you need to filter the query, which you can do with the terms_clauses hook. By putting the below code block in your theme's functions.php you can do that-

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

Second Question's Answer:

I don't think you need to create separate 27 pages for every letter. Rather you can use $_GET variable to do that for you. By using this $_GET variable you can pass the letter as parameter that you need to be and catch this to $name__like = isset($_GET['your_get_variable name']) ? $_GET['your_get_variable name'] : '';. Then pass it to $args array. The array will look like below-

$name__like = isset($_GET['your_get_variable name']) ? $_GET['your_get_variable name'] : '';
$args = array(
    'name__like' => $name__like, 
    'order' => 'ASC', 
    'hide_empty' => 0 // Put 0 If you need to show the empty terms otherwise 1
);

Hope that helps.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.