0

there is a main post:

$parent = wp_insert_post([
    'post_type' => 'parent',
    'post_name' => 'test parent'
]);

and the children:

$child1 = wp_insert_post([
    'post_type' => 'child',
    'post_name' => 'test child1'
]);
$child2 = wp_insert_post([
    'post_type' => 'child',
    'post_name' => 'test child2'
]);
$child3 = wp_insert_post([
    'post_type' => 'child',
    'post_name' => 'test child3'
]);

lets match them:

wp_update_post(
    array('ID' => $child1, 'post_parent' => $parent)
);
wp_update_post(
    array('ID' => $child2, 'post_parent' => $parent)
);
wp_update_post(
    array('ID' => $child3, 'post_parent' => $parent)
);

finally to list them:

$children = get_children(['post_parent' => $parent]);

this is theoretically seems to be OK, but it only describes the relation itself, not the order. What if I want to order the children? How to do it?

  • 1
    Save ordinal number as meta field child_no for each child post. Then, when selecting, sort post by this meta field. – nmr Aug 29 '18 at 13:20
  • seems like this is the easiest way – John Smith Aug 29 '18 at 14:21
  • Sorry, what's wrong with the Order property that already exists, menu_order? Not clear why a custom field is necessary here? – Jacob Peattie Aug 29 '18 at 14:28
  • menu_order is available for page and custom post type. Did I miss something? @JacobPeattie – nmr Aug 29 '18 at 14:33
  • 1
    You are right.. – nmr Aug 29 '18 at 14:39
1

This should be doable in the get_children() query, try the following:
Take a look at the codex entry of get_children(). You will see that get_children() uses the same args as get_posts(). If you than look at get_posts() you will see that you have 2 order arguments to work with:

'orderby' => 'date',
'order' => 'DESC',

For all possible orderby and order parameters, you can take a look at WP_Query codex.

  • but by wp_update_post, I cant see the way to set a direct sequence – John Smith Aug 29 '18 at 13:23
  • 1
    Do you want to save a specific order number to each post? Like its done on normal pages in the Page Attributes. – LWS-Mo Aug 29 '18 at 13:28

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.