简体   繁体   English

显示高级自定义字段的内容

[英]Displaying content of Advanced Custom Fields

I'm having a little problem understanding what (my) PHP is doing when I'm trying to display different Custom Posts and Advanced Custom fields on the same page. 当我尝试在同一页面上显示不同的“自定义帖子”和“高级自定义”字段时,我在理解PHP在做什么方面遇到了一些问题。

I have added different Advanced Custom Fields to a page, and I have custom posts that I am trying to display using the template. 我已在页面上添加了不同的“高级自定义字段”,并且我尝试使用模板显示自定义帖子。

I'm calling my custom fields throughout the template using: 我使用以下命令在整个模板中调用自定义字段:

<?php the_field(‘field-name’) ?>

My custom posts are called through loops like this (somewhere around the middle of the template): 我的自定义帖子通过这样的循环(在模板中间的某个地方)被调用:

<?php
  $args = array(
  'post_type' => ‘foo’
);

$foo = new WP_Query( $args );
if( $foo->have_posts() ) {

while( $foo->have_posts() ) {
  $foo->the_post();
?>
  <?php the_content() ?>                    
<?php
  }
}
else {
  // SOME MESSAGE
}
?>

The content of the Advanced Custom Fields is showing fine, above those loops. 在这些循环上方,“高级自定义字段”的内容显示良好。 Below the loops it just doesn't display. 在循环下面,它只是不显示。

I can't figure out why the content is not showing up. 我不知道为什么没有显示内容。

I assume it has to do with the while or if statements of the loops. 我认为这与while或if循环语句有关。 If I remove the loops, the content of any Advanced Custom Field below does display. 如果删除循环,则会显示下面任何“高级自定义字段”的内容。

When you use WP_Query() , you are changing the default $post variable on the page each time you loop through a post. 使用WP_Query() ,每次循环浏览帖子时,都将在页面上更改默认的$post变量。 You need to call wp_reset_postdata() after your loop to reset that $post variable so it corresponds to the current page again. 您需要在循环后调用wp_reset_postdata()来重置$post变量,使其再次与当前页面相对应。 You can call the function after your 'while' loop - 您可以在“ while”循环之后调用该函数-

<?php
$args = array(
    'post_type' => ‘foo’
);
$foo = new WP_Query( $args );

if( $foo->have_posts() ) {

    while( $foo->have_posts() ) { $foo->the_post();

        the_content();                    

    } wp_reset_postdata();
}
else {
  // SOME MESSAGE
}
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM