Hover for random Monopoly post
.random-post-image-container {
position: relative;
width: 300px;
height: 200px;
cursor: pointer;
overflow: hidden;
}
.image-placeholder {
position: absolute;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background-color: #f0f0f0;
color: #333;
font-weight: bold;
transition: opacity 0.3s ease;
z-index: 2;
}
.random-image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-size: cover;
background-position: center;
opacity: 0;
transition: opacity 0.3s ease;
z-index: 1;
}
.random-post-image-container:hover .image-placeholder {
opacity: 0;
}
.random-post-image-container:hover .random-image {
opacity: 1;
}
jQuery(document).ready(function($) {
// Array to store post data
let monopolyPosts = [];
// Function to fetch posts from the 'monopoly' category
function fetchMonopolyPosts() {
$.ajax({
url: '',
type: 'post',
data: {
action: 'get_monopoly_posts',
nonce: ''
},
success: function(response) {
if(response.success && response.data.length > 0) {
monopolyPosts = response.data;
}
}
});
}
// Fetch posts when page loads
fetchMonopolyPosts();
// Function to display random post image on hover
$('.random-post-image-container').on('mouseenter', function() {
if(monopolyPosts.length > 0) {
// Get random post from array
const randomIndex = Math.floor(Math.random() * monopolyPosts.length);
const randomPost = monopolyPosts[randomIndex];
// Set the background image
$(this).find('.random-image').css('background-image', 'url(' + randomPost.image + ')');
}
});
});
<?php
// Add this code to your theme's functions.php file or use a plugin like Code Snippets
function register_monopoly_posts_ajax() {
add_action('wp_ajax_get_monopoly_posts', 'get_monopoly_posts');
add_action('wp_ajax_nopriv_get_monopoly_posts', 'get_monopoly_posts');
}
add_action('init', 'register_monopoly_posts_ajax');
function get_monopoly_posts() {
// Verify nonce
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'get_monopoly_posts_nonce')) {
wp_send_json_error('Invalid nonce');
}
// Query posts from monopoly category
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1, // Get all posts
'category_name' => 'monopoly',
'fields' => 'ids' // Only get post IDs for efficiency
);
$posts = get_posts($args);
$post_data = array();
foreach($posts as $post_id) {
if(has_post_thumbnail($post_id)) {
$post_data[] = array(
'id' => $post_id,
'title' => get_the_title($post_id),
'image' => get_the_post_thumbnail_url($post_id, 'medium')
);
}
}
wp_send_json_success($post_data);
}
?>