按页面名称访问高级自定义字段
Accessing Advanced Custom Fields by Page Name
我正在尝试检索与特定页面关联的所有高级自定义字段。这与遍历帖子不同,我熟悉以下内容:
$posts = get_posts(array(
'post_type' => 'post_name',
'meta_key' => 'color',
'meta_value' => 'red'
));
但是,此方法特定于帖子,不允许我通过页面名称检索所有 ACF。
对于如何完成此任务的任何建议,我都很感激。
您可以使用 ACF 的 get_fields()
功能 -
<?php $fields = get_fields( $post->ID ); ?>
然后您可以遍历它们或简单地打印数组进行测试。
想到的方法太多了...
1。使用循环
使用 WP_Query 你可以做这样的事情...
<?php
// WP_Query arguments
$args = array (
'pagename' => 'homepage',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
the_field( "field_name" );
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
?>
代替 'pagename' => 'homepage'
中的 'homepage',您想放置页面的页面 slug。当然,您要添加 fields/content.
来代替 the_field( "text_field" );
您还可以通过页面ID和其他一些参数进行查询。您可以在此处找到可以使用的所有其他参数:
https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters
2。将第二个参数添加到 the_field() 函数
更简单的方法,无需自定义循环,只需使用 ACF 的内置 the_field()
函数,并添加 $post->ID
参数作为第二个参数。
<?php the_field('field_name', 123);
这可能是要走的路,因为您只想显示一页的内容,因此实际上不需要循环。
参考:http://www.advancedcustomfields.com/resources/how-to-get-values-from-another-post/
我正在尝试检索与特定页面关联的所有高级自定义字段。这与遍历帖子不同,我熟悉以下内容:
$posts = get_posts(array(
'post_type' => 'post_name',
'meta_key' => 'color',
'meta_value' => 'red'
));
但是,此方法特定于帖子,不允许我通过页面名称检索所有 ACF。
对于如何完成此任务的任何建议,我都很感激。
您可以使用 ACF 的 get_fields()
功能 -
<?php $fields = get_fields( $post->ID ); ?>
然后您可以遍历它们或简单地打印数组进行测试。
想到的方法太多了...
1。使用循环
使用 WP_Query 你可以做这样的事情...
<?php
// WP_Query arguments
$args = array (
'pagename' => 'homepage',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
the_field( "field_name" );
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
?>
代替 'pagename' => 'homepage'
中的 'homepage',您想放置页面的页面 slug。当然,您要添加 fields/content.
the_field( "text_field" );
您还可以通过页面ID和其他一些参数进行查询。您可以在此处找到可以使用的所有其他参数: https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters
2。将第二个参数添加到 the_field() 函数
更简单的方法,无需自定义循环,只需使用 ACF 的内置 the_field()
函数,并添加 $post->ID
参数作为第二个参数。
<?php the_field('field_name', 123);
这可能是要走的路,因为您只想显示一页的内容,因此实际上不需要循环。
参考:http://www.advancedcustomfields.com/resources/how-to-get-values-from-another-post/