Isotope,功能强大,效果出众的jQuery插件,但是文章中的代码并不能使用在项目中,所以今天通过WordPress主题来演示此功能,完全可以使用在你的主题当中。
引入Isotope代码
首先得确保你的主题加载了jQuery插件,然后在Isotope官网下载isotope.pkgd.min.js文件,放在主题的js文件夹下,添加以下代码在footer.php文件夹中:
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/isotope.pkgd.min.js"></script>
< script >
var $container = $(".portfolio ul").isotope({});
$("#filters").on("click", "button",
function() {
var filterValue = $(this).attr("data-filter");
$container.isotope({
filter: filterValue
})
});
$("#filters button").click(function() {
$("#filters button").removeClass("active");
$(this).addClass("active")
});
< /script>
.portfolio ul为包裹作品列表的元素,#filters为包裹按钮的元素,button为按钮。
作品集页面模板
新建一个名称为template-portfolio.php作品集页面模板,顶部代码为:
<?php
/*
*Template Name: 作品集
*/
get_header(); ?>
添加PHP代码
将以下代码添加到template-portfolio.php文件中,具体位置根据主题代码而定。
<section class="button-group">
<div id="filters">
<?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 '
<button class="button" data-filter=".'.$termname.'">'.$term->name.'</button>'; } } ?>
</div>
</section>
<section class="portfolio portfolio-list">
<ul>
<?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; ?>
<li class="<?php echo $tax; ?>">
<article class="portfolio-item">
<div class="portfolio-img">
<?php post_thumbnail(); ?>
</div>
<div class="portfolio-info">
<h3><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
</div>
</article>
</li>
<?php endwhile; ?>
</ul>
</section>
这里获取的文章类型为“portfolio”,获取的是全部作品。

