9ml

お気に入り機能

ローカルストレージを使ってWordPressのサイトにお気に入り機能を実装します。

お気に入りボタンがページに複数あると仮定します。

page-favorite.php

	<ul id='fav_list'></ul>
	
<script>
document.addEventListener('DOMContentLoaded', function(){

	const fav_list = document.getElementById('fav_list');
	let local_data = JSON.parse(localStorage.getItem('local_data')) || [];
	
	if ( local_data.length === 0 ) {
		fav_list.innerHTML = '<li>お気に入り美女が登録されていません</li>';
	} else {
		fetchFavoritePosts(local_data);
	}
});

function fetchFavoritePosts(postIds) {
	const fav_list = document.getElementById('fav_list');
	fetch('<?php echo site_url(); ?>/wp-json/wp/v2/posts?_embed&include=' + postIds.join(','))
		.then(response => response.json())
		.then(posts => {
			fav_list.innerHTML = '';
			posts.forEach(post => {
				const li = document.createElement('li');
				li.dataset.postId = post.id;
				const thumbnail = post._embedded['wp:featuredmedia'] ? post._embedded['wp:featuredmedia'][0].source_url : '';
				const date = new Date(post.date).toLocaleDateString();
				
				li.innerHTML = `
					<article>
						<dl>
							<dt>
								<a href="${post.link}">
									<img src="${thumbnail}">
								</a>
							</dt>
							<dd>
								<div>
									<h2>${post.title.rendered}</h2>
									<time>${post.date}</time>
								</div>
							</dd>
						</dl>
						<button class='fav_remove'>削除</button>
					</article>
				`;
				fav_list.appendChild(li);
				
			});
			
			// 削除イベント
			document.querySelectorAll('.fav_remove').forEach(button => {
				button.addEventListener('click', removeFavoritePosts);
			});
		});
}

function removeFavoritePosts(event) {
	const fav_list = document.getElementById('fav_list');
	let local_data = JSON.parse(localStorage.getItem('local_data')) || [];
	const postId = parseInt(event.target.closest('li').dataset.postId, 10);
	
	local_data = local_data.filter(id => parseInt(id,10) !== postId);
	localStorage.setItem('local_data', JSON.stringify(local_data));
	
	if ( local_data.length === 0 ) {
		fav_list.innerHTML = '<li>お気に入り美女が登録されていません</li>';
	} else {
		fetchFavoritePosts(local_data);
	}
}
</script>

single.php

<button class='fav_btn' data-post-id='<?php the_ID(); ?>'>☆</button>

	<!-- お気に入り機能 -->
	<script>
	document.addEventListener('DOMContentLoaded', function() {

		const fav_btns = document.querySelectorAll('.fav_btn');
		let local_data = JSON.parse( localStorage.getItem('local_data') ) || [];
		
		// お気に入り済みのページを閲覧したときの処理
		fav_btns.forEach(fav_btn => {
			const postId = fav_btn.dataset.postId;
			if ( local_data.includes(postId) ) {
				fav_btn.textContent = '★';
				fav_btn.style.background = 'radial-gradient(circle farthest-corner at 10% 20%,  rgba(249,232,51,1) 0%, rgba(250,196,59,1) 100.2% )';
				fav_btn.style.color = '#fff';
			}
		});
		
		// ボタンがクリックされたときの処理
		fav_btns.forEach(fav_btn => {
			fav_btn.addEventListener('click', function(){
				const postId = fav_btn.dataset.postId;
				if ( local_data.includes(postId) ) {
					local_data = local_data.filter(id => id !== postId);
					fav_btn.textContent = '☆';
					fav_btn.style.background = '#fff';
					fav_btn.style.color = 'var(--lightgrey)';
				} else {
					local_data.push(postId);
					fav_btn.textContent = '★';
					fav_btn.style.background = 'radial-gradient(circle farthest-corner at 10% 20%,  rgba(249,232,51,1) 0%, rgba(250,196,59,1) 100.2% )';
					fav_btn.style.color = '#fff';
				}
				localStorage.setItem('local_data', JSON.stringify(local_data));		
			})

		});
	});
	</script>
ホームに戻る