仅当存在具有相同自定义字段值的其他帖子时才显示div

时间:2012-06-07 16:19:00

标签: php wordpress custom-fields

我有一个带有一组自定义字段的wordpress主题。 其中一个被命名为“作者”。

在single.php上我有一个div,显示其他帖子具有相同的自定义字段值。

我想仅在存在具有相同自定义字段值的其他帖子时显示此div,否则我想不显示任何内容。

感谢您的帮助!!

这是我的实际代码:

<?php 

                        $myquery = array(
                        'meta_key' => 'autore',
                        'meta_value' => $autore,
                        'showposts' => 2,
                        'post__not_in' => array($post->ID)
                        );

                        if ( $myquery->have_posts() ) : ?>

                        <div class="related">

                        <h3>Altre di <?php the_field('autore'); ?></h3>

                        <ul>

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

                                <?php        
                                echo '<li>'; ?>

                                <?php
                                $fotorel = get_field('foto_homepage');
                                list($width, $height) = getimagesize("$fotorel");
                                $relheight = $height / 2;
                                ?>

                                <div class="related-foto" style="background:url(<?php the_field('foto_homepage'); ?>) no-repeat center center; height:<?php echo $relheight.'px' ?>"></div>
                                <a href="<?php the_permalink() ?>"><?php the_title(); ?></a>


                               <?php echo '</li>';?>

                               <?php endwhile; ?>

                              <?php else : // What to do if there are no posts from that author

                              endif;?>

                                        </ul>

        </div>



                        <?php wp_reset_query(); ?>

2 个答案:

答案 0 :(得分:0)

这是一个例子:

http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query

使用条件<?php if ($pageposts): ?>您可以打印您的div。

答案 1 :(得分:0)

我不确定你是如何查询自定义字段中的帖子的,但$ wp_query已内置条件来处理不返回帖子的查询。

更新了代码示例:

$args = array(
         'meta_key' => 'autore',
         'meta_value' => $autore,
         'showposts' => 2,
         'post__not_in' => array($post->ID)
        );
 $your_query = new WP_Query( $args );


if ( $your_query->have_posts() ) : ?>

  <div id="your-div">

while ( $your_query->have_posts() ) : $your_query->the_post();

// Do stuff 

endwhile;

  else : // What to do if there are no posts from that author

endif;
相关问题