admin管理员组

文章数量:1122846

I have 2 main problems:

  1. I can't seem to add editor_name custom field to default/native WordPress list of request URL query parameters.

This is the request WordPress is using:

http://localhost/wp-json/wp/v2/faq_category?context=view&per_page=100&orderby=name&order=asc&_fields=id%2Cname%2Cparent&_locale=user

I want to "intercept" the default request params and add my custom editor_name as field to retrieve from the database.

  1. I just notice something odd, that didn't happen before. I add the query parameter to the Request URL Wordpress is using, and it still doesn't retrieve the editor_name.

I have defined the following Custom Post Type, with its Categories Taxonomy, and custom Meta Box.

In my faqs.php file:

<?php

// Register Custom Post Type for FAQs
function register_faqs_post_type()
{
    $labels = array(
        'name'                  => 'FAQs',
        'singular_name'         => 'FAQ',
        'menu_name'             => 'FAQs',
        'name_admin_bar'        => 'FAQ',
        'archives'              => 'FAQ Archives',
        'attributes'            => 'FAQ Attributes',
        'parent_item_colon'     => 'Parent FAQ:',
        'all_items'             => 'All FAQs',
        'add_new_item'          => 'Add New FAQ',
        'add_new'               => 'Add New',
        'new_item'              => 'New FAQ',
        'edit_item'             => 'Edit FAQ',
        'update_item'           => 'Update FAQ',
        'view_item'             => 'View FAQ',
        'view_items'            => 'View FAQs',
        'search_items'          => 'Search FAQ',
        'not_found'             => 'FAQ not found',
        'not_found_in_trash'    => 'FAQ not found in Trash',
        'featured_image'        => 'Featured Image',
        'set_featured_image'    => 'Set featured image',
        'remove_featured_image' => 'Remove featured image',
        'use_featured_image'    => 'Use as featured image',
        'insert_into_item'      => 'Insert into FAQ',
        'uploaded_to_this_item' => 'Uploaded to this FAQ',
        'items_list'            => 'FAQs list',
        'items_list_navigation' => 'FAQs list navigation',
        'filter_items_list'     => 'Filter FAQs list',
    );
    $args = array(
        'label'                 => 'FAQ',
        'description'           => 'Frequently Asked Questions',
        'labels'                => $labels,
        'supports'              => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments'),
        'taxonomies'            => array('faq_category'), //  new custom taxonomy
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 5,
        'menu_icon'             => 'dashicons-editor-help',
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'       => 'page',
        'show_in_rest'          => true,
    );
    register_post_type('faqs', $args);
}
add_action('init', 'register_faqs_post_type', 0);



// Register Custom Taxonomy for FAQ Categories
function register_faq_category_taxonomy()
{
    $labels = array(
        'name'                       => 'FAQ Categories',
        'singular_name'              => 'FAQ Category',
        'menu_name'                  => 'FAQ Categories',
        'all_items'                  => 'All FAQ Categories',
        'parent_item'                => 'Parent FAQ Category',
        'parent_item_colon'          => 'Parent FAQ Category:',
        'new_item_name'              => 'New FAQ Category Name',
        'add_new_item'               => 'Add New FAQ Category',
        'edit_item'                  => 'Edit FAQ Category',
        'update_item'                => 'Update FAQ Category',
        'view_item'                  => 'View FAQ Category',
        'separate_items_with_commas' => 'Separate FAQ categories with commas',
        'add_or_remove_items'        => 'Add or remove FAQ categories',
        'choose_from_most_used'      => 'Choose from the most used FAQ categories',
        'popular_items'              => 'Popular FAQ Categories',
        'search_items'               => 'Search FAQ Categories',
        'not_found'                  => 'Not Found',
        'no_terms'                   => 'No FAQ categories',
        'items_list'                 => 'FAQ categories list',
        'items_list_navigation'      => 'FAQ categories list navigation',
    );
    $args = array(
        'labels'                     => $labels,
        'hierarchical'               => true,
        'public'                     => true,
        'show_ui'                    => true,
        'show_admin_column'          => true,
        'show_in_nav_menus'          => true,
        'show_tagcloud'              => true,
        'show_in_rest'               => true,
    );
    register_taxonomy('faq_category', array('faqs'), $args);
}
add_action('init', 'register_faq_category_taxonomy', 0);


