最终状态:正如NathanJohnson所说,我将插件更改为类,仍然不能在类似increment\\u的函数中使用post id。。。
<?php .... //irrelevant parts skipped
class wpse_263293 {
protected $ID;
//* Add actions on init
public function init() {
add_action( \'the_post\', [ $this, \'createLikeButton\' ] );
add_action( \'wp_footer\', [ $this, \'footer\' ] );
add_action(\'wp_enqueue_scripts\',[ $this ,\'button_js\']);
add_action(\'wp_ajax_increment_like\', [$this,\'increment_like\']);
add_action(\'wp_ajax_no_priv_increment_like\',[$this,\'increment_like\']);
}
public function footer() {
//* Print the ID property in the footer
echo $this->ID; //This one works
}
public function createLikeButton( $post ) {
$this->ID = $post->ID;
$myId=$post->ID;
echo "<button onclick=\\"likeButton()\\" p style=\\"font-size:10px\\" id=\\"likeButton\\">LIKE</button>";
}
public function button_js(){
wp_enqueue_script( \'likeButton\', plugins_url( \'/like.js\', __FILE__ ),array(\'jquery\'));
wp_localize_script(\'likeButton\', \'my_ajax_object\', array( \'ajax_url\' =>admin_url(\'admin-ajax.php\')));
wp_localize_script(\'likeButton\', \'new_ajax_object\', array( \'ajax_url\' =>admin_url(\'admin-ajax.php\')));
}
public function increment_like() {
echo $this->ID."test"; //I only see test
/* irrelevant code*/
}
}
//* Initiate the class and hook into init
add_action( \'init\', [ $wpse_263293 = new wpse_263293(), \'init\' ] );
?>
最合适的回答,由SO网友:Nathan Johnson 整理而成
我要做的就是not 使用全局变量。
这是一个简单的类,使用3个方法和1个属性进行挂钩the_post
并在页脚中回显帖子ID。
/**
* Plugin Name: WPSE_263293 Example
*/
class wpse_263293 {
protected $ID;
//* Add actions on init
public function init() {
add_action( \'the_post\', [ $this, \'the_post\' ] );
add_action( \'wp_footer\', [ $this, \'footer\' ] );
}
public function the_post( $post ) {
//* Only do this once
remove_action( \'the_post\', [ $this, \'the_post\' ] );
//* This is the property we\'re interested in
$this->ID = $post->ID;
}
public function footer() {
//* Print the ID property in the footer
echo $this->ID;
}
}
//* Initiate the class and hook into init
add_action( \'init\', [ $wpse_263293 = new wpse_263293(), \'init\' ] );