まず、Elementorで投稿テンプレートを開き、いいね!ボタンを配置したい場所に**「カスタムHTML」ウィジェット**をドラッグ&ドロップします。ウィジェットに以下のコードを貼り付けてください。
<div class="like-button" data-post-id="123">
<i class="far fa-heart"></i>
<span class="like-text">いいね!</span>
<span class="like-count">0</span>
</div><i class="far fa-heart"></i>は、Font Awesomeのアイコンです。もしアイコンが表示されない場合は、Elementorの設定でFont Awesome 4サポートの読み込みが有効になっているか確認してください。data-post-id="123"の部分は、ブログ記事のIDに置き換えてください。このIDを元に、投稿ごとのクリック数を管理します。次に、ボタンのデザインを設定します。Elementorの「カスタムCSS」セクションに以下のコードを貼り付けます。このCSSが、ボタンの色やアイコンの動きを制御します。
.like-button {
display: flex;
align-items: center;
gap: 5px;
cursor: pointer;
color: #ccc;
transition: color 0.3s ease;
}
.like-button .fa-heart {
font-size: 28px;
transition: transform 0.3s ease;
}
.like-button .like-text,
.like-button .like-count {
font-size: 16px;
font-weight: bold;
}
/* いいね!された時のスタイル */
.like-button.liked {
color: #ff385c;
}
.like-button.liked .fa-heart {
transform: scale(1.2);
}
.like-button.liked:active .fa-heart {
transform: scale(1.1);
}
/* 10回押された後のスタイル */
.like-button.disabled {
opacity: 0.5;
cursor: not-allowed;
pointer-events: none;
}color: #ccc;が初期のボタンの色です。likedクラスが付くと#ff385cに変わり、色が変化するアニメーションが発動します。.disabledクラスは、後述のJavaScriptによって追加され、ボタンを無効化します。最後に、ボタンのクリック回数をカウントし、10回で停止するロジックを実装します。このコードは、サイト全体に適用させるのがベストです。
WordPressのダッシュボードで、左メニューの「Elementor」→「カスタムコード」に進みます。「新規追加」をクリックし、以下の設定を行います。
<script>
document.addEventListener('DOMContentLoaded', () => {
const likeButtons = document.querySelectorAll('.like-button');
const MAX_CLICKS = 10;
const likedCounts = JSON.parse(localStorage.getItem('likedCounts')) || {};
likeButtons.forEach(button => {
const postId = button.dataset.postId;
const count = likedCounts[postId] || 0;
const countElement = button.querySelector('.like-count');
countElement.textContent = count;
if (count >= MAX_CLICKS) {
button.classList.add('disabled');
}
});
likeButtons.forEach(button => {
button.addEventListener('click', () => {
const postId = button.dataset.postId;
const isDisabled = button.classList.contains('disabled');
if (isDisabled) {
return;
}
likedCounts[postId] = (likedCounts[postId] || 0) + 1;
localStorage.setItem('likedCounts', JSON.stringify(likedCounts));
const currentCount = likedCounts[postId];
const countElement = button.querySelector('.like-count');
countElement.textContent = currentCount;
button.classList.add('liked');
setTimeout(() => {
button.classList.remove('liked');
}, 500);
if (currentCount >= MAX_CLICKS) {
button.classList.add('disabled');
}
});
});
});
</script>localStorageは、ユーザーのブラウザにデータを保存する機能です。これにより、ユーザーがページを離れてもクリック回数が保持されます。MAX_CLICKS の値を変更すれば、クリック回数の上限を簡単に変更できます。この3つのステップで、プラグインに頼らずに、Instagram風のいいね!ボタンをElementorで実装できます。見た目のカスタマイズも自由自在なので、ぜひあなたのブログに合ったデザインを試してみてください。