Lấy giá trị fields:
* Lấy fields cho taxonomy.
$term = $wp_query->queried_object;
//Retrieve a field
$t = get_field('image', $term); #field 'image'
|
acf sử dụng format "{$term->taxonomy}_{$term->term_id}" để lấy các giá trị fields của một taxonomy term. Cách mà trước đây chúng ta hay làm như sau:
$term = get_term_by('id,' 10);
$t = get_option("{$term->taxonomy}_{$term->term_id}");
|
* Lấy field với post hiện tại, chèn trong vòng lặp post.
// vars (Retrieve a field)
$image = get_field('hero_image');
//the_field print instead of return such as get_field (Display a field)
the_field('hero_image');
if( get_field('sub_heading') ):
the_field('sub_heading');
endif;
|
* Field image.
<?php
$image = get_field('image');
?>
<div class="hero">
<img src="<?php echo $image['url']; ?>" />
</div>
|
* Lấy giá trị trường từ post.
//This example will retrieve a field value from the post with an ID of 123.
$variable = get_field('field_name', 123);
$variable = get_field('field_name', $post->ID);
|
* Lấy giá trị trường từ comment. cú pháp:
the_field('field_name', $comment);
|
Truyền ID của comment vào tham số, chỉ định tiền tố comment_ vào trước ví dụ như thế này:
"comment_{$comment->comment_ID}".
get_field('field_name', 'comment_2');
|
Ví dụ sau tạo danh sách comment với hàm callback và hiển thị một vài trường tùy biến.
Single.php
<?php comments_template(); ?>
|
COMMENTS.PHP
<?php
wp_list_comments(array(
'callback' => 'my_comment_template'
));
?>
|
FUNCTIONS.PHP
<?php
function my_comment_template( $comment, $args, $depth ) {
?>
<div class="comment">
<?php if( get_field('upload_image', $comment) ): ?>
<img src="<?php the_field('image', $comment); ?>" />
<?php endif; ?>
</div>
<?php
}
?>
|
* Lấy giá trị trường từ user.
Tham số $post_id là chuỗi cần chứa từ 'user_' và user id do vậy chuỗi sẽ có định dạng như sau: "user_{$user_id}"
Ví dụ hiển thị giá trị trường từ user có ID=1
the_field('field_name', 'user_1');
//Retrieving a field $variable = get_field('field_name', 'user_1');
|
Bạn có thể tìm author với post hiện tại, và hiển thị dữ liệu custom field từ user đó.
<?php
$author_id = get_the_author_meta('ID');
$author_badge = get_field('author_badge', 'user_'. $author_id );
?>
<img src="<?php echo $author_badge['url']; ?>" alt="<?php echo $author_badge['alt']; ?>" />
|
* Lấy giá trị trường từ media attachment.
Vì wp lưu kiểu media attachment như một post type trong bảng wp_posts, do vậy cũng làm tương tự như cách lấy fields của post.
$variable = get_field('field_name', 13);
|
Ví dụ khác lấy ảnh từ một custom field của attachment.
<?php
// get an image field
$image = get_field('image');
// each image contains a custom field called 'link'
$link = get_field('link', $image['ID']);
// render
?>
<a href="<?php echo $link; ?>">
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
</a>
|
Unregistered version