From a6a04bebfb96f47df6c1f238c0fe63233d6dd3f5 Mon Sep 17 00:00:00 2001 From: Bernie Reiter <96308+ockham@users.noreply.github.com> Date: Mon, 25 Nov 2024 11:20:51 +0100 Subject: [PATCH] Terms: Respect order specified by register_taxonomy() (#67154) It is possible to supply a default set of `args` to `register_taxonomy()` which will be used when querying a list of terms -- for example, `orderby` in order to specify how the resulting list of terms should be sorted. This commit makes it so that the list of terms returned by the Terms REST API controller respects that order. Co-authored-by: ockham Co-authored-by: jsnajdr --- backport-changelog/6.8/7848.md | 3 +++ lib/compat/wordpress-6.8/rest-api.php | 29 +++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 backport-changelog/6.8/7848.md diff --git a/backport-changelog/6.8/7848.md b/backport-changelog/6.8/7848.md new file mode 100644 index 00000000000000..84600eb4847cdb --- /dev/null +++ b/backport-changelog/6.8/7848.md @@ -0,0 +1,3 @@ +https://github.com/WordPress/wordpress-develop/pull/7848 + +* https://github.com/WordPress/gutenberg/pull/67154 diff --git a/lib/compat/wordpress-6.8/rest-api.php b/lib/compat/wordpress-6.8/rest-api.php index da1b657cda0783..080e4003f57b38 100644 --- a/lib/compat/wordpress-6.8/rest-api.php +++ b/lib/compat/wordpress-6.8/rest-api.php @@ -20,3 +20,32 @@ function gutenberg_add_post_type_rendering_mode() { } } add_action( 'rest_api_init', 'gutenberg_add_post_type_rendering_mode' ); + +// When querying terms for a given taxonomy in the REST API, respect the default +// query arguments set for that taxonomy upon registration. +function gutenberg_respect_taxonomy_default_args_in_rest_api( $args ) { + // If a `post` argument is provided, the Terms controller will use + // `wp_get_object_terms`, which respects the default query arguments, + // so we don't need to do anything. + if ( ! empty( $args['post'] ) ) { + return $args; + } + + $t = get_taxonomy( $args['taxonomy'] ); + if ( isset( $t->args ) && is_array( $t->args ) ) { + $args = array_merge( $args, $t->args ); + } + return $args; +} +add_action( + 'registered_taxonomy', + function ( $taxonomy ) { + add_filter( "rest_{$taxonomy}_query", 'gutenberg_respect_taxonomy_default_args_in_rest_api' ); + } +); +add_action( + 'unregistered_taxonomy', + function ( $taxonomy ) { + remove_filter( "rest_{$taxonomy}_query", 'gutenberg_respect_taxonomy_default_args_in_rest_api' ); + } +);