The ‘redirect_post_location’ WordPress PHP filter allows you to modify the destination URL after updating or publishing a post. This is useful when you want to redirect users to a custom page or a different location after they edit or publish a post.
Usage
To use this filter, add the following code to your theme’s functions.php file or a custom plugin file:
function my_custom_redirect( $location, $post_id ) { // Your custom code here return $location; } add_filter( 'redirect_post_location', 'my_custom_redirect', 10, 2 );
Parameters
- $location (string)
- The destination URL.
- $post_id (int)
- The post ID.
Examples
Redirect to the home page after publishing a post
function redirect_to_home( $location, $post_id ) { return home_url(); } add_filter( 'redirect_post_location', 'redirect_to_home', 10, 2 );
This code will redirect users to the home page after they publish a post.
Redirect to a custom thank you page after publishing a post
function redirect_to_thank_you_page( $location, $post_id ) { return home_url( '/thank-you/' ); } add_filter( 'redirect_post_location', 'redirect_to_thank_you_page', 10, 2 );
After a user publishes a post, they will be redirected to the custom thank you page at the /thank-you/
URL.
Redirect to the post list in the admin area after updating a post
function redirect_to_post_list( $location, $post_id ) { return admin_url( 'edit.php' ); } add_filter( 'redirect_post_location', 'redirect_to_post_list', 10, 2 );
This code will redirect users to the post list in the admin area after they update a post.
Redirect to a custom page based on the post’s category
function redirect_based_on_category( $location, $post_id ) { $post_categories = wp_get_post_categories( $post_id ); $first_category = get_category( $post_categories[0] ); return home_url( '/' . $first_category->slug . '/submission-success/' ); } add_filter( 'redirect_post_location', 'redirect_based_on_category', 10, 2 );
After a user publishes a post, they will be redirected to a custom page based on the post’s first category. The URL will have the format /category-slug/submission-success/
.
Redirect to a specific page if a custom field is set
function redirect_if_custom_field_set( $location, $post_id ) { $custom_field_value = get_post_meta( $post_id, 'custom_field_key', true ); if ( ! empty( $custom_field_value ) ) { return home_url( '/custom-page/' ); } return $location; } add_filter( 'redirect_post_location', 'redirect_if_custom_field_set', 10, 2 );
This code checks if a custom field is set for a post. If the custom field is set, the user will be redirected to a specific page (/custom-page/
) after updating or publishing the post. If the custom field is not set, the default redirection will occur.