Wordpress主题使用jQuery插件Isotope添加作品集筛选功能

Wordpress主题使用jQuery插件Isotope添加作品集筛选功能 - 第1张上一篇文章我们介绍了Isotope,功能强大,效果出众的jQuery插件,但是文章中的代码并不能使用在项目中,所以今天通过Wordpress主题来演示此功能,完全可以使用在你的主题当中。

引入Isotope代码

首先得确保你的主题加载了jQuery插件,然后在Isotope官网下载isotope.pkgd.min.js文件,放在主题的js文件夹下,添加以下代码在footer.php文件夹中:

  1. <script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/isotope.pkgd.min.js"></script>
  2. < script >
  3. var $container = $(".portfolio ul").isotope({});
  4. $("#filters").on("click""button",
  5. function() {
  6.     var filterValue = $(this).attr("data-filter");
  7.     $container.isotope({
  8.         filter: filterValue
  9.     })
  10. });
  11. $("#filters button").click(function() {
  12.     $("#filters button").removeClass("active");
  13.     $(this).addClass("active")
  14. });
  15. < /script>

.portfolio ul为包裹作品列表的元素,#filters为包裹按钮的元素,button为按钮。

作品集页面模板

新建一个名称为template-portfolio.php作品集页面模板,顶部代码为:

  1. <?php
  2. /*
  3. *Template Name: 作品集
  4. */
  5. get_header(); ?>

添加PHP代码

将以下代码添加到template-portfolio.php文件中,具体位置根据主题代码而定。

  1. <section class="button-group">
  2.     <div id="filters">
  3.         <?php $terms=get_terms( "portfolio_field"); $count=count($terms); echo '<button class="button active" data-filter="*">'.__( '全部', 'salong' ). '</button>'; if ( $count>0 ){ foreach ( $terms as $term ) { $termname = strtolower($term->name); $termname = str_replace(' ', '-', $termname); echo '
  4.         <button class="button" data-filter=".'.$termname.'">'.$term->name.'</button>'; } } ?>
  5.     </div>
  6. </section>
  7. <section class="portfolio portfolio-list">
  8.     <ul>
  9.         <?php $args=array( 'post_type'=>'portfolio', 'posts_per_page' => -1 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); $terms = get_the_terms( $post->ID, 'portfolio_field' ); if ( $terms && ! is_wp_error( $terms ) ) : $links = array(); foreach ( $terms as $term ) { $links[] = $term->name; } $tax_links = join( " "str_replace(' ', '-', $links)); $tax = strtolower($tax_links); else : $tax = ''endif; ?>
  10.         <li class="<?php echo $tax; ?>">
  11.             <article class="portfolio-item">
  12.                 <div class="portfolio-img">
  13.                     <?php post_thumbnail(); ?>
  14.                 </div>
  15.                 <div class="portfolio-info">
  16.                     <h3><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
  17.                 </div>
  18.             </article>
  19.         </li>
  20.         <?php endwhile; ?>
  21.     </ul>
  22. </section>

这里获取的文章类型为“portfolio”,获取的是全部作品。
[musicbox]在后台新建一个作品集页面,模板选择作品集,就可以实现与萨龙网络作品集一样的筛选效果。[/musicbox]

本文原创,作者:萨龙龙,其版权均为萨龙网络所有。
如需转载,请注明出处:https://salongweb.com/wordpress-theme-isotope.html