查询高级自定义字段不显示

时间:2016-07-29 10:53:13

标签: php wordpress

我们有WP的ACF Pro,我们创建了一个ACF,显示了一个选择的位置。

尝试输出时,我们得到了这个:

  

注意:尝试获取非对象的属性   /home/cwplantactiveint/public_html/wp-content/themes/cwplant/loop-jobs.php   在第66行

这是什么

<?php $location = get_field('job_location'); echo $location->post_title; ?>

奇怪的是,它输出了另一个自定义字段,该字段已创建输出日期:

<?php if(get_field('closing_date')) { ?>
<?php the_field('closing_date'); ?>
<?php } else { ?>
Ongoing
<?php } ?>

整个代码块如下所示:

<?php while ( have_posts() ) : the_post(); ?>

<?php /* Check closing date is not past. */ 


$today = strtotime("now");
$closedate = strtotime(get_field('closing_date'));


if ($today < $closedate || !get_field('closing_date')) {

?>

<div class="singlepost infobox info-job content cfix">
        <h2><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>"><?php the_title(); ?></a></h2>
        <p><span class="red first">Location:</span> <?php $location = get_field('job_location'); echo $location->post_title; ?> 


         <span class="red">Closing Date:</span> 

      <?php if(get_field('closing_date')) { ?>
  <?php the_field('closing_date'); ?>
  <?php } else { ?>
  Ongoing
  <?php } ?>

             </p>

    <?php if ( is_archive() || is_search()  || is_home()) : // Only display excerpts for archives and search. ?>
            <?php the_excerpt(); ?>
            <a class="button" href="<?php the_permalink(); ?>">View Details</a>
    <?php else : ?> 
            <?php the_content( __( 'Continue reading &rarr;', 'twentyten' ) ); ?>
    <?php endif; ?>



</div>

<?php $jobstrue = 'true'; ?>

    <?php } else { ?>
    <?php $jobsfalse = 'true'; ?>
    <?php } ?>

<?php endwhile; // End the loop. Whew. ?>

1 个答案:

答案 0 :(得分:1)

我认为您的问题是您没有使用wp_reset_postdata()重置$post对象,因此您的查询将返回$post中的最后一个内容(可能createdto案件)。

每当我处理WP中的任何对象时,我总是将其设置然后重置为:

<?php
// YOUR CUSTOM FIELD
// 0- Reset post object from last query (this should really be part of your last query)
wp_reset_postdata();

// 1- Put custom field into post object and check for content
$post_object = get_field('location');

// 2- Check to make sure object exists and setup $post (must use $post variable name)
if ($post_object) {
  $post = $post_object;
  setup_postdata($post);

  // 3- Do some magic
  echo get_field('closing_date');

  // 4- reset postdata so other parts of the page can use it
  wp_reset_postdata();
}
?>