admin管理员组

文章数量:1122832

After reading this answer here, I can get the currently selected/checked terms for categories using this code:

wp.data.select("core/editor").getCurrentPostAttribute("categories")

However, this doesn't seem to work with custom taxonomies created with register_taxonomy(). Is there any other way to do this?

This merge seems like it might be relevant, but it's kind of hard for me to understand what's being implemented there.

After reading this answer here, I can get the currently selected/checked terms for categories using this code:

wp.data.select("core/editor").getCurrentPostAttribute("categories")

However, this doesn't seem to work with custom taxonomies created with register_taxonomy(). Is there any other way to do this?

This merge seems like it might be relevant, but it's kind of hard for me to understand what's being implemented there.

Share Improve this question asked Jan 9, 2019 at 9:38 Aidan McArthurAidan McArthur 134 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 3

When you register a custom taxonomy make sure to set show_in_rest to true. This way the taxonomy will show in the REST API which is what Gutenberg uses to get the data. Then you can use the selector:

wp.data.select("core/editor").getCurrentPostAttribute("my_taxonomy");

It's surprising how little information is available on this topic. Here’s my solution for retrieving the selected terms for a custom taxonomy:

    const taxonomySlug = 'your-taxonomy';

    // Get the selected series IDs
    const selectedSeries = useSelect(( select ) =>
        select('core/editor').getEditedPostAttribute(taxonomySlug),
    );

    // Get all series terms
    const seriesTerms = useSelect(( select ) =>
        select('core').getEntityRecords('taxonomy', taxonomySlug, {
            object_id: postId,
        }),
    );

    // Filter selected terms based on the selected series IDs
    const selectedTerms = seriesTerms
        ? seriesTerms.filter(( term ) => selectedSeries.includes(term.id))
        : [];

本文标签: Getting the selected terms for custom taxonomies in the editor