循环内的Wordpress循环

时间:2017-01-04 12:46:50

标签: php wordpress

我有以下代码,它是循环中的循环,第二个循环是动态的,并使用当前页面标题`get_the_title();

我遇到的问题是它不起作用,我认为是因为原始循环中的get_the_title();在第二个循环中被覆盖。

<?php if ( have_posts() ) : ?>

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

<?php if(get_field( 'artist_photo')) { $image=g et_field( 'artist_photo'); } ?>

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

  <header>
    <h1><?php the_title(); ?></h1>
    <hr />
  </header>

  <div class="content">

    <?php if(!empty($image)) { echo "<img src='" . $image[ 'url'] . "' alt='" . $image[ 'alt'] . "' class='featured' />"; } ?>

    <?php the_content(); ?>

    <hr />
    <h2>Artwork for Sale</h2>
    <?php $args=a rray( 'post_type'=>'artwork', 'meta_key' => 'artist', 'meta_value' => the_title() ); $query = new WP_Query( $args ); ?>
    <?php if ( $query->have_posts() ) : ?>

    <ul id="related-artwork" class="row">

      <?php while ( $query->have_posts() ) : $query->the_post(); ?>

      <li class="col-sm-3">

        <?php if(get_field( 'image')) { $image=g et_field( 'image'); } ?>
        <?php if(!empty($image)) { echo "<img src='" . $image[ 'url'] . "' alt='" . $image[ 'alt'] . "' />"; } ?>

        <div class="info">
          <h3><?php the_title(); ?></h3>
        </div>

      </li>


      <?php endwhile; ?>

      <?php wp_reset_query(); ?>

    </ul>
    <?php else : ?>

    <?php endif; ?>


  </div>

  <footer>
  </footer>

</article>

<?php endwhile; ?>

<?php wp_reset_query(); ?>

<?php else : ?>

<?php endif; ?>

2 个答案:

答案 0 :(得分:1)

我认为

的主要问题
$args = array(
'post_type'     => 'artwork',
'meta_key'      => 'artist',
'meta_value'    => the_title()
    );

因为the_title()不是返回值,而是回显 get_the_title()

因此,请更换“元数据”&#39; =&GT;带有&#39; meta_value&#39;的the_title()行=&GT; get_the_title()

此外,在第二个循环中,记得在while循环中调用 $ the_query-&gt; the_post(); 来进行切换。

类似的东西:

<ul id="related-artwork" class="row">

<?php while ( $query->have_posts() ) : $query->the_post(); ?>

 $the_query->the_post();

    <li class="col-sm-3">
    .....

两个编辑应该是我认为的伎俩。其他一切似乎都很好。

答案 1 :(得分:0)

使用wp_reset_postdata()代替wp_reset_query()

  

使用WP_Query或后,不需要调用wp_reset_query   get_posts因为这些不会修改主查询对象。而是使用   wp_reset_postdata