这可以通过一个带有2个动作和2个过滤器的简单自定义插件来实现。
首先使用post_row_actions
筛选以更改管理页面上的编辑链接,以附加一个名为final\\u destination的自定义查询,其中包含我们当前所在页面的URI。
接下来,我们可以使用edit_form_advanced
使用final\\u destination的值向后期编辑表单添加隐藏字段的操作GET
参数
现在我们可以使用redirect_post_location
筛选器以检查中的最终\\u目标POST
数组并返回重定向(如果已设置)。
最后,我们还需要编辑管理工具栏,以便那里的编辑链接也具有final\\u destination参数集。为此,我们可以使用admin_bar_menu
行动
因此,整个插件最终会像这样:
<?php
/*
Plugin Name: Post Edit Redirects
Description: When viewing a post, and then clicking on edit post, after saving you post you should be redirected back
to the original page. Same deal with when you are on an admin screen viewing a list of posts and then click edit.
This module sorts all that out.
Version: 1.0
*/
// Alter the edit link on post listings pages to include a final destination so we can redirect here after editing is done.
add_filter(\'post_row_actions\', \'post_edit_redirects_post_row_actions\', 10, 1);
function post_edit_redirects_post_row_actions($actions) {
$actions[\'edit\'] = str_replace(\'action=edit\', \'action=edit&final_destination=\' . urlencode($_SERVER[\'REQUEST_URI\']), $actions[\'edit\']);
return $actions;
}
// Alter the post edit form to include a hidden field for final destination
add_action(\'edit_form_advanced\', \'post_edit_redirects_edit_form_advanced\');
function post_edit_redirects_edit_form_advanced() {
if (!empty($_GET[\'final_destination\'])) {
echo \'<input id="final_destination" name="final_destination" type="hidden" value="\' . urldecode($_GET[\'final_destination\']) . \'">\';
}
}
// After a post is saved check for a final destination to redirect to.
add_filter(\'redirect_post_location\', \'post_edit_redirects_redirect_post_location\');
function post_edit_redirects_redirect_post_location($location) {
if (!empty($_POST[\'final_destination\'])) {
return $_POST[\'final_destination\'];
}
}
// Edit the admin toolbar so the edit link has the final_destination query string attached
add_action(\'admin_bar_menu\', \'post_edit_redirects_admin_bar_menu\', 999);
function post_edit_redirects_admin_bar_menu(WP_Admin_Bar $wp_admin_bar) {
$all_nodes = $wp_admin_bar->get_nodes();
// It is not possible to edit a node, so remove them all and put them back again, making the edit along the way.
foreach($all_nodes as $key => $val) {
$current_node = $all_nodes[$key];
$wp_admin_bar->remove_node($key);
if($key == \'edit\') {
$current_node->href .= \'&final_destination=\' . urlencode($_SERVER[\'REQUEST_URI\']);
}
$wp_admin_bar->add_node($current_node);
}
}