致命错误:未捕获错误:调用未定义函数get_posts()wordpress

时间:2017-08-10 08:27:19

标签: php ajax wordpress

我有关于如何将自己的ajax注册到wordpress的问题我已经阅读了this并且还遵循了this教程但似乎发生了错误

错误

  

致命错误:未捕获错误:调用未定义函数get_posts()   ... \文案主题\ orderer_creator_data.php:4   堆栈跟踪:#0 {main}被抛入   ... \文案主题\ orderer_creator_data.php   第4行

这是我的 PHP

if(isset($_POST['type'])){
    $posts = get_posts(   //this is the line 4
            array(
                    'post_type'   => 'orderer',
                    'post_status' => 'publish',
                    'posts_per_page' => -1,
                    'fields' => 'ids'
                )
            );
    $data = array();
    //loop over each post
    foreach($posts as $p){
        //get the meta you need form each post
        $data[] = array(
                "family_name" => get_post_meta($p,"family_name",true),
                "given_name" => get_post_meta($p,"given_name",true),
                "email" => get_post_meta($p,"e-mail_address",true),
                "reg_date" => $post->post_date,
                "last_mod" => $post->post_modified
        );
    }

    echo json_encode($data);
}

我的 Ajax

$(".toggle").on("change",function(){
        $.ajax({
            url: url,
            type: "POST",
            data: {type: $(".toggle option:selected").val()},
            success: function(result){
                $(".print").append(result);
            }
        });
    });

到目前为止,我尝试的是创建一个插件并注册他们的ajax。

插件

add_action( 'init', 'my_script_enqueuer' );

function my_script_enqueuer() {
    wp_register_script( "ajax_script", get_stylesheet_directory_uri().'/js/copywriter.js', array('jquery'));
    wp_localize_script( 'ajax_script', 'Ajax_call', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));

    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'ajax_script' );

}

1 个答案:

答案 0 :(得分:0)

您需要使用操作附加它,以便在代码执行之前加载默认函数。

function handle_ajax_request(){
    if(isset($_POST['type'])){
    $posts = get_posts(   //this is the line 4
        array(
                'post_type'   => 'orderer',
                'post_status' => 'publish',
                'posts_per_page' => -1,
                'fields' => 'ids'
            )
        );
    $data = array();
    //loop over each post
    foreach($posts as $p){
        //get the meta you need form each post
        $data[] = array(
            "family_name" => get_post_meta($p,"family_name",true),
            "given_name" => get_post_meta($p,"given_name",true),
            "email" => get_post_meta($p,"e-mail_address",true),
            "reg_date" => $post->post_date,
            "last_mod" => $post->post_modified
        );
    }

    echo json_encode($data);
    }


}

add_action( 'init', 'handle_ajax_request' );