// Add Editor Name Field to FAQ Categories (for creation)
function add_faq_category_meta_box() {
    ?>
    <div class="form-field term-editor-name-wrap">
        <label for="editor-name"><?php _e('Editor Name', 'text_domain'); ?></label>
        <input type="text" name="editor_name" id="editor-name" value="" />
        <p class="description"><?php _e('Enter the name to display in the editor.', 'text_domain'); ?></p>
    </div>
    <?php
}
add_action('faq_category_add_form_fields', 'add_faq_category_meta_box', 10, 2);

// Add Editor Name Field to FAQ Categories (for editing)
function edit_faq_category_meta_box($term) {
    $editor_name = get_term_meta($term->term_id, 'editor_name', true);
    ?>
    <tr class="form-field term-editor-name-wrap">
        <th scope="row">
            <label for="editor-name"><?php _e('Editor Name', 'text_domain'); ?></label>
        </th>
        <td>
            <input type="text" name="editor_name" id="editor-name" value="<?php echo esc_attr($editor_name); ?>" />
            <p class="description"><?php _e('Enter the name to display in the editor.', 'text_domain'); ?></p>
        </td>
    </tr>
    <?php
}
add_action('faq_category_edit_form_fields', 'edit_faq_category_meta_box', 10, 2);

// Save Editor Name Field
function save_faq_category_meta($term_id) {
    if (isset($_POST['editor_name'])) {
        update_term_meta($term_id, 'editor_name', sanitize_text_field($_POST['editor_name']));
    }
}
add_action('edited_faq_category', 'save_faq_category_meta');
add_action('create_faq_category', 'save_faq_category_meta');

// Filter the display of FAQ categories in the editor and client side
function filter_faq_category_display($terms, $post_id, $taxonomy) {
    if ($taxonomy === 'faq_category') {
        foreach ($terms as $key => $term) {
            if (is_admin()) {
                $editor_name = get_term_meta($term->term_id, 'editor_name', true);
                if (!empty($editor_name)) {
                    $term->name = $editor_name;
                }
            }
        }
    }
    return $terms;
}
add_filter('get_the_terms', 'filter_faq_category_display', 10, 3);

The problem is in my faqs-service.php file, I believe:

<?php

/**
 * Registers the REST API routes for FAQ endpoints.
 */
function faqs_api()
{
    register_rest_route('wp/v2', '/faqs/categories', array(
        'methods' => 'GET',
        'callback' => 'get_faq_categories',
    ));

    register_rest_route('wp/v2', '/faqs/category/(?P<id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'get_faqs_by_category_id',
    ));
}

/**
 * Retrieves all FAQ categories.
 *
 * @return WP_REST_Response The response containing the formatted categories.
 */
function get_faq_categories()
{
    // Get all FAQ categories
    $categories = get_terms(array(
        'taxonomy' => 'faq_category', // Change 'category' to your custom category taxonomy if needed
        'hide_empty' => false,
        'exclude'    => array(1), // Exclude categories with ID equal to 1
    ));

    $formatted_categories = array();

    // Format categories data
    foreach ($categories as $category) {
        $editor_name = get_term_meta($category->term_id, 'editor_name', true);
        $formatted_categories[] = array(
            'id'          => $category->term_id,
            'name'        => $category->name,
            'slug'        => $category->slug,
            'editor_name' => $editor_name ? $editor_name : $category->name,
        );
    }

    // Return JSON response
    return rest_ensure_response($formatted_categories);
}

/**
 * Retrieves FAQs by category ID.
 *
 * @param WP_REST_Request $data The request object.
 * @return WP_REST_Response The response containing the formatted FAQs.
 */
