Wordpress函数在类成员函数中不可用

时间:2018-01-07 03:24:04

标签: php wordpress oop

我正在构建一个Wordpress插件,该插件具有通过AJAX运行的独立PHP。因此我正在使用

define( 'SHORTINIT', true );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );

位于PHP文件的顶部,以便Wordpress函数在我的类及其成员函数中可用。但是,Wordpress功能在成员函数中不可用。

这是我班级的简化版本,但我收到错误:

  

未捕获错误:调用未定义的函数wp_insert_post()

define( 'SHORTINIT', true );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );

class fpe_events {

    public function add_post_and_meta( $post_data ) {

        if( $post_data["ID"] ) {

            // Post exists, update it

            wp_update_post( $post_data );

        } else {

            wp_insert_post( $post_data );

        }

    }
}

1 个答案:

答案 0 :(得分:0)

您应该在WordPress插件文件中执行PHP代码。

以下是一个例子:

将您的JS文件添加到插件主PHP:

wp_enqueue_script( 'your-script', plugins_url( '/js-file.js', __FILE__ ), 
array('jquery'), '1.0', true );

wp_localize_script( 'your-script', 'your_awesome_name', array(
    'ajax_url' => admin_url( 'admin-ajax.php' )
));

Ajax的呼叫:

jQuery( document ).on( 'click', '.simple-button', function() {
var post_id = jQuery(this).data('id');
jQuery.ajax({
    url : your_awesome_name.ajax_url,
    type : 'post',
    data : {
        action : 'my_php_script',
        post_id : post_id
    },
    success : function( response ) {
        alert(response)
    }
});
})

在你的Plugin php文件上运行:

add_action( 'wp_ajax_my_action', 'my_php_script' );

function my_php_script() {
  //your php script
wp_die();
}

或阅读codex:https://codex.wordpress.org/AJAX_in_Plugins

相关问题