WordPress:Advanced Custom Fieldsの「関連」フィールドで、並び順を日付やランダムに設定する方法

WordPress:Advanced Custom Fieldsの「関連」フィールドで、並び順を日付やランダムに設定する方法

WordPressでカスタムフィールドを扱いやすくするプラグイン「Advanced Custom Fields」の「関連」フィールドタイプは、デフォルトでは記事選択部分の並びはタイトル順になっていますが、それを日付やランダムで並ぶように設定する方法です。

※「Advanced Custom Fields」の概要や使用方法については省略します。
また、ここで紹介しているものは Ver 4.4.11 で検証した内容になります。

日付順+昇順

並びを日付順+昇順にしたい場合は、下記をfunctions.phpに記述することで実装できます。
昇順の指定についてはデフォルトの指定が昇順になっているので指定する必要はありません。

functions.php

add_filter( 'acf/fields/relationship/query', 'custom_acf_relationship_query', 10, 3 );
function custom_acf_relationship_query( $args, $field, $post_id ) {
  $args['orderby'] = 'date';
  return $args;
}

日付順+降順

並びを日付順+降順にしたい場合は、下記をfunctions.phpに記述することで実装できます。

functions.php

add_filter( 'acf/fields/relationship/query', 'custom_acf_relationship_query', 10, 3 );
function custom_acf_relationship_query( $args, $field, $post_id ) {
  $args['orderby'] = 'date';
  $args['order'] = 'DESC';
  return $args;
}

ランダム

並びをランダムにしたい場合は、下記をfunctions.phpに記述することで実装できます。
沢山記事があるのにいつも同じものを選択しがちな場合などに設定しておくと良いかもです。

functions.php

add_filter( 'acf/fields/relationship/query', 'custom_acf_relationship_query', 10, 3 );
function custom_acf_relationship_query( $args, $field, $post_id ) {
  $args['orderby'] = 'rand';
  return $args;
}

Close the search window,
please press close button or esc key.