dongrong7883 2017-02-21 14:11
浏览 105
已采纳

在wordpress中创建rest api时无法修改头错误

I am trying to create a REST API which generate json data for wordpress posts. The code below is in functions.php file:

add_action('wp_enqueue_scripts', 'create_json_data', 0);
function create_json_data(){
    ob_start();
    if (isset($_GET['getjson'])  && $_GET['getjson'] == true) {
        if (have_posts()) {
            $data = array();
            while (have_posts()) {
                the_post();
                $new_data = array(
                    "title" => get_the_title(), 
                    "content" => get_the_excerpt(), 
                    "image" => get_the_post_thumbnail_url(),
                    "hyperlink" => get_the_permalink()
                    );
                array_push($data, $new_data);
            }
        }
        header('Content-type: application/json');
        echo json_encode($data);
        exit();
    }
    ob_end_flush();
}

It runs very well in newly wordpress installation. But when I implement it in my online website it gives me error

Warning: Cannot modify header information - headers already sent by (output started at /home1/public_html/blogsite/wp-content/themes/webtheme/header.php:10) in /home1/public_html/website-theme/wp-content/themes/webtheme/functions.php on line 159

at line 10 in header.php is wp_head()

I don't know how to get ride of this error to generate json data only.

  • 写回答

1条回答 默认 最新

  • dongxin991209 2017-02-21 14:19
    关注

    You need to create custom AJAX action. You will find everything you need on the codex : https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

    Or you can use the Wordpress REST API plugin. It's allow you to create your own API endpoint. https://wordpress.org/plugins/rest-api/

    EDIT I give you a little example, with the jQuery ajax code to call it.

    add_action('wp_ajax_XXXXXX', 'ajax_XXXXXX');
    add_action('wp_ajax_nopriv_XXXXXX', 'ajax_XXXXXX');
    function ajax_XXXXXX() {
        header('Content-Type: application/json');
        echo json_encode(array(
            'text' => "Lorem ipsum dolor ...",
            'time' => time(),
            'user_id' => get_current_user_id()
        ));
        die();
    }
    
    $.ajax({
        url : "/wp-admin/admin-ajax.php",
        method : "POST",
        data : {
            action : "XXXXXX"
        },
        success : function(datas) {
            console.log(datas);
        }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建