Post Rank on Single Post page based on custom field

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();

Leave a Comment