在Wordpress侧边栏中显示更多帖子(如YouTube)

时间:2017-05-06 19:23:23

标签: javascript jquery html css wordpress

我正在尝试创建一个YouTube Esque侧边栏“显示更多”按钮。

使用以下代码在我的模板侧栏中显示相同类别的帖子:

<div class="sidebar-left">
    <div class="grid-container">
        <?php
                global $post;
                $category = get_the_category($post->ID);
                $current_cat = $category[0]->cat_name;

                $my_query = new WP_Query('category_name='.$current_cat.'&showposts=10');
                while ($my_query->have_posts()) : $my_query->the_post(); ?>
                <a href="<?php the_permalink(); ?>">
                        <div class="grid-item-meta">
                                <span><?php echo $entry_cats; ?></span>
                                <h3><?php the_title(); ?></h3>
                                <h5>Written by <?php echo get_the_author(); ?></h5>
                        </div>
                </a>
                <?php endwhile;
                    wp_reset_postdata();
                ?>
    </div>
</div>

是否可以限制此查询/偏移它并在单击“显示更多”按钮时获取更多信息。一旦显示更多已被切换,我需要将其更改为“显示更少”。我很高兴在一个查询中拉出所有帖子并将它们隐藏在前端(我不太关心进入复杂的AJAX)。

限制div的高度可以切断中间的帖子。似乎有很多关于通过AJAX加载更多信息或在特定div中加载帖子的信息/答案,但不是像我之后的简单显示和隐藏场景。提前谢谢了。

1 个答案:

答案 0 :(得分:1)

如果您不介意加载所有帖子,可以使用一些jQuery来实现这一效果。查看CodePen链接。

https://codepen.io/pen/QvOpGK

声明你将隐藏帖子,4将是我们隐藏的第一个帖子

#posts div:nth-child(n + 4) {
  display: none;
}

然后使用jQuery在点击时显示帖子,我添加了一个show

的课程display: block;
//We need to tell jQuery which posts to show in hiddenPosts

var hiddenPosts = $('#posts div:nth-child(n + 4)');

var button = $('#showMore');

$(button).click(function() {

  hiddenPosts.toggleClass( 'show' );

  //change button's text

  if (button.text() == "Show More") {
    button.text("Show Less");
  } else {
    button.text("Show More");
  }

});