首页 > 解决方案 > 如何使用 WordPress REST API 获取单个自定义 Post-Type 项目

问题描述

我有一个名为的自定义帖子类型product,它有一个带有标题、没有帖子内容和一堆自定义元的帖子。我下面的 jQuery 代码返回 404 错误。到目前为止,我还没有在 WP Rest API 文档中找到有关获取单个自定义帖子类型帖子的任何内容,尽管我确实看到您可以使用post帖子类型这样做。我正在尝试做的事情还可能吗?

jQuery(document).ready(function($){

    $( '#product-select' ).on( 'change', function(){ //changing a drop-down triggers the function
        var productID = $(this).val();

        $.ajax({
            type: 'GET',
            url: '/wp-json/wp/v2/types/product/137', // <= /product works but /product/137 does not
            success: function( data ){
                console.log( data );
            }
        });
    });
});

标签: jqueryajaxcustom-post-typewordpress-rest-api

解决方案


URL 是/wp-json/wp/v2/product- 删除“类型”路径。show_in_rest并在注册您的cpt 时检查您是否已设置为true。

这也是一个非常常见的用例,因此谷歌搜索“wordpress rest api custom post type”会很容易地向您展示这一点。

请参阅文档:https ://developer.wordpress.org/rest-api/extending-the-rest-api/adding-rest-api-support-for-custom-content-types/


推荐阅读