【问题标题】:Accessing Advanced Custom Fields by Page Name按页面名称访问高级自定义字段
【发布时间】:2016-03-10 13:54:17
【问题描述】:

我正在尝试检索与特定页面相关的所有高级自定义字段。这与遍历帖子不同,我熟悉以下内容:

$posts = get_posts(array(
    'post_type'     => 'post_name',
    'meta_key'      => 'color',
    'meta_value'    => 'red'
));

但是,此方法特定于帖子,不允许我按页面名称检索所有 ACF。

感谢任何有关如何完成此任务的建议。

【问题讨论】:

    标签: wordpress wordpress-theming advanced-custom-fields


    【解决方案1】:

    想到的方法太多了......

    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' =&gt; 'homepage' 中的“主页”,您想放置页面的页面块。当然,您想添加字段/内容来代替 the_field( "text_field" );

    您还可以通过Page ID和其他一些参数进行查询。您可以在此处找到可以使用的所有其他参数: https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters

    2。向 the_field() 函数添加第二个参数

    更简单的方法,没有自定义循环,只是使用 ACF 的内置 the_field() 函数,并将 $post-&gt;ID 参数添加为第二个参数。

    <?php the_field('field_name', 123);
    

    这可能是要走的路,因为您只想显示一页的内容,因此实际上不需要循环。

    参考:http://www.advancedcustomfields.com/resources/how-to-get-values-from-another-post/

    【讨论】:

      【解决方案2】:

      你可以使用ACF的get_fields()函数——

      <?php $fields = get_fields( $post->ID ); ?>
      

      然后您可以遍历它们或简单地打印数组进行测试。

      http://www.advancedcustomfields.com/resources/get_fields/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-05-27
        • 2016-06-28
        • 2021-02-18
        • 2016-01-20
        • 1970-01-01
        • 2016-01-15
        • 1970-01-01
        相关资源
        最近更新 更多