Example / Snippet: Redirect based on post_type / get_post_meta

This topic contains 4 reply and 2 voices, and was last updated by towhid 9 years, 3 months ago
Viewing 4 Posts - 1 through 4 (of 4 total)
Author Posts
January 15, 2015 at 2:53 pm 34208
towhid I was having some issues figuring out how to do redirects based on post_type. Here's a nifty snippet that you can use to get more control over redirects. I also included a way to find a related post from a custom meta field.
//Redirect WPUF Version: 2.2.6
function wpuf_force_redirection($response, $post_id) {
 
        $post_type = get_post_type($post_id);
       
        if($post_type == 'type1'){
   
        //get parent post
        $parent_id = get_post_meta($post_id, 'related_id', true);
       
        //If parent found, update $response
        if ($related_id) {
                //Update Response Vars
                $response['redirect_to'] = get_permalink($related_id);
        }
       
    }elseif($post_type == 'type2'){
   
        //Update response to new post url
        $response['redirect_to'] = get_permalink($post_id);
       
    }
    return $response;
}
add_filter('wpuf_add_post_redirect', 'wpuf_force_redirection', 10, 2); //10: priority, 2: accepted vars
add_filter('wpuf_update_post_redirect', 'wpuf_force_redirection', 10, 2);
January 17, 2015 at 1:09 pm 34335
towhid towhid

Hello Dan,

Would you please let me know where you want to actually implement this code? Have you tried this code for you ? Are you getting any error?

Thank you 🙂

January 17, 2015 at 1:40 pm 34337
Dan Dan

I was thinking you could add this to the documentation. There are examples for the other filters, but not redirection. You could add this as an example to help out users.

January 17, 2015 at 1:42 pm 34338
Dan Dan

There was a typo, here is the fixed version:

//Redirect WPUF Version: 2.2.6
function wpuf_force_redirection($response, $post_id) {
 
        $post_type = get_post_type($post_id);
       
        if($post_type == 'type1'){
   
        //get parent post
        $related_id = get_post_meta($post_id, 'related_id', true);
       
        //If parent found, update $response
        if ($related_id) {
                //Update Response Vars
                $response['redirect_to'] = get_permalink($related_id);
        }
       
    }elseif($post_type == 'type2'){
   
        //Update response to new post url
        $response['redirect_to'] = get_permalink($post_id);
       
    }
    return $response;
}
add_filter('wpuf_add_post_redirect', 'wpuf_force_redirection', 10, 2); //10: priority, 2: accepted vars
add_filter('wpuf_update_post_redirect', 'wpuf_force_redirection', 10, 2);
January 17, 2015 at 2:40 pm 34341
towhid towhid

Hello Dan,

Thank you so much!!. I will provide this snippet of code to our developer team. 🙂

Viewing 4 Posts - 1 through 4 (of 4 total)