【问题标题】:WP display ACF value from all posts on a pageWP 显示页面上所有帖子的 ACF 值
【发布时间】:2018-10-09 22:49:00
【问题描述】:

我想创建一个按字母顺序显示 3 个 ACF 值的页面。我有一个自定义帖子类型 =“product”,并希望显示以下两个字段(都是 ACF 文本字段)1. vendor_or_brand_name 和 2. product_url

我可以像这样从产品帖子类型中输出所有帖子标题:

function output_product_list() {
    global $wpdb;
    $custom_post_type = 'product'; 
    $results = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = %s and post_status = 'publish'", $custom_post_type ), ARRAY_A );
    if ( ! $results )
            return;
            $output = '<ul id="products">';
            foreach( $results as $index => $post ) {
                    $output .= '<li id="' . $post['ID'] . '">' . $post['post_title'] . '</li>';
                }
            $output .= '</ul>'; // end of select element
            return $output;
}

但是当我尝试将“post_title”修改为任一 ACF 字段值时,我没有得到任何输出。请指教。

【问题讨论】:

  • 那是因为您正在查询数据库中的细节......这些字段在那里不存在。 ACF 具有获取字段值的现有功能,例如get_field()
  • 是否可以列出所有字段值而不仅仅是特定帖子?大多数示例将 post_id 作为参数传递。
  • 嗯.. 您设置的任何 ACF 值都将在 inside 帖子中,不是吗?

标签: php mysql wordpress


【解决方案1】:

那是因为您正在查询数据库中的详细信息……那里不存在这些字段。 ACF 具有获取字段值的现有功能,例如get_field()

所以在你的情况下:

function output_product_list() {
    global $wpdb;
    $custom_post_type = 'product'; 
    $results = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = %s and post_status = 'publish'", $custom_post_type ), ARRAY_A );
    if ( ! $results )
            return;
            $output = '<ul id="products">';
            foreach( $results as $index => $post ) {
                    $output .= '<li id="' . $post['ID'] . '">' . get_field('ACF_FIELD_NAME',$post['ID']) . '</li>';
                }
            $output .= '</ul>'; // end of select element
            return $output;
}

请务必将 ACF_FIELD_NAME 更改为您在 WP Admin 中命名的 ACF 字段

【讨论】:

  • the_field()会直接输出,这里要get_field()。
  • 已记录,已更改。
【解决方案2】:
function output_product_list() {
    global $wpdb;
    $custom_post_type = 'product'; 
    $results = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = %s and post_status = 'publish'", $custom_post_type ), ARRAY_A );
    $res_count = count($results);
    if($res_count > 0){
        $output = '<ul id="products">';
        foreach( $results as $index => $post ) {
                $output .= '<li id="' . $post['ID'] . '">' . get_field('ACF_FIELD_NAME',$post['ID']) . '</li>';
            }
        $output .= '</ul>'; // end of select element
        echo $output;
     }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多