WebberZone / contextual-related-posts

Contextual Related Posts WordPress plugin
https://webberzone.com/plugins/contextual-related-posts/
38 stars 23 forks source link

Return same set of results when Translator plugins are enabled #130

Closed ajaydsouza closed 3 years ago

ajaydsouza commented 3 years ago

By default if the translator plugin like PolyLang is enabled, then the correct language posts are only processed on the fly in get_crp which can result in different behaviour if someone is using get_crp_posts_id. The code below ensures that the same set of IDs are returned in this circumstances.

function crp_translated_ids( $results, $args ) {
    global $post;

    $processed_ids     = array();
    $processed_results = array();

    foreach( $results as $result ) {

        $resultid = crp_object_id_cur_lang( $result->ID );

        // If this is NULL or already processed ID or matches current post then skip processing this loop.
        if ( ! $resultid || in_array( $resultid, $processed_ids ) || intval( $resultid ) === intval( $post->ID ) ) { // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict
            continue;
        }

        // Push the current ID into the array to ensure we're not repeating it.
        array_push( $processed_ids, $resultid );

        $result = get_post( $resultid );    // Let's get the Post using the ID.
        array_push( $processed_results, $result );
    }
    return $processed_results;
}
add_filter( 'get_crp_posts_id', 'crp_translated_ids', 999, 2 );