function get_faqs_by_category_id($data)
{
    // Get category ID from the request
    $category_id = $data['id'];

    // Query FAQs by category ID
    $args = array(
        'post_type'      => 'faqs', // Change 'faqs' to your custom post type name
        'posts_per_page' => -1, // Retrieve all posts
        'tax_query'      => array(
            array(
                'taxonomy' => 'faq_category', // Change 'faq_category' to your custom category taxonomy if needed
                'field'    => 'term_id',
                'terms'    => $category_id,
            ),
        ),
        'orderby'        => 'date', // Order by creation date
        'order'          => 'ASC', // Ascending order
    );
    $faqs_query = new WP_Query($args);

    $faqs = array();

    // Format FAQ data
    if ($faqs_query->have_posts()) {
        while ($faqs_query->have_posts()) {
            $faqs_query->the_post();

            $faq = array(
                'question'    => get_the_title(), // Retrieve the post title
                'answer'  => get_the_content(), // Retrieve the post content
            );

            $faqs[] = $faq;
        }
    }

    // Reset post data
    wp_reset_postdata();

    // Prepare the response
    $response = array(
        'faqs' => $faqs,
        'debug' => array(
            'category_id' => $category_id,
            'args' => $args,
            'faqs_query' => $faqs_query,
        )
    );

    // Return JSON response
    return rest_ensure_response($response);
}


// Hook into the REST API initialization
add_action('rest_api_init', 'faqs_api');

I tried almost everything, and I'm currently burntout with this issue.

Thanks for the help.

I have 2 main problems:

  1. I can't seem to add editor_name custom field to default/native WordPress list of request URL query parameters.

This is the request WordPress is using:

http://localhost/wp-json/wp/v2/faq_category?context=view&per_page=100&orderby=name&order=asc&_fields=id%2Cname%2Cparent&_locale=user

I want to "intercept" the default request params and add my custom editor_name as field to retrieve from the database.

  1. I just notice something odd, that didn't happen before. I add the query parameter to the Request URL Wordpress is using, and it still doesn't retrieve the editor_name.

I have defined the following Custom Post Type, with its Categories Taxonomy, and custom Meta Box.

In my faqs.php file:

<?php

// Register Custom Post Type for FAQs
function register_faqs_post_type()
{
    $labels = array(
        'name'                  => 'FAQs',
        'singular_name'         => 'FAQ',
        'menu_name'             => 'FAQs',
        'name_admin_bar'        => 'FAQ',
        'archives'              => 'FAQ Archives',
        'attributes'            => 'FAQ Attributes',
        'parent_item_colon'     => 'Parent FAQ:',
        'all_items'             => 'All FAQs',
        'add_new_item'          => 'Add New FAQ',
        'add_new'               => 'Add New',
        'new_item'              => 'New FAQ',
        'edit_item'             => 'Edit FAQ',
        'update_item'           => 'Update FAQ',
        'view_item'             => 'View FAQ',
        'view_items'            => 'View FAQs',
        'search_items'          => 'Search FAQ',
        'not_found'             => 'FAQ not found',
        'not_found_in_trash'    => 'FAQ not found in Trash',
        'featured_image'        => 'Featured Image',
        'set_featured_image'    => 'Set featured image',
        'remove_featured_image' => 'Remove featured image',
        'use_featured_image'    => 'Use as featured image',
        'insert_into_item'      => 'Insert into FAQ',
        'uploaded_to_this_item' => 'Uploaded to this FAQ',
        'items_list'            => 'FAQs list',
        'items_list_navigation' => 'FAQs list navigation',
        'filter_items_list'     => 'Filter FAQs list',
    );
    $args = array(
        'label'                 => 'FAQ',
        'description'           => 'Frequently Asked Questions',
        'labels'                => $labels,
        'supports'              => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments'),
        'taxonomies'            => array('faq_category'), //  new custom taxonomy
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 5,
        'menu_icon'             => 'dashicons-editor-help',
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'       => 'page',
        'show_in_rest'          => true,
    );
    register_post_type('faqs', $args);
}
add_action('init', 'register_faqs_post_type', 0);



