Function.PHP Code
/* ==========================================
WOOCOMMERCE LIKE & DISLIKE SYSTEM
Shop Page + Single Product Page
========================================== */
// 1. Create custom voting database table
add_action('init', 'pmd_vote_create_table', 1);
function pmd_vote_create_table() {
global $wpdb;
$version = '1.0';
if (get_option('pmd_vote_db_version') === $version) {
return;
}
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$table = $wpdb->prefix . 'product_votes';
$charset = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
product_id bigint(20) unsigned NOT NULL,
voter_key char(64) NOT NULL,
vote varchar(10) NOT NULL,
created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY product_voter (product_id, voter_key),
KEY product_vote (product_id, vote)
) $charset;";
dbDelta($sql);
update_option('pmd_vote_db_version', $version);
}
// 2. Generate guest voter cookie
add_action('template_redirect', 'pmd_vote_guest_cookie');
function pmd_vote_guest_cookie() {
if (!function_exists('is_woocommerce') ||
!(is_woocommerce() || is_product())) {
return;
}
if (is_user_logged_in() || !empty($_COOKIE['pmd_voter'])) {
return;
}
$token = bin2hex(random_bytes(32));
setcookie('pmd_voter', $token, [
'expires' => time() + YEAR_IN_SECONDS,
'path' => COOKIEPATH ?: '/',
'domain' => COOKIE_DOMAIN,
'secure' => is_ssl(),
'httponly' => true,
'samesite' => 'Lax'
]);
$_COOKIE['pmd_voter'] = $token;
}
// 3. Get unique voter identity
function pmd_vote_get_voter_key() {
if (is_user_logged_in()) {
$identity = 'user:' . get_current_user_id();
} else {
$token = isset($_COOKIE['pmd_voter'])
? sanitize_text_field(wp_unslash($_COOKIE['pmd_voter']))
: '';
if (!preg_match('/^[a-f0-9]{64}$/', $token)) {
return false;
}
$identity = 'guest:' . $token;
}
return hash('sha256', $identity);
}
// 4. Get product vote counts
function pmd_vote_get_counts($product_id) {
global $wpdb;
$table = $wpdb->prefix . 'product_votes';
$result = $wpdb->get_row(
$wpdb->prepare(
"SELECT
SUM(CASE WHEN vote = 'like' THEN 1 ELSE 0 END) AS likes,
SUM(CASE WHEN vote = 'dislike' THEN 1 ELSE 0 END) AS dislikes
FROM $table
WHERE product_id = %d",
$product_id
)
);
return [
'likes' => (int) ($result->likes ?? 0),
'dislikes' => (int) ($result->dislikes ?? 0)
];
}
// 5. Render Like & Dislike buttons
function pmd_vote_buttons($product_id) {
if (!$product_id) {
return;
}
$counts = pmd_vote_get_counts($product_id);
global $wpdb;
$table = $wpdb->prefix . 'product_votes';
$voter_key = pmd_vote_get_voter_key();
$current_vote = '';
if ($voter_key) {
$current_vote = (string) $wpdb->get_var(
$wpdb->prepare(
"SELECT vote FROM $table
WHERE product_id = %d AND voter_key = %s",
$product_id,
$voter_key
)
);
}
?>
<div class="pmd-vote-box"
data-product-id="<?php echo esc_attr($product_id); ?>">
<button type="button"
class="pmd-vote-btn <?php echo $current_vote === 'like' ? 'is-active' : ''; ?>"
data-vote="like"
aria-label="Like this product"
aria-pressed="<?php echo $current_vote === 'like' ? 'true' : 'false'; ?>">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M7 10v12H3V10h4zm2 12h9.5a2 2 0 0 0 1.96-1.6l1.5-8A2 2 0 0 0 20 10h-6l1-5.2A2.4 2.4 0 0 0 12.6 2L8 10v12z"/>
</svg>
<span class="pmd-like-count"><?php echo esc_html($counts['likes']); ?></span>
</button>
<button type="button"
class="pmd-vote-btn <?php echo $current_vote === 'dislike' ? 'is-active' : ''; ?>"
data-vote="dislike"
aria-label="Dislike this product"
aria-pressed="<?php echo $current_vote === 'dislike' ? 'true' : 'false'; ?>">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M17 14V2h4v12h-4zm-2-12H5.5a2 2 0 0 0-1.96 1.6l-1.5 8A2 2 0 0 0 4 14h6l-1 5.2A2.4 2.4 0 0 0 11.4 22l4.6-8V2z"/>
</svg>
<span class="pmd-dislike-count"><?php echo esc_html($counts['dislikes']); ?></span>
</button>
<span class="pmd-vote-message"
role="status"
aria-live="polite"></span>
</div>
<?php
}
// 6. Add buttons on single product page
add_action(
'woocommerce_single_product_summary',
'pmd_vote_single_product',
35
);
function pmd_vote_single_product() {
global $product;
if ($product) {
pmd_vote_buttons($product->get_id());
}
}
// 7. Add buttons on shop and category pages
add_action(
'woocommerce_after_shop_loop_item',
'pmd_vote_shop_product',
15
);
function pmd_vote_shop_product() {
global $product;
if ($product) {
pmd_vote_buttons($product->get_id());
}
}
// 8. AJAX voting system
add_action('wp_ajax_pmd_submit_vote', 'pmd_submit_vote');
add_action('wp_ajax_nopriv_pmd_submit_vote', 'pmd_submit_vote');
function pmd_submit_vote() {
check_ajax_referer('pmd_vote_nonce', 'nonce');
global $wpdb;
$product_id = absint($_POST['product_id'] ?? 0);
$vote = isset($_POST['vote'])
? sanitize_text_field(wp_unslash($_POST['vote']))
: '';
if (
!$product_id ||
get_post_type($product_id) !== 'product' ||
!in_array($vote, ['like', 'dislike'], true)
) {
wp_send_json_error([
'message' => 'Invalid product or vote.'
], 400);
}
$voter_key = pmd_vote_get_voter_key();
if (!$voter_key) {
wp_send_json_error([
'message' => 'Please refresh the page and try again.'
], 403);
}
$table = $wpdb->prefix . 'product_votes';
// Insert new vote or update previous vote
$sql = $wpdb->prepare(
"INSERT INTO $table
(product_id, voter_key, vote, created_at, updated_at)
VALUES (%d, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
vote = VALUES(vote),
updated_at = VALUES(updated_at)",
$product_id,
$voter_key,
$vote,
current_time('mysql'),
current_time('mysql')
);
$saved = $wpdb->query($sql);
if ($saved === false) {
wp_send_json_error([
'message' => 'Unable to save your vote. Please try again.'
], 500);
}
$counts = pmd_vote_get_counts($product_id);
wp_send_json_success([
'likes' => $counts['likes'],
'dislikes' => $counts['dislikes'],
'vote' => $vote,
'message' => 'Thank you for your feedback!'
]);
}
// 9. Load JavaScript
add_action('wp_enqueue_scripts', 'pmd_vote_enqueue_scripts');
function pmd_vote_enqueue_scripts() {
if (!function_exists('is_woocommerce')) {
return;
}
if (!(is_woocommerce() || is_product())) {
return;
}
wp_register_script(
'pmd-vote-script',
false,
['jquery'],
'1.0',
true
);
wp_enqueue_script('pmd-vote-script');
wp_localize_script('pmd-vote-script', 'pmdVoteData', [
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('pmd_vote_nonce')
]);
wp_add_inline_script('pmd-vote-script', "
jQuery(function($) {
$(document).on('click', '.pmd-vote-btn', function(e) {
e.preventDefault();
var button = $(this);
var box = button.closest('.pmd-vote-box');
if (box.hasClass('pmd-loading')) {
return;
}
var productId = box.data('product-id');
var vote = button.data('vote');
box.addClass('pmd-loading');
box.find('.pmd-vote-message').text('Saving...');
$.ajax({
url: pmdVoteData.ajaxurl,
type: 'POST',
data: {
action: 'pmd_submit_vote',
nonce: pmdVoteData.nonce,
product_id: productId,
vote: vote
},
success: function(response) {
if (response.success) {
box.find('.pmd-like-count')
.text(response.data.likes);
box.find('.pmd-dislike-count')
.text(response.data.dislikes);
box.find('.pmd-vote-btn')
.removeClass('is-active')
.attr('aria-pressed', 'false');
var activeButton = box.find(
'[data-vote=\"' + response.data.vote + '\"]'
);
activeButton.addClass('is-active')
.attr('aria-pressed', 'true');
box.find('.pmd-vote-message')
.text(response.data.message);
} else {
box.find('.pmd-vote-message')
.text(response.data.message || 'Vote failed.');
}
},
error: function() {
box.find('.pmd-vote-message')
.text('Something went wrong. Please try again.');
},
complete: function() {
box.removeClass('pmd-loading');
}
});
});
});
");
}
CSS Code
/* WooCommerce Like Dislike Design */
.pmd-vote-box {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 10px;
margin: 15px 0;
}
.pmd-vote-btn {
display: inline-flex !important;
align-items: center;
justify-content: center;
gap: 7px;
min-width: 65px;
padding: 9px 13px !important;
border: 1px solid #e2e5e9 !important;
border-radius: 8px !important;
background: #ffffff !important;
color: #444 !important;
font-size: 14px !important;
font-weight: 600;
line-height: 1.4 !important;
cursor: pointer;
transition: all .2s ease;
box-shadow: none !important;
}
.pmd-vote-btn svg {
width: 17px;
height: 17px;
fill: currentColor;
flex-shrink: 0;
}
.pmd-vote-btn:first-child:hover,
.pmd-vote-btn:first-child.is-active {
color: #16a34a !important;
background: #ecfdf3 !important;
border-color: #16a34a !important;
}
.pmd-vote-btn:last-of-type:hover,
.pmd-vote-btn:last-of-type.is-active {
color: #dc2626 !important;
background: #fef2f2 !important;
border-color: #dc2626 !important;
}
.pmd-vote-btn:focus-visible {
outline: 2px solid #2563eb;
outline-offset: 3px;
}
.pmd-vote-box.pmd-loading {
opacity: .65;
pointer-events: none;
}
.pmd-vote-message {
width: 100%;
display: block;
font-size: 12px;
color: #16a34a;
}
/* Shop page */
.woocommerce ul.products li.product .pmd-vote-box {
justify-content: center;
margin: 12px 0;
}
/* Single product page */
.single-product .pmd-vote-box {
justify-content: flex-start;
margin: 20px 0;
}
/* Mobile responsive */
@media (max-width: 600px) {
.pmd-vote-box {
gap: 7px;
}
.pmd-vote-btn {
padding: 8px 11px !important;
font-size: 13px !important;
}
.pmd-vote-btn svg {
width: 16px;
height: 16px;
}
}