【问题标题】:Wordpress get_posts returns correct results but won't load subsequent functionsWordpress get_posts 返回正确结果但不会加载后续函数
【发布时间】:2014-01-06 03:06:59
【问题描述】:

我正在使用此代码查询两个分类:

$args = array(
    'posts_per_page'  => 1,
    'offset'          => 0,
    'orderby'         => 'post_date',
    'order'           => 'DESC',
    'include'         => '',
    'exclude'         => '',
    'meta_key'        => '',
    'meta_value'      => '',
    'post_type'       => 'post',
    'post_mime_type'  => '',
    'post_parent'     => '',
    'post_status'     => 'publish',
    'suppress_filters' => true,
    'tax_query' => array(
        array(
            'taxonomy' => 'category',
        'terms' => '16',
        'field' => 'term_id',
        ),
        array(
        'taxonomy' => $this_taxonomy,
        'terms' => $this_page,
        'field' => 'slug',
        )
    )
);
$myposts2 = get_posts( $args );

并且它返回了一个很好的结果(生成的帖子对象具有正确的类别和分类/slug 分配)。

但是当我尝试使用这样的后续功能时:

<?php foreach ( $myposts2 as $post2 ) : ?>
    <li class="product-details">
    <a href="<?php the_permalink($post2->ID); ?>"><?php get_the_post_thumbnail( $post2->ID, 'medium' ); ?><h3><?php $post2->post_title; ?></h3></a>
</li>
<?php 
    endforeach; 
wp_reset_postdata();
?>

我最终得到了错误的永久链接结果,并且没有得到标题或缩略图的结果。

任何想法我做错了什么?

谢谢你,BA_Webimax!代码还有一些其他问题,但是您发送的参考链接帮助我朝着正确的方向前进。我没想到 WP 会要求我调用对象 $post(而不是 $post2)。另外,我使用了错误的函数来检索这些位。 get_permalink() 很好,但我应该使用 the_post_thumbnail() 和 the_title() 而不是我选择的函数。

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    您需要在其中拨打setup_postdata() 电话。详情见这里...https://codex.wordpress.org/Function_Reference/setup_postdata

    <?php foreach ( $myposts2 as $post2 ) :
        setup_postdata($post2); ?>
        <li class="product-details">
        <a href="<?php the_permalink($post2->ID); ?>"><?php get_the_post_thumbnail( $post2->ID, 'medium' ); ?><h3><?php $post2->post_title; ?></h3></a>
    </li>
    <?php 
        endforeach; 
    wp_reset_postdata();
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      • 2016-05-28
      相关资源
      最近更新 更多