使用ACF 提供的Function
ACF官方建議使用ACF提供的function取得欄位值,能達到最好的相容性
| get_field() | 取得當前 post 的欄位值 |
| the_field() | 顯示當前 post 的欄位值 |
使用WordPress 原生 function
雖然ACF有提供了很好用的方法獲取欄位值,但我實在不太喜歡被綁在某個插件下,倘若我卸載ACF,呼叫ACF的方法就必然失敗,此時我再去一個個更改我的主題,就會曠日廢時,ACF其實只是一個工具,幫助我們很快速地使用而已,而它欄位的資料結構其實就是WordPress Post的標準資結構,使用Post Meta data,所以提供了一個其他的選項,用WordPress原生的方取取值,哪天他忽然漲價,就不怕被插件綁架了。
| get_post_meta() | 取得指定 post 的欄位值 |
ACF 取得欄位值範例:
其中<h1>跟<h2>結果相同,差異在於一個使用WP原生Function,一個使用ACF的Function
<?php
/**
* Template Name: Home Page
*/
get_header();
?>
<div id="primary">
<div id="content" role="main">
<?php while ( have_posts() ) : the_post(); ?>
// ACF 建議
<h1><?php the_field('custom_title'); ?></h1>
// WordPress 原生
<h2><?php echo get_post_meta( get_the_ID(), 'custom_title', true ); ?></h2>
<img src="<?php the_field('hero_image'); ?>" />
<p><?php the_content(); ?></p>
<?php endwhile; // end of the loop. ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_footer(); ?>ACF 簡碼用法:
與 the_field() 用法相同
[acf field="{$field_name}"]取得某一post種的欄位
[acf field="{$field_name}" post_id="{$post_id}"]