0

This is kind of a different request, but my client wants the index of a custom post type.

Basically for a regular post, they can select 1 custom post from a list in a custom field to "attach" to the post. I'm doing this through ACF.

On the front end, I'm getting just that single custom post returned with the regular post data. My user wants the index of that custom post relative to the other custom posts.

For example if there are 10 custom posts, and No. 1 is the oldest, and they happened to select the 3rd oldest one, they want it to say "No. 3".

Any idea how to do this without running a bunch of queries?

I'm guessing I should use the php array_search() function in some way...

 

EDIT

Answer found here: Get the index of post outside the loop

Basically I just queried all posts first, then used the function in the post above:

function get_post_index ( $posts = array(), $vs = 0) {
    if ( empty($posts) ) return -1;
    $i = 0;
    foreach ( $posts as $one ) {
        if ( $one->ID == $vs ) return $i;
        $i++;
    }
    return -1;
}

to get the index of my custom post.

1
  • 1
    Welcome to WPSE. You should post this as an answer, instead of an edit. It's OK to answer your own question, and you can choose to accept it after 48 hours.
    – Gabriel
    Jun 23, 2015 at 22:19

1 Answer 1

1

For example if there are 10 custom posts, and No. 1 is the oldest, and they happened to select the 3rd oldest one, they want it to say "No. 3".

There is a more elegant way than that function:

$args = array(
  'post_type' => 'book',
  'fields' => 'ids',
  'ignore_sticky_posts' => true,
  'orderby' => 'post_date',
  'order' => 'DESC'
);
$posts = new WP_Query($args);
// var_dump($posts->posts);

$index = array_search(300,$posts->posts);
if (!empty($index)) {
  echo $index + 1;
} else {
  echo 'not found';
}

It is hardly worth a function, really, but if you want one:

function get_post_index ( $ids, $vs = 0 {
  if (empty($ids) || !is_array($ids)) return false;
  $index = array_search($vs,$ids);
  if (!empty($index)) {
    return $index + 1;
  } else {
    return false;
  }
}
3
  • Is array_search() faster than looping through the posts?
    – Corey
    Jun 24, 2015 at 1:18
  • Also, I was using get_posts() instead of new WP_Query(), is there a best option there?
    – Corey
    Jun 24, 2015 at 1:19
  • get_posts is a pretty thin wrapper around WP_Query. I haven't benchmarked the two, but my guess is that array_search is faster.
    – s_ha_dum
    Jun 24, 2015 at 1:33

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.