【问题标题】:ACF loop for grid, get/display custom field网格的 ACF 循环,获取/显示自定义字段
【发布时间】:2020-02-06 22:27:27
【问题描述】:

我在我的 Wordpress 模板中使用了这段代码:

<?php
    $args = array( 'numberposts' => '12', 'post_type' => 'training', 'post_status' => 'publish' );
    $recent_posts = wp_get_recent_posts( $args );
    foreach( $recent_posts as $recent ) {
        echo '<div class="col-xs-12 col-md-4"><article><div class="kartel"><a href="' . get_permalink($recent["ID"]) . '">';
        if ( has_post_thumbnail( $recent["ID"]) ) {
              echo  get_the_post_thumbnail($recent["ID"],'medium');
        }
        echo '</a></div><a href="' . get_permalink($recent["ID"]) . '"><h3>' .   $recent["post_title"].'</h3></a> ';

        echo '<em>Doelgroep //</em>
        <p>One-liner/super korte omschrijving</p>';
        echo '<a href="' . get_permalink($recent["ID"]) . '">Tell me more</a> ';
        echo '</article></div>';
    }
    wp_reset_query();
?>

问题是我现在想添加一个自定义字段(比如说“custom_field”),它在网格的缩略图下方显示自定义摘录。我可以获取常用字段(摘录、标题等),但不能获取自定义字段。例如 the_field('custom_field');不工作..

有什么想法/建议吗?

希望收到你们的来信!

过滤

【问题讨论】:

  • 你没有用 wp 查询循环它,所以你必须告诉 get_field() 或 the_field() 函数你想从哪个页面 id 显示。试试the_field( 'custom_field', $recent["ID"] );
  • 太棒了,这很有效,也许不是最好的方法,但至少是最快的!谢谢

标签: wordpress advanced-custom-fields


【解决方案1】:

首先,使用 WP_Query 类更改查询和 Wordpress 循环的方法。

<?php
$args = array( 'numberposts' => '12', 'post_type' => 'training', 'post_status' => 'publish' );
$loop = new WP_Query($args);
if( $loop->have_posts() ) {
    while( $loop->have_posts() ){
        $loop->the_post(); ?>
        <div class="col-xs-12 col-md-4">
            <article>
                <div class="kartel">
                    <a href="<?php the_permalink(); ?>">
                        <?php if( has_post_thumbnail("medium") ) {
                            the_post_thumbnail( "medium" );
                        }
                        ?>
                    </a>
                </div>
                <a href="<?php the_permalink(); ?>">
                    <?php the_title("<h3>","</h3>"); ?>
                </a>
                <em>Doelgroep //</em>
                <a href="<?php the_permalink(); ?>">Tell me more</a>
            </article>
        </div>
    <?php }
}
wp_reset_postdata();
?>

稍后,在您的帖子循环中,您可以使用以下方法调用自定义字段:

the_field ('custom'); //which prints the result on screen

$var = get_field ('custom'); //or echo get_field ('custom') which returns the content in a variable.

如果您想调用插入到帖子或页面或自定义帖子类型中的特定自定义字段,您必须使用以下语法:

the_field ('custom', $ post_id);

get_field ('custom', $ post_id)

就是这样:)

【讨论】:

  • 嘿,非常感谢!看起来很棒,并且是关于使用 WP_Query 的好提示。唯一的问题是缩略图没有加载,整个页面正在折叠。在某处看起来像一个小错误,但我找不到任何东西。有什么想法吗?
  • 对不起伙计,有一个错误。我写道:缩略图的缩略图实例。我更正了我的回复:)
  • 太棒了!看起来更好,只有缩略图“中等”没有加载,但我会自己解决这个问题!再次感谢您的宝贵时间
猜你喜欢
  • 1970-01-01
  • 2022-11-07
  • 2021-10-06
  • 2019-04-17
  • 2018-05-01
  • 2021-07-30
  • 1970-01-01
  • 1970-01-01
  • 2020-05-11
相关资源
最近更新 更多