donglian5309 2018-01-07 03:24
浏览 31

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

I am building a Wordpress plugin that has standalone PHP that is run via AJAX. As such I am using

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

at the top of the PHP file so that Wordpress functions are available throughout my class and its member functions. However, the Wordpress functions are not available in the member functions.

This is a simplified version of my class but I am getting the error :

Uncaught Error: Call to undefined function 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条回答 默认 最新

  • dpge74512 2018-01-07 19:03
    关注

    You should do your PHP-Code in WordPress Plugin files.

    Here is an example:

    Add your JS-File to Plugin Main 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-Call:

    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)
        }
    });
    })
    

    And run on your Plugin php file this:

    add_action( 'wp_ajax_my_action', 'my_php_script' );
    
    function my_php_script() {
      //your php script
    wp_die();
    }
    

    Or read the codex: https://codex.wordpress.org/AJAX_in_Plugins

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看