// Register Custom Taxonomy for FAQ Categories
function register_faq_category_taxonomy()
{
    $labels = array(
        'name'                       => 'FAQ Categories',
        'singular_name'              => 'FAQ Category',
        'menu_name'                  => 'FAQ Categories',
        'all_items'                  => 'All FAQ Categories',
        'parent_item'                => 'Parent FAQ Category',
        'parent_item_colon'          => 'Parent FAQ Category:',
        'new_item_name'              => 'New FAQ Category Name',
        'add_new_item'               => 'Add New FAQ Category',
        'edit_item'                  => 'Edit FAQ Category',
        'update_item'                => 'Update FAQ Category',
        'view_item'                  => 'View FAQ Category',
        'separate_items_with_commas' => 'Separate FAQ categories with commas',
        'add_or_remove_items'        => 'Add or remove FAQ categories',
        'choose_from_most_used'      => 'Choose from the most used FAQ categories',
        'popular_items'              => 'Popular FAQ Categories',
        'search_items'               => 'Search FAQ Categories',
        'not_found'                  => 'Not Found',
        'no_terms'                   => 'No FAQ categories',
        'items_list'                 => 'FAQ categories list',
        'items_list_navigation'      => 'FAQ categories list navigation',
    );
    $args = array(
        'labels'                     => $labels,
        'hierarchical'               => true,
        'public'                     => true,
        'show_ui'                    => true,
        'show_admin_column'          => true,
        'show_in_nav_menus'          => true,
        'show_tagcloud'              => true,
        'show_in_rest'               => true,
    );
    register_taxonomy('faq_category', array('faqs'), $args);
}
add_action('init', 'register_faq_category_taxonomy', 0);


// Add Editor Name Field to FAQ Categories (for creation)
function add_faq_category_meta_box() {
    ?>
    <div class="form-field term-editor-name-wrap">
        <label for="editor-name"><?php _e('Editor Name', 'text_domain'); ?></label>
        <input type="text" name="editor_name" id="editor-name" value="" />
        <p class="description"><?php _e('Enter the name to display in the editor.', 'text_domain'); ?></p>
    </div>
    <?php
}
add_action('faq_category_add_form_fields', 'add_faq_category_meta_box', 10, 2);

// Add Editor Name Field to FAQ Categories (for editing)
function edit_faq_category_meta_box($term) {
    $editor_name = get_term_meta($term->term_id, 'editor_name', true);
    ?>
    <tr class="form-field term-editor-name-wrap">
        <th scope="row">
            <label for="editor-name"><?php _e('Editor Name', 'text_domain'); ?></label>
        </th>
        <td>
            <input type="text" name="editor_name" id="editor-name" value="<?php echo esc_attr($editor_name); ?>" />
            <p class="description"><?php _e('Enter the name to display in the editor.', 'text_domain'); ?></p>
        </td>
    </tr>
    <?php
}
add_action('faq_category_edit_form_fields', 'edit_faq_category_meta_box', 10, 2);

// Save Editor Name Field
function save_faq_category_meta($term_id) {
    if (isset($_POST['editor_name'])) {
        update_term_meta($term_id, 'editor_name', sanitize_text_field($_POST['editor_name']));
    }
}
add_action('edited_faq_category', 'save_faq_category_meta');
add_action('create_faq_category', 'save_faq_category_meta');

// Filter the display of FAQ categories in the editor and client side
function filter_faq_category_display($terms, $post_id, $taxonomy) {
    if ($taxonomy === 'faq_category') {
        foreach ($terms as $key => $term) {
            if (is_admin()) {
                $editor_name = get_term_meta($term->term_id, 'editor_name', true);
                if (!empty($editor_name)) {
                    $term->name = $editor_name;
                }
            }
        }
    }
    return $terms;
}
add_filter('get_the_terms', 'filter_faq_category_display', 10, 3);

The problem is in my faqs-service.php file, I believe:

<?php

/**
 * Registers the REST API routes for FAQ endpoints.
 */
function faqs_api()
{
    register_rest_route('wp/v2', '/faqs/categories', array(
        'methods' => 'GET',
        'callback' => 'get_faq_categories',
    ));

    register_rest_route('wp/v2', '/faqs/category/(?P<id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'get_faqs_by_category_id',
    ));
}

/**
 * Retrieves all FAQ categories.
 *
 * @return WP_REST_Response The response containing the formatted categories.
 */
function get_faq_categories()
{
    // Get all FAQ categories
    $categories = get_terms(array(
        'taxonomy' => 'faq_category', // Change 'category' to your custom category taxonomy if needed
        'hide_empty' => false,
        'exclude'    => array(1), // Exclude categories with ID equal to 1
    ));

    $formatted_categories = array();

    // Format categories data
    foreach ($categories as $category) {
        $editor_name = get_term_meta($category->term_id, 'editor_name', true);
        $formatted_categories[] = array(
            'id'          => $category->term_id,
            'name'        => $category->name,
            'slug'        => $category->slug,
            'editor_name' => $editor_name ? $editor_name : $category->name,
        );
    }

    // Return JSON response
    return rest_ensure_response($formatted_categories);
}

