1

How do I order a post query by the length of the post content?

$orderby = ?;

$query = array(
  'posts_per_page' => 10,
  'post_status' => 'publish',
  'orderby' => $orderby,
  'order' => 'DESC',
); 
$the_query = new WP_Query($query);
  • That's not an option provided by WP_Query, the full list of what you can order by is in the docs – Tom J Nowell Apr 21 '18 at 22:33
0

As Tom has said in his comment, there is no option for WP_Query for ordering posts by their word count/length.

If you wanted to do this then you would have to firstly store the word count or length of each post as post meta. Once this was stored, you could then use WP_Query like so:

$args = array(
    'posts_per_page' => 10,
    'post_status' => 'publish',
    'orderby'   => 'meta_value_num',
    'meta_key'  => 'wordcount',
    'order' => 'DESC',
);
$query = new WP_Query( $args );

You could store the word count of posts as post meta when updating posts or when new posts are created by using the following code:

/**
 * Get post wordcount and save as post meta
 */
function add_post_wordcount( $post_id ) {
    $content = get_post_field( 'post_content', $post_id ); // Get the content
    $wordcount = str_word_count( strip_tags( $content ) ); // Count the words
    if ( ! add_post_meta( $post_id, 'wordcount', $wordcount, true ) ) { 
        update_post_meta( $post_id, 'wordcount', $wordcount );
    }
}

Then, run this function on the following WordPress actions:

On save new post

add_action( 'save_post', 'add_post_wordcount' );

On updating existing post

add_action( 'post_updated', 'add_post_wordcount' );
| improve this answer | |
  • Why do you assume that post length is calculated as word count? – Krzysiek Dróżdż Apr 21 '18 at 23:37
  • @KrzysiekDróżdż - I gave the word count as an example, as authors generally state the length of written text as a word count. I did also state in my answer that the OP would need to store the 'word count' or 'length'. Why do you assume that I assumed something? – Mat Apr 22 '18 at 17:33

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.