questions

Order posts by Title length in WP_QUERY

Rate this post

I am having problem ordering the posts based on the title length. Here is my code:

<?php
$terms = get_terms(array(
  'taxonomy' => 'vendor_category',
  'slug' => 'venues',
  'hide_empty' => false
));
?>
<?php
foreach ($terms as $term) {
  $eventargs = array(
    'post_type'      => 'vendor',
    'posts_per_page' => -1,
    'orderby' => 'title',
    'order'   => 'ASC',
    'meta_key' => 'primary_category',
    'meta_value' => $term->term_id,
  );

  $eventqry = new WP_Query($eventargs);
?>

How can i sort the posts based on the title length in ascending order.

 

✔️Solution:

You can save title length in post meta on save_post hook. and then you can retrieve post order by post meta value.

You can use save_post hook to save the post meta. put this code in your active theme.

//for existing vendors
add_action('admin_init', 'udpate_existing_vendor');
function udpate_existing_vendor(){

    $existing_vendor_updated = get_option('existing_vendor_updated', 'no');
    
    if( $existing_vendor_updated == 'no' ){
        
        $vendor_args = array(
            'post_type' => 'vendor', 
            'post_status' => 'publish', 
            'posts_per_page'   => -1 
        );

        $vendors = new WP_Query( $vendor_args );
        
        if( $vendors->have_posts() ) { 
            while ( $vendors->have_posts() ) { $vendors->the_post();
                $length = strlen( get_the_title() );
                update_post_meta( get_the_ID(), 'title_length', $length );
            } wp_reset_postdata(); 
        }

        update_option('existing_vendor_updated', 'yes');
    }

}

// for new vendor
function save_vendor_title_length( $post_id ) {
    $length = strlen( get_the_title( $post_id ) );
    update_post_meta( $post_id, 'title_length', $length );
}
add_action( 'save_post_vendor', 'save_vendor_title_length');

Here your query will look like.

$terms = get_terms(array(
    'taxonomy'   => 'vendor_category',
    'slug'       => 'venues',
    'hide_empty' => false
));

foreach ($terms as $term) {

    $eventargs = array(
        'post_type'      => 'vendor',
        'posts_per_page' => -1,
        'orderby'        => 'meta_value_num',
        'order'          => 'ASC',
        'meta_key'       => 'title_length'
    );

    $eventqry = new WP_Query( $eventargs );

}

Leave a Reply

Your email address will not be published.

Back to top button