How to identifty post from its URL in 404 page?

Why GUID is such unstable? Some of the post's GUID are pretty permalinked, but most of them are default. I's using Pippin's function to get the post_id from its GUID, but it's not working if my site is using pretty permalink, and the GUID is default. But it's working on those posts only, where the GUID is pretty permalinked. I tried using url_to_postid() too - same result.

I'm actually failing doing such redirection where posts that are expired (post_status expired) will be redirected from their 404 page to their respective category page. Any idea on which I can do it successfully?

function prefix_expired_redirection() {
    if( ! is_404() )
        return;

    //Grab the URL
    $this_url   = prefix_get_current_url(); //custom function retrieves pretty permalinked URL

    //If the URL is of a post
    //Pippin's Function: https://pippinsplugins.com/retrieve-attachment-id-from-image-url/
    $post_id    = prefix_get_post_id( $this_url );

    //We've tasks if it's only a post :)
    if( ! $post_id )
        return;

    //Grab the post's terms from 'cpt_tax'
    $terms      = wp_get_post_terms( $post_id, 'cpt_tax' );

    //Grab the first term and its link
    $term_id    = $terms[0]-term_id;
    $term_link  = get_term_link( $term_id, 'cpt_tax' );

    //is_expired_post() custom function - determining expired posts
    if( is_expired_post( $post_id ) ) {
        wp_redirect( esc_url( $term_link ) );
        exit();
    }
}
add_action( 'template_redirect', 'prefix_expired_redirection' );

Topic template-redirect wp-redirect guids permalinks Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.