【问题标题】:Cannot modify header error when creating rest api in wordpress在wordpress中创建rest api时无法修改标题错误
【发布时间】:2017-02-21 14:11:13
【问题描述】:

我正在尝试创建一个REST API,它为wordpress 帖子生成json 数据。下面的代码在 functions.php 文件中:

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

在新的wordpress 安装中运行良好。但是当我在我的在线网站中实现它时,它给了我错误

警告:无法修改标头信息 - 标头已由 (输出开始于 /home1/public_html/blogsite/wp-content/themes/webtheme/header.php:10) 在 /home1/public_html/website-theme/wp-content/themes/webtheme/functions.php 在第 159 行

header.php 的第 10 行是 wp_head()

我不知道如何解决这个错误,只生成json 数据。

【问题讨论】:

    标签: php json wordpress rest


    【解决方案1】:

    您需要创建自定义 AJAX 操作。 你会在 codex 上找到你需要的一切: https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

    或者您可以使用 Wordpress REST API 插件。它允许您创建自己的 API 端点。 https://wordpress.org/plugins/rest-api/

    编辑 我举个小例子,用jQuery ajax代码来调用它。

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

    【讨论】:

    • 谢谢。但是当我使用这个钩子时,它不会返回任何 json 数据
    • 我正在按照您的回答尝试使用 url http://localhost:1234,它返回整个页面内容而不是仅返回 json 数据。
    • 这很奇怪,我已经在我的本地主机上的一个空 wordpress 上复制了我的代码,它的工作。验证或 ajax 调用 URL。我有这个:url : "http://127.0.0.1/wp-test/wp-admin/admin-ajax.php",
    • 我将这个hook 添加到functions.php 文件中。这行得通吗?
    • 所有钩子都需要在主题functions.php中,或者包含在主插件的文件中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    相关资源
    最近更新 更多