How to get real term_meta using ACF with custom fields on taxonomy terms (instead of wp_options)

ぐ巨炮叔叔 提交于 2019-12-06 16:17:48

I could fix this doing the following:

Let's say I have 2 custom fields on my taxonomy terms: color and shape (means I have a color and shape input on my backend terms edit/create page for the given taxonomy).

function acf_update_term_meta( $value, $post_id, $field ) {
    $term_id = (int) filter_var( $post_id, FILTER_SANITIZE_NUMBER_INT );
    if ( $term_id > 0 ) {
        update_term_meta( $term_id, $field['name'], $value );
    }

    return $value;
}
add_filter( 'acf/update_value/name=color', 'acf_update_term_meta', 10, 3 );
add_filter( 'acf/update_value/name=shape', 'acf_update_term_meta', 10, 3 );

function acf_load_term_meta( $value, $post_id, $field ) {
    $term_id = (int) filter_var( $post_id, FILTER_SANITIZE_NUMBER_INT );
    if ( $term_id > 0 ) {
        $value = get_term_meta( $term_id, $field['name'], true );
    }

    return $value;
}
add_filter( 'acf/load_value/name=color', 'acf_load_term_meta', 10, 3 );
add_filter( 'acf/load_value/name=shape', 'acf_load_term_meta', 10, 3 );

So we have:

  • a filter to update the term_meta using update_term_meta() (codex) when updating this ACF fields (hooked 2 times, one for color and one for shape)
  • a filter to return the term_meta value using get_term_meta() (codex) instead of the wp_option (hooked 2 times, one for color and one for shape)

source

Note 1:

this will trigger for ALL terms (no matter the taxonomy) having the color or shape custom field. You may need to filter by taxonomy if you don't want it to always apply in those fields cases.

Note 2:

ACF5 seems to support out-of-the-box real term_meta, but is still in early access only. The upgrade process seems to contain a refactor method for this particular case (duplicate data from wp_options to real term_metas):

After updating to ACF 5, you will be prompted to upgrade the Database.

This is a necessary step to migrate across your field and field group settings from version 4.x. This upgrade will also copy across any taxonomy term values from the 'wp_options' table to the 'wp_termmeta' table.

No data is deleted or modified during this upgrade. (source)

Note 3: I believe it would be possible to loop on all ACF terms custom fields to "generate" this code automatically for all custom fields on terms, and prevent having to add 2 filters for each new ACF term field. But as ACF5 should go out soon, it may not be worth the time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!