List post by title length

So over on wordpress I have a custom post type called crosses, and I need to list them on my search results page in order with the shortest titles first and longest titles last. I thought the way to do it would be to create a custom field called “name-length” and then include a function to count the number of letters in each post title and assign it as a number in a that custom field, but the code I’m trying got it isn’t working.

function update_my_metadata(){
$args = array(
‘post_type’ => ‘crosses’, // Only get the posts
‘post_status’ => ‘publish’, // Only the posts that are published
‘posts_per_page’ => -1 // Get every post
$posts = get_posts($args);
foreach ( $posts as $post ) {
$step = get_the_title($post->ID);
$title_word = count_chars($step);
update_post_meta( $post->ID, ‘name_length_crosses’, $title_word );

Read more here:: List post by title length

Leave a Reply

Your email address will not be published. Required fields are marked *