Get Labels for Advanced Custom Fields

新版本的ACF已经具备这个功能,可以参考 get_field_object()

Advanced Custom Fields for wordpress 是一个不错的插件,但是api 里只有 get fields,却没有get labels,对此,作者认为没有必要(作者的论坛上表示的)。一般情况是真的没必要。但是有会更好!

在配合 WPML 做多语言网站的时候就大有用处了,可以设置不同的 Field Label 用相同的 Field Name,这样就可以实现切换语言的时候自动切换 Field Label,而用相同的 get field 获取不同 label 下面的值。

吧下面的代码放进header.php 或这 function.php

function get_acf_labels($name = null, $post_id) {

	global $wpdb;

//SELECT name, label FROM wp_acf_fields as waf left jolin wp_acf_values as wav on wav.field_id = waf.id where wav.post_id=145 and waf.name = 'work_year'

	// Query DB to find either a single row or all acf field names and labels

	$fields_table = $wpdb->prefix . "acf_fields";

	$fields_values = $wpdb->prefix . "acf_values";

	if ($name) $fields_query = "SELECT waf.label FROM $fields_table as waf left join $fields_values as wav on wav.field_id = waf.id WHERE waf.name = '$name' and wav.post_id = '$post_id'";

	else $fields_query = "SELECT name, label FROM $fields_table";

	$records = $wpdb->get_results( $fields_query );

	//print_r($records);

	// Sort results into associative array, using field name as key for label values

	if (sizeof($records) > 0) {

		foreach ($records as $record) {

			//$labels[$record->name] = $record->label;

			$labels = $record->label;

		}

		echo $labels;

	} else return false;

}

获取

<?php if(get_field('work_year')){ ?>
<ul>
	<li><span><?php get_acf_labels('work_year', $post->ID);?&gt;:</span><?php the_field('work_year'); ?></li>
</ul>
<?php } ?> <?php if(get_field('work_name')){ ?>
<ul>
	<li><span><?php get_acf_labels('work_name', $post->ID);?&gt;:</span><?php the_field('work_name'); ?></li>
</ul>
<?php } ?>