Skip to content

Instantly share code, notes, and snippets.

@pepe84
Forked from Tyxz/polylang-sync-rate-my-post.php
Last active September 7, 2022 16:46
Show Gist options
  • Save pepe84/fd063783282fc89b40b193a54da39dc9 to your computer and use it in GitHub Desktop.
Save pepe84/fd063783282fc89b40b193a54da39dc9 to your computer and use it in GitHub Desktop.
Sync the ratings of the Wordpress plugin "rate-my-post" with all polylang translated variants of it.
<?php
/**
* @package polylang-sync-rate-my-post
*/
/*
Plugin Name: polylang-sync-rate-my-post
Plugin URI: https://gist.github.com/Tyxz/09ea3d4b205738be2a8b2b777892b62a
Description: Sync the ratings of the Wordpress plugin "rate-my-post" with all polylang translated variants of it.
Version: 0.1
Author: Arne Rantzen
Author URI: https://github.com/Tyxz
License: ???
Text Domain: polylang-sync-rate-my-post
*/
if ( ! defined( 'ABSPATH' ) ) {
die;
}
function pll_sync_store_rating($post_id, $translation_id, $new_avg_rating, $new_vote_count, $submitted_rating) {
// Update rating sum
$new_ratings_sum = $submitted_rating;
if ( $new_vote_count > 1) {
$new_ratings_sum = get_post_meta($post_id, 'rmp_rating_val_sum', true);
}
// Store new sum in linked page
if ( ! add_post_meta( $translation_id, 'rmp_vote_count', $new_vote_count, true ) ) {
update_post_meta( $translation_id, 'rmp_vote_count', $new_vote_count );
}
if ( ! add_post_meta( $translation_id, 'rmp_rating_val_sum', $new_ratings_sum, true ) ) {
update_post_meta( $translation_id, 'rmp_rating_val_sum', $new_ratings_sum );
}
if ( ! add_post_meta( $translation_id, 'rmp_avg_rating', $new_avg_rating, true ) ) {
update_post_meta( $translation_id, 'rmp_avg_rating', $new_avg_rating );
}
}
function pll_sync_after_vote( $post_id, $new_avg_rating, $new_vote_count, $submitted_rating ) {
// Check if polylang is enabled and working
if (function_exists('pll_languages_list') && function_exists('pll_get_post')) {
// get data from switcher for current page
$raw = pll_the_languages( array('post_id' => $post_id, 'raw' => 1));
// parse trough supported languages
foreach($raw as $key => $value) {
if(!$value['current_lang']) {
$translation_id = pll_get_post( $post_id, $value['slug']);
pll_sync_store_rating($post_id, $translation_id, $new_avg_rating, $new_vote_count, $submitted_rating);
}
}
}
}
add_action('rmp_after_vote', 'pll_sync_after_vote', 10, 4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment