【WordPress Popular posts】人気記事スライダーを作る

やりたいこと

某ブログサービスでよく見る人気記事スライダーと似たようなものを作る。

記事を人気順に並べるために「WordPress Popular Posts」を使う。

検証済みテーマ

CocoonLuxeritasその他テーマ
OKOK未検証

「Luxeritas」のコードを改変して作成しています。「Cocoon」でも利用可能なよう調整済みです。
その他テーマで使用する場合はCSSの調整が必要だと思います。

やりかた

プラグイン「WordPress Popular Posts」を事前にインストールしておく必要があります。

事前にPHPファイルをショートコードとして呼び出せるようにしておきましょう。
手順は以下の記事を参照してください。

ファイルの配置

以下のファイルをダウンロードし、解凍後にPHPのインクルード用フォルダー(以前の記事通り作成していれば「myphpfiles」)に配置してください。

ショートコードの配置

以下のショートコードを「カスタムHTML」ウィジェットに記載します。

[myphp file="mobile_swiper"]

以下のように人気記事スライダーが表示されていれば成功です。
※表示されているスライド数は環境によって異なります。

デスクトップの場合

モバイルの場合

追加可能なパラメータと初期値

以下のパラメータを追加で渡すことができます。

ショートコードを以下のように記載してください。

例)集計期間を1週間にする場合

[myphp file="mobile_swiper" range="weekly"]
パラメータ説明初期値
rangePVやコメントの集計期間
daily / weekly / monthly / all
all
order_by表示順の基準
views / comments / avg
views
post_type表示したいリストのpost typepost
limit表示する総記事数15
pppスライド当たりの表示記事数3
autoplayオートプレイ有無、有効な場合ミリ秒数
false / 半角ミリ秒数
3800

改変した各ファイルのソースコード

mobile_swiper.php

<?php
/**
 * === WordPress Popular Posts ===
 * @package   WordPressPopularPosts
 * @author    Hector Cabrera <me@cabrerahector.com>
 * @license   GPL-2.0+
 * @link      https://cabrerahector.com
 * @copyright 2008-2022 Hector Cabrera
 */

/**
 * Luxeritas WordPress Theme - free/libre wordpress platform
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * @copyright Copyright (C) 2015 Thought is free.
 * @license http://www.gnu.org/licenses/gpl-2.0.html GPL v2 or later
 * @author LunaNuko
 * @link https://thk.kanzae.net/
 * @translators rakeem( http://rakeem.jp/ )
 */

/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * @copyright Copyright (C) 2024 KentaroShiomi
 * @license http://www.gnu.org/licenses/gpl-2.0.html GPL v2 or later
 * @author KentaroShiomi
 * @link https://techhowto.blog/
 */

$atts = array(//引数なしの場合のデフォルト値
		'range' => 'all',//集計する期間 {daily(1日), weekly(1週間), monthly(1ヶ月), all(全期間)}
		'order_by' => 'views',//表示順{views(閲覧数),comments(コメント数),avg(1日の平均)}
		'post_type' => 'post',//複数の場合は'post, name1, nem2'
		'limit' => 15,//表示する総記事数
		'ppp' => 3,//表示するページ当たりの記事数
		'autoplay' => 3800,
	);
if ( !empty( $range )){
	$atts['range'] = $range;
}
if ( !empty( $order_by )){
	$atts['order_by'] = $order_by;
}
if ( !empty( $post_type )){
	$atts['post_type'] = $post_type;
}
if ( !empty( $limit )){
	$atts['limit'] = $limit;
}
if ( !empty( $ppp )){
	$atts['ppp'] = $ppp;
}
if ( empty( $autoplay )){
	$autoplay = $atts['autoplay'];
}

if (class_exists('\WordPressPopularPosts\Query')) {
	global $post;
	$args = array(
		'range' => $atts['range'],
		'order_by' => $atts['order_by'],
		'post_type' => $atts['post_type'],
		'limit' => $atts['limit'],
	);
	$wpp_query = new \WordPressPopularPosts\Query($args);
	$wpp_posts = $wpp_query->get_posts();
	$pps_num = '0';
	if ($wpp_posts) { ?>
		<div id="pps-ranking-list" class="thk_swiper_widget">
		<div class="swiper-container swiper-container-initialized swiper-container-horizontal swiper-container-free-mode swiper-container-android" style="display: block; max-height: none; visibility: visible; padding-bottom: 0px;">
		<ol class="swiper-wrapper">
			<?php
			foreach ($wpp_posts as $wpp_post) {
				$pps_num++;
				$post = get_post($wpp_post->id);
				setup_postdata($post);
				if ($pps_num % $atts['ppp'] === 1){
					echo '<ol class="swiper-slide">';
				};
			?>
			<li>
				<a href="<?php the_permalink();?>">
				<div class="pps-num"><?php echo $pps_num ?></div>
				<figure>
				<?php 
				if(has_post_thumbnail()){ //アイキャッチ
					the_post_thumbnail('thumb75', array('alt' => get_the_title()));
				}else{ //アイキャッチのない場合に表示する画像?>
					<img src="<?php echo get_theme_file_uri('/myphpfiles/mobile_swiper_src/no-image.png');?>" alt="no image">
					<?php };?>
				</figure>
				<div class="post-ttl"><?php the_title();?></div>
				</a>
			</li>
			<?php
				if ($pps_num % $atts['ppp'] === 0){
					echo '</ol>';
				};
			}
			if ($pps_num % $atts['ppp'] !== 0){
				echo '</ol>';
			}
			?>
		</ol>
		</div>
		</div>
		<?php 
		wp_reset_postdata();
	}
}
?>
<?php

	$min_css = array( get_theme_file_uri('/myphpfiles/mobile_swiper_src/pps-thk-swiper.min.css'), get_theme_file_uri('/myphpfiles/mobile_swiper_src/pps-thk-swiper.min.css') );
	$min_css[1] .= file_exists( $min_css[0] ) === true ? '?v=' . filemtime( $min_css[0] ) : '?v=' . $_SERVER['REQUEST_TIME'];

	$min_js = array( get_theme_file_uri('/myphpfiles/mobile_swiper_src/pps-thk-swiper.min.js'), get_theme_file_uri('/myphpfiles/mobile_swiper_src/pps-thk-swiper.min.js') );
	$min_js[1] .= file_exists( $min_js[0] ) === true ? '?v=' . filemtime( $min_js[0] ) : '?v=' . $_SERVER['REQUEST_TIME'];

	$swiper_js = array( get_theme_file_uri('/myphpfiles/mobile_swiper_src/swiper.min.js'), get_theme_file_uri('/myphpfiles/mobile_swiper_src/swiper.min.js') );
	$swiper_js[1] .= file_exists( $swiper_js[0] ) === true ? '?v=' . filemtime( $swiper_js[0] ) : '?v=' . $_SERVER['REQUEST_TIME'];

	if ($pps_num % $atts['ppp'] === 0){
		$pps_num = intdiv($pps_num, $atts['ppp']);
	}else{
		$pps_num = intdiv($pps_num, $atts['ppp']) + 1;
	}
	$pps_show_num = '4';
	if ($pps_show_num > $pps_num){
		$pps_show_num = $pps_num;
	}
?>
<script>(function() {
var elm = document.querySelector('#pps-ranking-list .swiper-container'),
c = elm.style;
c.maxHeight='160';
c.display='block';
c.visibility='hidden';
})();</script>
<script src="<?php echo $min_js[1] ?>"></script>
<script>pps_thk_swiper( '<?php echo $swiper_js[1] ?>', '<?php echo $min_css[1] ?>',<?php
echo
	"'", "pps-ranking-list", "'", ',',
	"0", ',',//初期スライド番号
	"$pps_num", ',',//全スライド数
	"$pps_show_num", ',',//見えるスライド数
	"'", "160", "'", ',',//高さ
	"160", ',',//高さpx
	"'", "auto", "'", ',',//横幅
	"'", "#FFFFFF", "'", ',',//スライドBGcolor
	"'", "none", "'", ',',//navigation有無
	"'", "none", "'", ',',//next-prev有無
	"'", "#FFFFFF", "'", ',',//
	"'", "", "'", ',',//effect
	"'", "post", "'", ',',//
	"'", "", "'", ',',//darkness
	"$autoplay"//autoplay
; ?> );</script>

pps-thk-swiper.min.css

/*! Luxeritas WordPress Theme - free/libre wordpress platform
 *
 * @copyright Copyright (C) 2015 Thought is free.
 * @license http://www.gnu.org/licenses/gpl-2.0.html GPL v2 or later
 * @author LunaNuko
 * @link https://thk.kanzae.net/
 * @translators rakeem( http://rakeem.jp/ )
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 *//*!
 * Swiper 3.4.2
 * Most modern mobile touch slider and framework with hardware accelerated transitions
 * 
 * http://www.idangero.us/swiper/
 * 
 * Copyright 2017, Vladimir Kharlampidi
 * The iDangero.us
 * http://www.idangero.us/
 * 
 * Licensed under MIT
 * 
 * Released on: March 10, 2017
 */
/*
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * @copyright Copyright (C) 2024 KentaroShiomi
 * @license http://www.gnu.org/licenses/gpl-2.0.html GPL v2 or later
 * @author KentaroShiomi
 * @link https://techhowto.blog/
 */[id^="pps_thk_swiper"] img{max-width:none;}.swiper-container{padding-bottom:40px;margin-left:auto;margin-right:auto;position:relative;overflow:hidden;z-index:1}.swiper-container-no-flexbox .swiper-slide{float:left}.swiper-wrapper{position:relative;width:100%;height:auto;z-index:1;display:flex;transition-property:transform;box-sizing:border-box;margin:0;padding:0;}.swiper-container-android .swiper-slide,.swiper-wrapper{transform:translate3d(0,0,0);}.swiper-slide{display:initial;flex-shrink:0;align-items:center;justify-content:center;position:relative;border:1px solid #ddd;text-align:center;box-sizing:border-box;overflow:hidden;list-style-type:none;margin:0 5px!important;padding:0;}a.swiper-slide img,a.swiper-slide img:hover{padding:0;border:0;opacity:1;}p.swiper-title{position:absolute;left:0;right:0;bottom:0;margin:0;padding:8px 10px;height:3pc;line-height:1.5;font-size:1.3rem;color:#fff;font-weight:700;text-align:left;background:rgba(0,0,0,.6);overflow:hidden;}.swiper-container-3d{perspective:75pc;}.swiper-container-3d .swiper-cube-shadow,.swiper-container-3d .swiper-slide,.swiper-container-3d .swiper-slide-shadow-bottom,.swiper-container-3d .swiper-slide-shadow-left,.swiper-container-3d .swiper-slide-shadow-right,.swiper-container-3d .swiper-slide-shadow-top,.swiper-container-3d .swiper-wrapper{transform-style:preserve-3d;}.swiper-container-3d .swiper-slide-shadow-bottom,.swiper-container-3d .swiper-slide-shadow-left,.swiper-container-3d .swiper-slide-shadow-right,.swiper-container-3d .swiper-slide-shadow-top{position:absolute;left:0;top:0;width:100%;height:100%;pointer-events:none;z-index:2;}#pps-ranking-list .swiper-wrapper .swiper-slide li{height:50px;margin:2px 0;}#pps-ranking-list .swiper-wrapper .swiper-slide li a{display:flex;align-items:center;font-size:10pt!important;font-weight:700!important;line-height:12pt!important;text-decoration:none;color:#111;}#pps-ranking-list .swiper-wrapper .swiper-slide li a .pps-num{margin:0 2px;white-space:nowrap;display:flex;justify-content:center;align-items:center;background-color:#999;color:#FFF;width:17px;height:50px;flex-shrink:0;}#pps-ranking-list .swiper-wrapper .swiper-slide li a figure{height:50px;width:50px;border:1px solid #eee;flex-shrink:0;box-sizing:border-box;}#pps-ranking-list .swiper-wrapper .swiper-slide li a figure img{height:100%;object-fit:cover;}#pps-ranking-list .swiper-wrapper .swiper-slide li a .post-ttl{margin:0 2px 0 5px;text-align:left;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;}

pps-thk-swiper.min.js

/*! Luxeritas WordPress Theme - free/libre wordpress platform
 *
 * @copyright Copyright (C) 2015 Thought is free.
 * @link https://thk.kanzae.net/
 * @license http://www.gnu.org/licenses/gpl-2.0.html GPL v2 or later
 * @author LunaNuko
 */
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * @copyright Copyright (C) 2024 KentaroShiomi
 * @license http://www.gnu.org/licenses/gpl-2.0.html GPL v2 or later
 * @author KentaroShiomi
 * @link https://techhowto.blog/
 */;function pps_thk_swiper(A,k,q,o,l,d,p,a,w,f,i,r,h,t,z,b,g){if(document.getElementById("thk-swiper-css")===null){var v=document.createElement("link");v.async=true;v.defer=true;v.rel="stylesheet";v.id="thk-swiper-css";v.href=k;if(document.getElementsByTagName("head")[0]!==null){document.getElementsByTagName("head")[0].appendChild(v)}}var e="slide",u="";if(f!==""){u+="#"+q+" .swiper-slide {background: "+f+";}"}if(w!=="auto"){u+="#"+q+" a.swiper-slide img {width: 100%;}"}if(p==="full"){u+="#"+q+" a.swiper-slide img {height: 100%;}"}if(r==="hover"){u+="#"+q+" .swiper-button-prev,#"+q+" .swiper-button-next {	-webkit-transition: opacity ease 0.5s;	-moz-transition: opacity ease 0.5s;	-o-transition: opacity ease 0.5s;	transition: opacity ease 0.5s;	opacity: 0;}#"+q+" .swiper-container:hover > .swiper-button-prev,#"+q+" .swiper-container:hover > .swiper-button-next {	opacity: 1.0;}"}if(b){u+="#"+q+' .swiper-slide::before {content: "";position: absolute;top: 0;bottom: 0;left: 0;right: 0;-webkit-transition: all 0.4s linear;-moz-transition: all 0.4s linear;transition: all 0.4s linear;}#'+q+" .swiper-slide::before {background: rgba( 0, 0, 0, 0.4 );}"}if(t==="highlight"){u+="#"+q+" .swiper-slide {transform: scale3d( 0.95, 0.95, 0.95 );}#"+q+" .swiper-slide::before {-webkit-transition: all 0.5s linear;-moz-transition: all 0.5s linear;transition: all 0.5s linear;}#"+q+" .swiper-slide-active,#"+q+" .swiper-title,#"+q+" .swiper-slide:hover {-webkit-transition: scale3d( 1.00, 1.00, 1.0 );-moz-transition: scale3d( 1.00, 1.00, 1.0 );transform: scale3d( 1.00, 1.00, 1.0 );}"}else{if(t==="flip"){u+="#"+q+" .swiper-slide:hover {-webkit-transition: transform 1s cubic-bezier(0.500, 0, 0.250, 1);-webkit-transition: transform 1s cubic-bezier(0.500, -0.500, 0.250, 1.500);-moz-transition: transform 1s cubic-bezier(0.500, -0.500, 0.250, 1.500);transition: transform 1s cubic-bezier(0.500, -0.500, 0.250, 1.500);-webkit-transform: rotateY(361deg);-moz-transform: rotateY(361deg);transform: rotateY(361deg);}"}else{if(t==="coverflow"){e="coverflow"}}}u+="#"+q+" .swiper-pagination-fraction,#"+q+" .swiper-button-prev::before,#"+q+" .swiper-button-next::before {	color: "+h+";}#"+q+" .swiper-pagination-bullet-active,#"+q+" .swiper-pagination-progress .swiper-pagination-progressbar {	background: "+h+";}#"+q+" .swiper-slide:hover::before{background: rgba( 0, 0, 0, 0.2 );}#"+q+" .swiper-slide-active:hover::before,#"+q+" .swiper-slide-active::before {background:none;}";if(u!==""){var m=document.createElement("style");m.appendChild(document.createTextNode(u.replace(/\t/g,"")));document.getElementsByTagName("head")[0].appendChild(m)}if(g!=0){g={delay:g}}else{g=false}function x(n,C){var c=document.createElement("script");var B=document.getElementsByTagName("script")[0];c.async=1;c.onload=c.onreadystatechange=function(D,s){if(s||!c.readyState||/loaded|complete/.test(c.readyState)){c.onload=c.onreadystatechange=null;c=undefined;if(!s){if(C){C()}}}};c.src=n;B.parentNode.insertBefore(c,B)}x(A,function(){var F=2,C=3,G=4,s=5,B=7,n=z!=="order"?true:false;if(F>d){F=d}if(C>d){C=d}if(G>d){G=d}if(s>d){s=d}if(B>d){B=d}var D=document.querySelector("#"+q+" .swiper-container"),E=D.style;if(i==="none"){E.paddingBottom="0";i="bullets"}E.maxHeight="none";E.visibility="visible";var H=new Swiper("#"+q+" .swiper-container",{loop:true,speed:150,parallax:true,freeMode:true,freeModeMomentum:false,freeModeSticky:true,preloadImages:false,updateOnImagesReady:false,lazyLoading:true,autoplay:g,initialSlide:o,centeredSlides:n,slidesPerView:d,loopedSlides:l,effect:e,paginationClickable:true,spaceBetween:11.2,pagination:{el:"#"+q+" .swiper-pagination",type:i},navigation:{nextEl:"#"+q+" .swiper-button-next",prevEl:"#"+q+" .swiper-button-prev"},breakpoints:{480:{slidesPerView:1.25},640:{slidesPerView:2},768:{slidesPerView:2.5},992:{slidesPerView:3.5},1199:{slidesPerView:4}}})});if(p==="manual"){var j,y;j=document.querySelectorAll("#"+q+" .swiper-slide");Object.keys(j).forEach(function(c){y=this[c].style;y.height=a+"px"},j);j=document.querySelectorAll("#"+q+" .swiper-title");Object.keys(j).forEach(function(c){y=this[c].style;y.bottom="0"},j)}};

参考

コメント

タイトルとURLをコピーしました