• I’m sorry, I speak a little English.

    My code in my custom theme (functions.php) [only example]:

    $posts = array(
    '141th',
    // ...
    '3rd',
    '2nd',
    '1st'
    );
    foreach( $posts as $post ) {
    wp_insert_post( array( 'post_title'=> $post ) );
    }

    My posts list:

    141
    139
    140
    137
    138
    ...
    1

    I would like (in order):

    141
    140
    139
    138
    ...
    1

    Why? What is the problem and how to solving?

    Thanks.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter otto2021

    (@otto2021)

    My $posts array is okay. I used the krsort( $posts ) function. I checked with print_r() function. My $posts variable is okay. Why is it wrong?

    Moderator bcworkz

    (@bcworkz)

    When you bulk insert like that, the exact publish date can be a little erratic and unreliable for precise sorting. By default posts are sorted by their published date. You need to specify a 'orderby'=>'title', parameter when you query your posts.

    Titles are saved as a string, so the sorting is alphabetic, not numeric. Unless your titles all have the exact same digit count, you cannot get numeric title sorting using WP_Query alone. The resulting SQL needs to be modified through the “posts_request” filter by adding +0 to the title ORDER BY parameter. This casts the string as a number by performing math on it.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘wp_insert_post order problem’ is closed to new replies.