/**
 * Retrieves FAQs by category ID.
 *
 * @param WP_REST_Request $data The request object.
 * @return WP_REST_Response The response containing the formatted FAQs.
 */
function get_faqs_by_category_id($data)
{
    // Get category ID from the request
    $category_id = $data['id'];

    // Query FAQs by category ID
    $args = array(
        'post_type'      => 'faqs', // Change 'faqs' to your custom post type name
        'posts_per_page' => -1, // Retrieve all posts
        'tax_query'      => array(
            array(
                'taxonomy' => 'faq_category', // Change 'faq_category' to your custom category taxonomy if needed
                'field'    => 'term_id',
                'terms'    => $category_id,
            ),
        ),
        'orderby'        => 'date', // Order by creation date
        'order'          => 'ASC', // Ascending order
    );
    $faqs_query = new WP_Query($args);

    $faqs = array();

    // Format FAQ data
    if ($faqs_query->have_posts()) {
        while ($faqs_query->have_posts()) {
            $faqs_query->the_post();

            $faq = array(
                'question'    => get_the_title(), // Retrieve the post title
                'answer'  => get_the_content(), // Retrieve the post content
            );

            $faqs[] = $faq;
        }
    }

    // Reset post data
    wp_reset_postdata();

    // Prepare the response
    $response = array(
        'faqs' => $faqs,
        'debug' => array(
            'category_id' => $category_id,
            'args' => $args,
            'faqs_query' => $faqs_query,
        )
    );

    // Return JSON response
    return rest_ensure_response($response);
}


// Hook into the REST API initialization
add_action('rest_api_init', 'faqs_api');

I tried almost everything, and I'm currently burntout with this issue.

Thanks for the help.

Share Improve this question edited Aug 23, 2024 at 13:31 neke90 asked Aug 23, 2024 at 13:29 neke90neke90 11 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

To solve the problem of adding the editor_name custom field to the default WordPress REST API request for categories, we need to take a few steps to ensure that the custom field is correctly registered and included in the REST API responses.

  1. Register the Custom Field in the REST API Response: You need to register the editor_name field to be included in the REST API responses for your custom taxonomy faq_category. You can do this using the register_rest_field() function.

Here's how you can update your faqs-service.php file:

// Register the REST API routes for FAQ endpoints.
function faqs_api() {
    register_rest_route('wp/v2', '/faqs/categories', array(
        'methods' => 'GET',
        'callback' => 'get_faq_categories',
    ));

    register_rest_route('wp/v2', '/faqs/category/(?P<id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'get_faqs_by_category_id',
    ));
}

// Register the custom field editor_name for the REST API response
function register_faq_category_fields() {
    register_rest_field('faq_category', 'editor_name', array(
        'get_callback' => 'get_faq_category_editor_name',
        'update_callback' => null,
        'schema' => null,
    ));
}

// Callback function to retrieve the editor_name field
function get_faq_category_editor_name($object, $field_name, $request) {
    return get_term_meta($object['id'], $field_name, true);
}

// Hook into the REST API initialization
add_action('rest_api_init', 'faqs_api');
add_action('rest_api_init', 'register_faq_category_fields');
  1. Ensure the Field is Saved Properly: Make sure that the editor_name field is being saved correctly when you add or edit a category. You've already handled this in your save_faq_category_meta() function.

  2. Modify the Custom REST Route (if needed): If you still want to use your custom REST routes, you should ensure that the editor_name field is included in the response. You've mostly handled this in the get_faq_categories() function by manually retrieving the editor_name meta field.

  3. Testing the REST API: You can now test the REST API by accessing the endpoint. The default WordPress REST API query for faq_category should now include the editor_name field. The following request should retrieve the categories with the editor_name field included: http://localhost/wp-json/wp/v2/faq_category?context=view&per_page=100&orderby=name&order=asc&_fields=id,name,parent,editor_name&_locale=user

Troubleshooting:

Ensure caching is disabled: If you're not seeing the expected results, ensure that no caching is interfering with your API responses. Debugging: Add logging or debugging statements in your functions to track the flow and see if the fields are being fetched and added correctly. With these changes, your editor_name field should be correctly added to the REST API responses for your custom taxonomy.

本文标签: Can39t retrieve custom post type taxonomy term to custom post type editor