1

As per my previous question.

How to show posts rank based on custom field value

It works perfect on homepage as I wanted. Now I want to show the same rank in single post pages also.

1 Answer 1

1

We will use a small piece of the logic from my previous answer in this appraoch.

We need to do the following:

  • Get an array of post ID's from the query we have run to get our post limit of 100

  • Use the current post ID and search for that specific post ID in the array of post ID's

  • Use the array key where our values match, add 1, and return that as our rank #

(NOTE: If you are using default post paging, you will get posts that is not in your 100 post limit. For that we will add a fallback of "Not Ranked")

THE CODE

The following goes into functions.php. (NOTE: The following requires PHP 5.4 + and is untested)

function get_single_post_rank()
{

    // First check if we are on a single page, else return false
    if ( !is_single() )
        return false;

    /**
     * Get our ranked 100 posts as ID's
     * @link http://wordpress.stackexchange.com/a/194730/31545
     */
    $args = [
        'posts_per_page' => 100,
        'fields'         => 'ids',
    'meta_key'       => 'custom_field',
    'orderby'        => 'meta_value_num', //or 'meta_value_num'
    'order'          => 'DESC',
        // Add additional args here
    ];
    $post_ids = get_posts( $args );

    // Get the current single post ID
    $current_post_id = get_queried_object_id();

    // Search for our $current_post_id in the $post_ids array
    $key = array_search( $current_post_id, $post_ids );

    // If $key is false or null, return the fallback value "Not Ranked"
    if ( !$key && $key != 0 )
        return 'Not Ranked';

    // $key returns a value, lets add one and return the value
    return ( $key + 1 );
}

In your single page, inside your loop, just add the following then

$rank = get_single_post_rank();
echo 'Ranked ' . $rank . ' ' . get_the_title();
2
  • It works great but #1 raked post shows Not Ranked. Commented Jul 17, 2015 at 18:27
  • Please see my edit Commented Jul 18, 2015 at 2:55

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.