[![Wordpress主题使用jQuery插件Isotope添加作品集筛选功能](https://pic.salongweb.com/2015/12/wordpress-isotope.jpg)](https://pic.salongweb.com/2015/12/wordpress-isotope.jpg "Wordpress主题使用jQuery插件Isotope添加作品集筛选功能")[上一篇文章](https://api.salongweb.com/isotope.html)我们介绍了Isotope，功能强大，效果出众的jQuery插件，但是文章中的代码并不能使用在项目中，所以今天通过Wordpress主题来演示此功能，完全可以使用在你的主题当中。

## 引入Isotope代码

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

1. &lt;script type=“text/javascript” src=“&lt;?php bloginfo(‘template\_directory’); ?&gt;/js/isotope.pkgd.min.js”&gt;&lt;/script&gt;
2. &lt; script &gt;
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. &lt; /script&gt;

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

## 作品集页面模板

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

1. &lt;?php
2. /\*
3. \*Template Name: 作品集
4. \*/
5. get\_header(); ?&gt;

## 添加PHP代码

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

1. &lt;section class=“button-group”&gt;
2. &lt;div id=“filters”&gt;
3. &lt;?php $terms=get\_terms( “portfolio\_field”); $count=count($terms); echo ‘&lt;button class=“button active” data-filter=“\*”&gt;’.\_\_( ‘全部’, ‘salong’ ). ‘&lt;/button&gt;’; if ( $count&gt;0 ){ foreach ( $terms as $term ) { $termname = strtolower($term-&gt;name); $termname = str\_replace(‘ ‘, ‘-‘, $termname); echo ‘
4. &lt;button class=“button” data-filter=“.’.$termname.'”&gt;’.$term-&gt;name.'&lt;/button&gt;’; } } ?&gt;
5. &lt;/div&gt;
6. &lt;/section&gt;
7. &lt;section class=“portfolio portfolio-list”&gt;
8. &lt;ul&gt;
9. &lt;?php $args=array( ‘post\_type’=&gt;’portfolio’, ‘posts\_per\_page’ =&gt; -1 ); $loop = new WP\_Query( $args ); while ( $loop-&gt;have\_posts() ) : $loop-&gt;the\_post(); $terms = get\_the\_terms( $post-&gt;ID, ‘portfolio\_field’ ); if ( $terms &amp;&amp; ! is\_wp\_error( $terms ) ) : $links = array(); foreach ( $terms as $term ) { $links\[\] = $term-&gt;name; } $tax\_links = join( ” “, str\_replace(‘ ‘, ‘-‘, $links)); $tax = strtolower($tax\_links); else : $tax = ”; endif; ?&gt;
10. &lt;li class=“&lt;?php echo $tax; ?&gt;”&gt;
11. &lt;article class=“portfolio-item”&gt;
12. &lt;div class=“portfolio-img”&gt;
13. &lt;?php post\_thumbnail(); ?&gt;
14. &lt;/div&gt;
15. &lt;div class=“portfolio-info”&gt;
16. &lt;h3&gt;&lt;a href=“&lt;?php the\_permalink() ?&gt;” title=“&lt;?php the\_title(); ?&gt;”&gt;&lt;?php the\_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt;
17. &lt;/div&gt;
18. &lt;/article&gt;
19. &lt;/li&gt;
20. &lt;?php endwhile; ?&gt;
21. &lt;/ul&gt;
22. &lt;/section&gt;

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