可以捕获$post_id
使用以下组合wp_get_referer()
和url_to_postid()
然后重置$post
使用setup_postdata
.
这对于前端来说应该足够容易。但在管理方面,我们需要使用parse_url
抓住ID
使用parse_str
. 为了更好地衡量,我们应该通过检查action
还要看看ID
is_numeric
-- 跑步intval
在我们用它来排除任何有趣的事情之前。
PHP
// for logged-in users
add_action( \'wp_ajax_foobar\', \'wpse20160117_wp_ajax_foobar\' );
// let\'s skip the nopriv because we want to only target logged-in users
// add_action( \'wp_ajax_nopriv_foobar\', \'wpse20160117_wp_ajax_foobar\' );
function wpse20160117_wp_ajax_foobar() {
$url = wp_get_referer();
$post_id = \'\';
// works with front-end urls
// $post_id = url_to_postid( $url );
if ( empty( $post_id ) ) { // lets do it the hard way
// strip the query
$query = parse_url( $url, PHP_URL_QUERY );
// parse the query args
$args = array();
parse_str( $query, $args );
// make sure we are editing a post and that post ID is an INT
if ( isset( $args[ \'post\' ] ) && is_numeric( $args[ \'post\' ] ) && isset( $args[ \'action\' ] ) && $args [ \'action\' ] === \'edit\' ) {
if ( $id = intval( $args[ \'post\' ] ) ) {
// cool.. it worked
$post_id = $id;
}
}
}
if ( ! $post_id ) {
echo "No foobar for you!";
} else {
global $post;
// make sure we have a post
if ( $post = get_post( $post_id ) ) {
// prep the post data
setup_postdata( $post );
// now we\'re ready!
echo "Are you referring to $post_id? Title: " . get_the_title();
} else {
echo "No post for you!";
}
}
die();
}
JS
jQuery.post(
ajaxurl,
{
\'action\': \'foobar\',
\'data\': \'baz\'
},
function(response){
alert(\'The server responded: \' + response);
}
);