【问题标题】:Wordpress Advanced Custom Fields display two fields from two different post types in one templateWordpress 高级自定义字段在一个模板中显示来自两种不同帖子类型的两个字段
【发布时间】:2016-07-19 09:03:11
【问题描述】:

我有两种帖子类型。我需要在同一个循环中显示每个内容。目前,我可以调用 'releases' 帖子类型来显示内容,但我还需要调用 'artists' 帖子类型来在同一个 DIV 中显示一些内容。

下面的行以“可捕获的致命错误:WP_Post 类的对象无法转换为字符串错误”中断页面。

<?php the_field('release_artist_name'); ?>

如何让 release_artist_name 字段停止破坏网站?它是一个通过帖子对象的字段(帖子类型名为“艺术家”)。任何帮助表示赞赏。

    <?php 
       $posts = get_posts(array(
        'post_type'     => 'releases'
    )
       ));

       if( $posts ): ?>
    <?php foreach( $posts as $post ): 
       setup_postdata( $post )       
       ?>
<div>
    <?php the_title(); ?> // THIS COMES FROM RELEASES POST TYPE
    <?php the_field('release_artist_name'); ?> // THIS SHOULD COME FROM ARTISTS POST TYPE BUT BREAKS THE PAGE
</div>

    <?php endif; ?>
    <?php endforeach; ?>
    <?php wp_reset_postdata(); ?>
    <?php endif; ?>

如下所示,print_r($posts) 的结果...

Array ( [0] => WP_Post Object ( [ID] => 10661 [post_author] => 1 [post_date] => 2016-03-31 02:37:57 [post_date_gmt] => 2016-03-31 02:37:57 [post_content] => [post_title] => New Gold Mountain [post_excerpt] => [post_status] => publish [comment_status] => closed [ping_status] => closed [post_password] => [post_name] => new-gold-mountain [to_ping] => [pinged] => [post_modified] => 2016-03-31 04:41:04 [post_modified_gmt] => 2016-03-31 04:41:04 [post_content_filtered] => [post_parent] => 0 [guid] => http://127.0.0.1:4001/wordpress/?post_type=releases&p=10661 [menu_order] => 0 [post_type] => releases [post_mime_type] => [comment_count] => 0 [filter] => raw )

【问题讨论】:

  • 请问print_r($posts) 好吗?并将其添加到您的问题中?
  • 我这样做了,根本没有提到帖子类型“艺术家”。问题出在哪里?
  • $posts = get_posts(array( 'post_type' =&gt; 'releases' ))); 在这段代码下面,添加print_r($posts); 并刷新页面,看看有什么输出?
  • 基本上,我上面的代码设置为从 RELEASES 帖子类型中提取数据。我还需要从同一 DIV 中的 ARTISTS 帖子类型中提取数据。
  • 正如我上面所说,我无法在没有看到输出的情况下弄清楚。为什么你不能按照我上面写的步骤?

标签: php wordpress custom-post-type advanced-custom-fields


【解决方案1】:

如果您有 artists 的帖子类型并且您正在使用 ACF,那么在您的 releases 帖子类型中,您应该添加一个名为 release_artist(例如)类型为 Post Object 的自定义字段,您将为发布关联艺术家(或艺术家)。我建议您将此字段设置为返回 Post ID 而不是 Post Object

然后在您的循环中,您将获得艺术家 ID:

$artist_id = get_field('release_artist');

因此您可以使用此 ID 查询艺术家的任何自定义字段:

$artist_name = get_field('artist_name', $artist_id);

请注意,所有 ACF 函数都接受带有帖子 ID 的第二个参数来查询其他帖子,例如,当您在循环中时。

请参阅get_field 文档。希望这会有所帮助。

【讨论】:

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