Created
January 10, 2017 12:42
-
-
Save Basilakis/374bbef5670af0e0bf912a458197f3bc to your computer and use it in GitHub Desktop.
WordPress: Redirect to post/page after publishing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Redirect to the post/page itself after publishing or updating a post in | |
// WordPress. This code is from the WordPress forum [1], modified so it doesn't | |
// redirect when saving a draft. | |
// [1]: http://wordpress.org/support/topic/redirect-to-new-post-after-publish | |
add_filter('redirect_post_location', function($location) | |
{ | |
global $post; | |
if ( | |
(isset($_POST['publish']) || isset($_POST['save'])) && | |
preg_match("/post=([0-9]*)/", $location, $match) && | |
$post && | |
$post->ID == $match[1] && | |
(isset($_POST['publish']) || $post->post_status == 'publish') && // Publishing draft or updating published post | |
$pl = get_permalink($post->ID) | |
) { | |
// Always redirect to the post | |
$location = $pl; | |
} | |
return $location; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// This version redirects to the homepage for new posts (since new posts always | |
// appear on the homepage on my blog), and tries to redirect to whatever page | |
// you were on before clicking Edit if you're editing an existing post. | |
add_filter('redirect_post_location', function($location) | |
{ | |
global $post; | |
if ( | |
(isset($_POST['publish']) || isset($_POST['save'])) && | |
preg_match("/post=([0-9]*)/", $location, $match) && | |
$post && | |
$post->ID == $match[1] && | |
(isset($_POST['publish']) || $post->post_status == 'publish') && // Publishing draft or updating published post | |
$pl = get_permalink($post->ID) | |
) { | |
if (isset($_POST['publish'])) { | |
// Homepage for new posts only | |
$location = home_url(); | |
} elseif ($ref = wp_get_original_referer()) { | |
// Referer for edited posts | |
$ref = explode('#', $ref, 2); | |
$location = $ref[0] . '#post-' . $post->ID; | |
} else { | |
// Post page as a last resort | |
$location = $pl; | |
} | |
} | |
return $location; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment