問題描述

如何使用 WP REST API(v1 或 v2) 獲取特定自定義帖子類型的所有帖子?我很新,試圖理解如何做到這一點。

我目前正在使用 WP REST API v2,並通過這種方式獲取所有帖子類型的列表

http://domain.com/wp-json/wp/v2/types

然後設法獲取我感興趣的帖子類型

http://domain.com/wp-json/wp/v2/types/the-icons-update

如何獲取該特定內容類型的所有帖子?

我試過了

http://domain.com/wp-json/wp/v2/posts?filter[post_type]=the-icons-update

但它返回一個空數組 (我想它返回默認的帖子,在我的網站上只有我正在嘗試檢索的自定義帖子類型中的帖子) 。

可能會有一個問題,我如何註冊的帖子類型?

function custom_post_type() {
$labels = array(
    'name'               => _x( 'The Icons Update', 'post type general name' ),
    'singular_name'      => _x( 'The Icons Update', 'post type singular name' ),
    'add_new'            => _x( 'Add Page', 'magazine' ),
    'add_new_item'       => __( 'Add New Page' ),
    'edit_item'          => __( 'Edit Page' ),
    'new_item'           => __( 'New Page' ),
    'all_items'          => __( 'All Pages' ),
    'view_item'          => __( 'View Page' ),
    'search_items'       => __( 'Search Pages' ),
    'not_found'          => __( 'No Page found' ),
    'not_found_in_trash' => __( 'No Page found in the Trash' ),
    'parent_item_colon'  => '',
    'menu_icon'          => '',
    'menu_name'          => 'The Icons Update'
);
$args = array(
    'labels'        => $labels,
    'description'   => 'Holds our projects and project specific data',
    'public'        => true,
    'menu_position' => 5,
    'supports'      => array( 'title', 'editor', 'thumbnail', 'excerpt', 'custom-fields' ),
    'has_archive'   => true,
    'taxonomies'    => array('post_tag', 'category'),
    'hierarchical'  => false,
    'query_var'     => true,
    'queryable' => true,
        'searchable'    => true,
    'rewrite'       => array( 'slug' => 'the-icons-update' )
);
register_post_type( 'magazine', $args );
flush_rewrite_rules();
}
add_action( 'init', 'custom_post_type' );

任何幫助這是非常感謝。

最佳解決方案

只需將下一個參數添加到功能 register_post_type 中,就可以在’menu_position’ 參數之前。 ‘show_in_rest’ => 真正

如果您使用插件註冊您的 posttype,您可以使用下一個代碼:

add_action( 'init', 'add_anuncios_to_json_api', 30 );
function add_anuncios_to_json_api(){
    global $wp_post_types;
    $wp_post_types['anuncio']->show_in_rest = true;
}

之後,您將能夠從 mydomain.com/wp-json/wp/v2/posttype_slug 列出您的帖子

在我的情況下:mydomain.com/wp-json/wp/v2/anuncio

您還可以使用下一個代碼註冊新的基數:

add_action( 'init', 'add_anuncios_to_json_api', 30 );
function add_anuncios_to_json_api(){
    global $wp_post_types;
    $wp_post_types['anuncio']->show_in_rest = true;
    $wp_post_types['anuncio']->rest_base = 'clasi';
    $wp_post_types['anuncio']->rest_controller_class = 'WP_REST_Posts_Controller';
}

只需替換 anuncio 作為您的帖子類型的插件,’clasi’ 將成為您的路由。 mydomain.com/wp-json/wp/v2/clasi

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。