This code will add recently viewed post or cpt by storing post id in browser cookies so we can queried later.

/**
 * Function to add post ID to cookies for recently viewed items.
 */
function add_id_to_cookies() {
    // Get the post ID of the current post
    $post_id = get_the_ID();

    // Check if 'viewed' cookie is set
    if (empty($_COOKIE['viewed'])) {
        $recently_viewed = array();
    } else {
        // Parse the cookie value into an array
        $recently_viewed = wp_parse_id_list((array) explode('|', wp_unslash($_COOKIE['viewed'])));
    }

    // Unset if already in viewed products list.
    $keys = array_flip($recently_viewed);

    if (isset($keys[$post_id])) {
        unset($recently_viewed[$keys[$post_id]]);
    }

    // Add current post ID to the recently viewed array
    $recently_viewed[] = $post_id;

    // Ensure only 15 most recent items are stored
    if (count($recently_viewed) > 15) {
        array_shift($recently_viewed);
    }

    // Update the 'viewed' cookie
    setcookie('viewed', implode('|', $recently_viewed), time() + 3600, '/');
}

/**
 * Hook to add recently viewed posts to cookies on single post view.
 */
function add_id_to_cookies_on_single_post() {
    // Check if it's a single post view
    if (is_singular('post')) {
        // Run the function add_id_to_cookies()
        add_id_to_cookies();
    }
}
add_action('template_redirect', 'add_id_to_cookies_on_single_post');

This code can be added to the functions.php file of your theme or a custom plugin. It will track the IDs of the posts a user has viewed, specifically for the post type 'post' (you can change 'post' to your custom post type if needed), and store them in a cookie named 'viewed'. The cookie will store up to 15 most recent viewed posts, ensuring that older ones are removed as new ones are added.

Then to display the post we can use Query Editor in element option by putting the code below:

Watch video tutorial here