LoginSignup
0
0

More than 1 year has passed since last update.

IntuitiveCustomPostOrderとget_terms()を併用できない条件がある

Last updated at Posted at 2022-12-02

概要

表題どおりですが、↓のようなケースで地味にハマったので忘備録も兼ねて。

  • Intuitive Custom Post Orderを使ってタクソノミーを並び替えている
  • 並び替えた順序に従って、get_terms()でタームを取り出す

本題

端的に言うと、orderby=menu_order は fieldsプロパティと併用できないようです。

動かないコードの例

fieldsにデフォルト値以外が指定されていると動きません。

// ラベルを取り出したい
$terms = get_terms($taxName, [
  'orderby' => 'menu_order',
  'fields' => 'name'
]);

動くコードの例

一度オブジェクトで取り出した後にforeachで任意のfieldを取り出しましょう。

// 1. オブジェクトを取り出す
$terms = get_terms($taxName, [
  'orderby' => 'menu_order',
  'fields' => 'all' // fieldsプロパティを指定するときはallを設定する必要があります
]);

// 2. ラベルだけ取り出す ... 'fields'=>'name' と同じ結果を受け取る
foreach ($terms as $i => $termObj) {
  $terms[$i] = $termObj->name;
}

※ $termsの型が Array<stdClass>Array<String> になってるのはご愛嬌ということでご勘弁ください...

余談

↓の2点を考えると、パフォーマンスは下がりそう。

  • fieldsが指定できればクエリの時点でSELECTする列を減らせる 1 2
  • 条件によっては結構大きいオブジェクトをforeachにかけなきゃいけない

プラグイン使う時点である程度は覚悟しなきゃいけないとはいえ、ちょっと悲しいですね。

  1. https://github.com/WordPress/wordpress-develop/blob/6.1/src/wp-includes/taxonomy.php#L1267-L1331

  2. https://github.com/WordPress/wordpress-develop/blob/6.1/src/wp-includes/class-wp-term-query.php#L348-L906

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0