0

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:

1
4
3
2
5
...
141

I would like (in order):

1
2
3
4
5
...
141

Why? What is the problem and how to solving?

Thanks.

4
  • Well, from what I could tell, you just need to ensure the $posts array items are sorted in the order you've specified. But that is a generic PHP question and better suited on Stack Overflow.
    – Sally CJ
    Sep 10, 2021 at 14:32
  • Dear @SallyCJ, my $posts array is okay. I used the krsort( $posts ) function. I checked with print_r() function. My $posts variable is okay. Sep 10, 2021 at 15:37
  • How and where are you viewing the posts where they are not in the order you are expecting?
    – ScottM
    Sep 10, 2021 at 18:20
  • @luckyluck31 even so, I don't think this is a wp_insert_post() issue - and just to remind you that ksort() sorts from highest to lowest. And if you're actually referring to the post list on pages like the homepage, then the posts would by default be sorted by the post date, from newest to oldest ones. So if you wanted to know how to change that, then you should edit your question and include as much details as possible like where the post list is, the template used on that page and the code which outputs the post list.
    – Sally CJ
    Sep 11, 2021 at 9:39

1 Answer 1

0

I found a solution. I just set my own value for the "post_date" field in the wp_insert_post function.

As an example:

$time = time();
for ($i=0; $i < count($postArgs); $i++) { 
    $postArg = $postArgs[$i];
    $postArg['post_date'] = $time-$i;
    wp_insert_post($postArg);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.