0

I have a custom post called foundation_firms, from which I'd like to create an array of letters, each letter representing that there exists a post starting with that letter.

I've been trying to use in_array() to avoid adding a letter to the array if it already is in the array, however that approach hasn't been working for me. Anyone have any idea why? Here's my code thus far:

$alphas = range('A', 'Z');
$post_alphas = [];
$post_args = array(
    'post_type' => 'foundation_firms',
    'post_status' => 'publish',
    'order' => 'ASC',
    'posts_per_page' => -1,
    'orderby' => 'title',
);
$firm_query = new WP_Query($post_args);
if($firm_query->have_posts()){
    while($firm_query->have_posts()){
        $firm_query-> the_post();
        $title = get_the_title();
        echo $title.'<br/>';
        $title_alpha = $title[0];
        if(!in_array($post_alphas, $title_alpha)){
            $post_alphas[] = $title_alpha;
        }
    }
}
$final_alpha = array_intersect($post_alphas, $alphas);
echo '<pre>'.var_dump($final_alpha).'</pre>';

Basically this just gives me an array of the first letter of each post, duplicates and all. Isn't the in_array() function supposed to eliminate that?

Thanks in advance to any takers here.

1

The arguments for in_array() are the wrong way round. Looking at the documentation you can see that the first argument is the value you want to check (the 'needle') and the second argument is the array you want to check for it in (the 'haystack').

So this means it's always evaluating as false, meaning that the code inside the condition is running every time.

Just swap the arguments around to fix the issue:

if( ! in_array( $title_alpha, $post_alphas ) ) {
    $post_alphas[] = $title_alpha;
}

There's a (I think) cleaner way to do this though, with a bit less code. You can get the posts first, then use array_map() to replace every value in the array with just the first letter of each title. Then finally array_unique() to remove duplicates:

$posts = get_posts( array(
    'post_type'      => 'foundation_firms',
    'post_status'    => 'publish',
    'order'          => 'ASC',
    'posts_per_page' => -1,
    'orderby'        => 'title',
) );

$letters = array_map( $posts, function( $post ) {
    return $post->post_title[0];
} );

$letters_unique = array_unique( $letters );

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.