Display Output During Each Iteration of for Loop - javascript

I want to show a message displaying the result of each iteration of a for loop in php.
I have tried several methods using jquery, ajax etc but they doesn't seem to fit my needs or either i am not getting to work around with them.
What my script does?
It scans a website, grab some links, then visits each link one by one and grab an image from each page and finally send it to my wordpress including its title and image.
What's the problem?
The problem is that as there can be several links (more than 200), so even though my scripts displays message regarding the success but it shows the messages after the whole loop is finished executing.
What I want to do?
Now, what i want to do that during each iteration the message should be shown on the browser rather than waiting for the loop to complete i.e. during 1st iteration (Posted Successfully) then during 2nd (Not Posted) and so on...
Here is the code:
<?php
$category = array();
for ($i = 0; $i < count($result); $i++)
{
set_time_limit(30);
// Check if post already exists
global $wpdb;
$query = $wpdb->prepare('SELECT ID FROM ' . $wpdb->posts .
' WHERE post_name = %s',sanitize_title_with_dashes($result[$i]->title));
$cID = $wpdb->get_var($query);
if (!empty($cID))
{
echo $result[$i]->title .
" <font style='color:#FF0000; font-weight:bold;'>Already Exists.</font><br />";
} else
{
$inner_html = file_get_html($result[$i]->href);
$inner_result_image = $inner_html->find('meta[property=og:image]',1);
$inner_result_cats = $inner_html->find('a[rel=category tag]');
$title = $result[$i]->title;
$body = "<a href='$inner_result_image->content'><img src='$inner_result_image->content' /></a>";
// Automatically Create new Category if it doesn't exist.
foreach ($inner_result_cats as $cats)
{
if (!($cats->innertext == "Jobs"))
{
array_push($category,$cats->innertext);
$count = 0;
// For Cities
if (search_city($cats->innertext))
{
wp_insert_term($cats->innertext,'category',array(
'description' => '',
'slug' => '',
'parent' => '14')); // Jobs by City
} else
{
$count += 1;
}
// For Qualification
if (search_qualification($cats->innertext))
{
wp_insert_term($cats->innertext,'category',array(
'description' => '',
'slug' => '',
'parent' => '51')); // Jobs by Qualification
} else
{
$count += 1;
}
// International Jobs
if (check_international(parse_url($cats->href,PHP_URL_PATH)))
{
wp_insert_term($cats->innertext,'category',array(
'description' => '',
'slug' => '',
'parent' => '52')); // International Jobs
} else
{
$count += 1;
}
if ($count == 3)
{
wp_insert_term($cats->innertext,'category',array('description' => '','slug' =>
''));
}
} // End if NewsPaper Check
} // End if Auto Category
echo "<br />";
$postdate = new IXR_Date(strtotime($date));
$title = htmlentities($title,ENT_NOQUOTES,"UTF-8");
$content = array(
'title' => $title,
'description' => $body,
'mt_allow_comments' => 1, // 1 to allow comments
'mt_allow_pings' => 1, // 1 to allow trackbacks
'post_type' => 'post',
'date_created_gmt' => $postdate,
'categories' => $category,
);
// Create the client object
$client = new IXR_Client('http://localhost/FDJ/xmlrpc.php');
$username = "Admin";
$password = "Password";
$params = array(0,
$username,
$password,
$content,
true); // Last parameter is 'true' which means post immediately, to save as draft set it as 'false'
// Run a query for PHP
if (!$client->query('metaWeblog.newPost',$params))
{
die('Something went wrong - ' . $client->getErrorCode() . ' : ' . $client->
getErrorMessage());
echo $title . " <font style='color:#FF0000; font-weight:bold;'>Not Posted.</font><br />";
} else
echo $title . " <font style='color:#00FF00; font-weight:bold;'>Posted Successfully.</font><br />";
}
} // End if Main
?>

Related

Wordpress - post edit Custom Metabox with post search

I've impletend this code that creates a custom metabox to choose a related article for a specific post type. It creates a list of 1000 articles to choose from.
Since I have a lot of articles I would like to replace the list with the same search form wp uses in nav-menus edit page (wp-admin/nav-menus.php), where I can search trough pages and click on a checkbox to select the page to link.
Here is my code:
// Add the Meta Box
function add_related_article_meta_box() {
add_meta_box(
'related_article_meta_box', // $id
'Related Article', // $title
'show_related_article_meta_box', // $callback
'wpdmpro', // $post type
'side', // $position
'high'); // $priority
}
add_action('add_meta_boxes', 'add_related_article_meta_box');
// Array field
$prefix = 'related_article_';
$custom_meta_fields = array(
array(
'label' => 'Post List',
'desc' => 'Select your article',
'id' => $prefix.'post_id',
'type' => 'post_list',
'post_type' => array('post')
)
);
// Callback
function show_related_article_meta_box() {
global $custom_meta_fields, $post;
// nonce verify
echo '<input type="hidden" name="related_article_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';
// form table start and loop
echo '<table class="form-table">';
foreach ($custom_meta_fields as $field) {
// get filed value if exists
$meta = get_post_meta($post->ID, $field['id'], true);
// table tr start
echo '<tr>
<td>';
switch($field['type']) {
// Post List
case 'post_list':
$items = get_posts( array (
'post_type' => $field['post_type'],
'posts_per_page' => 1000
));
echo '<select name="'.$field['id'].'" id="'.$field['id'].'">
<option value="">Select</option>'; // Post Select
foreach($items as $item) {
$custom_post_date = date_i18n( 'd-m-Y', strtotime($item->post_date));
echo '<option value="'.$item->ID.'"',$meta == $item->ID ? ' selected="selected"' : '','>' .$custom_post_date. '- ' .$item->post_title.'</option>';
} // end foreach
echo '</select><br /><span class="description">'.$field['desc'].'</span>';
break;
} //end switch
echo '</td></tr>';
} // end foreach
echo '</table>'; // end tabella
}
// Save data
function save_custom_meta($post_id) {
global $custom_meta_fields;
// verifica nonce
if (!wp_verify_nonce($_POST['related_article_meta_box_nonce'], basename(__FILE__)))
return $post_id;
// check autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return $post_id;
// check permessions
if ('page' == $_POST['post_type']) {
if (!current_user_can('edit_page', $post_id))
return $post_id;
} elseif (!current_user_can('edit_post', $post_id)) {
return $post_id;
}
// loop into fields and save
foreach ($custom_meta_fields as $field) {
$old = get_post_meta($post_id, $field['id'], true);
$new = $_POST[$field['id']];
if ($new && $new != $old) {
update_post_meta($post_id, $field['id'], $new);
} elseif ('' == $new && $old) {
delete_post_meta($post_id, $field['id'], $old);
}
} // end foreach
// save taxonomies
$post = get_post($post_id);
$category = $_POST['category'];
wp_set_object_terms( $post_id, $category, 'category' );
}
add_action('save_post', 'save_custom_meta');
Any hint on how to edit callback function (and save data function) in order to get this kind of result would be appreciated.
Thank you for your help.

Wordpress favorite system without plugin learning method

Good afternoon devs, I developed a favorite system using Wordpress and php, it works as follows, clicking on the add favorites icon I send an ajax request to php with the favorite id and the user id logged in. php processes this by saving in user_meta the information with number of favorite users and in the logged user an array with the ids of the favorites. Anyway, the question is, the system is working, but whenever I develop something I keep wondering if there is a way to improve the code, if there is a way to do it in a better way, I will leave my code here.
All this for learning ok?
HTML
<div class="stats -favorites">
<a class="icon -click <?php echo is_favorite(get_current_user_id(), $user_ID) ? 'fa' : 'far' ?> fa-heart" data-js="favorite" data-favorite="<?php echo $user_ID; ?>" data-user="<?php echo get_current_user_id(); ?>"></a>
<span class="label" data-js="favorite_label">
<?php echo get_favorites_num( $user_ID ); ?>
</span>
<span class="value">favoritos</span>
</div>
JS
function setFavorite(userid, favoriteid) {
var favorite_field = $('[data-js="favorite"]');
var favorite_label = $('[data-js="favorite_label"]');
$.ajax({
url : appmeninas_ajax_params.ajaxurl,
data : {
'action' : 'setfavorite',
'userid' : userid,
'favoriteid' : favoriteid,
},
dataType : 'json',
type : 'POST',
cache : false,
beforeSend : function( xhr ) {
favorite_field.removeClass('far fa fa-heart').addClass('fas fa-circle-notch fa-spin');
},
success : function( data ) {
var icon = (data.is_favorite) ? 'fa fa-heart' : 'far fa-heart';
favorite_field.removeClass('fas fa-circle-notch fa-spin');
favorite_field.addClass(icon);
favorite_label.html('');
favorite_label.append(data.favorites_num);
}
});
};
$('[data-js=favorite]').click(function() {
var favoriteid = $(this).data('favorite');
var userid = $(this).data('user');
setFavorite(userid, favoriteid);
});
PHP
function setfavorite() {
$userid = $_POST['userid'];
$favoriteid = $_POST['favoriteid'];
// user require favorite
$favorites_list = get_field( 'favorites_list', 'user_' .$userid );
$favorites_num = get_field( 'favorites', 'user_' .$favoriteid );
if ( !$favorites_list ) {
$favorites_list = [];
}
// profile favorite
if ( in_array( $favoriteid, $favorites_list ) ) {
$favorites_num--;
$tmp = array_search( $userid, $favorites_list );
array_splice( $favorites_list, $tmp, 1 );
$is_favorite = false;
} else {
$favorites_num++;
$favorites_list[] = $favoriteid;
$is_favorite = true;
}
// set favorite counter
update_user_meta( $favoriteid, 'favorites', $favorites_num );
// set favorite list
update_user_meta( $userid, 'favorites_list', $favorites_list );
echo json_encode( array(
'favorites_num' => $favorites_num,
'favorites_list' => $favorites_list,
'is_favorite' => $is_favorite,
) );
die();
}
function is_favorite($userid, $favoriteid) {
$favorites_list = get_field( 'favorites_list', 'user_' .$userid );
return in_array( $favoriteid, $favorites_list );
}
function get_favorites_num( $userid ) {
if ( get_field( 'favorites', 'user_' .$userid ) ) {
return get_field( 'favorites', 'user_' .$userid );
} else {
return '0';
}
}
add_action('wp_ajax_setfavorite', 'setfavorite');
add_action('wp_ajax_nopriv_setfavorite', 'setfavorite');
i maybe will implement a same function in the next 2 months. i allready started researching plugins but as your question states, it does not seems to be very hard.
I try to come back then but first i need a frontend profile page where i can list the favorites.
The first impression looks good so far but first i would give attention to the $_POST array and sanitize and maybe validate the values because sometimes not only your ajax will call.
if ( isset($_POST['userid']) && isset($_POST['favoriteid']) ) { // Both $_POST values exist
$userid = filter_var($_POST['userid'], FILTER_SANITIZE_NUMBER_INT);
$favoriteid = filter_var($_POST['favoriteid'], FILTER_SANITIZE_NUMBER_INT);
if ( filter_var($userid, FILTER_VALIDATE_INT) && filter_var($favoriteid, FILTER_VALIDATE_INT) ) {
// $_POST was save, both values are Integers
}
}
The second one is related to get_field which is a function provided by the ACF Plugin. therefor when deactivating it or it gets replaced with JCF, it may cause errors.
You can avoid this by using if ( function_exists('get_field') ) {. Then your code only stops working when ACF gets deactivated.
Otherwise it seems not neccessary to use the ACF function and you can use the WP native function get_user_meta instead:
function is_favorite($userid, $favoriteid){
$favorites_list = get_user_meta($userid, 'favorites_list', true);
// check the new output instead of get_field
return in_array( $favoriteid, $favorites_list );
}
and also all calls to get_field('favorites', 'user_' .$favoriteid) seem to be wrong then. The ACF Docs say the the second parameter of get_field ist a post ID so i don't know what 'user_' means then. I would call:
function get_favorites_num($favoriteid){
return get_user_meta($favoriteid, 'favorites', true) || 0;
}
i now have my own favorite system ready where users can favorite posts from a specific post_type
HTML
<?php while ( have_posts() ) : the_post() ?>
<?php
$customPostsMeta = get_post_custom();
$favorite_class = 'favorite-me disabled';
$fav_count = isset($customPostsMeta['_favorites']) ? intval($customPostsMeta['_favorites'][0]) : 0;
$fav_count_text = $fav_count > 0 ? '(' . $fav_count . ')' : '';
$fav_count = ' <span class="fav-count clearfix">' . $fav_count_text . '</span>';
$favorite_title = '';
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
$favorites = get_user_meta($user->ID, '_favorite_posts', true);
$fav_key = array_search($post_id, $favorites);
$is_favorite = ( $fav_key !== false );
if ( $is_favorite ) {
$favorite_class .= ' is-favorite';
$favorite_title = ' title="' . get_the_title() . ' ' . __('favorisieren', 'myTheme') . '"';
} else {
$favorite_title = ' title="' . get_the_title() . ' ' . __('nicht mehr favorisieren', 'myTheme') . '"';
}
}
?>
<a class="<?php echo $favorite_class; ?>" href="#post-<?php the_ID() ?>"<?php echo $favorite_title; ?>><?php echo __('Favorit', 'myTheme')?><?php echo $fav_count; ?></a>
<?php endwhile; ?>
JS
// i use a small self written JS module frame where this is included as module
// favorite.setup() is fired imediatly, favorite.ready() fires on document ready
// you can see a full version here: https://dev.alphabetisierung.at/wp-content/themes/sandbox_2017/js/actions.js
// line 732
/**
* Favorites ajax system
* =====================
* https://stackoverflow.com/questions/60468237
*/
favorite: {
options: {
selectors: {
link: '.favorite-me',
fav_count: '.fav-count'
},
classNames: {
disabled: 'disabled',
is_favorite: 'is-favorite',
}
},
events: function(){
var options = this.options,
selectors = options.selectors,
classNames = options.classNames,
info = this.info;
this.$favorites.on('click', function(event){
var post_id = this.hash.replace('#post-', ''),
$favorite_link = $(this).addClass(classNames.disabled),
$fav_count = $favorite_link.children(selectors.fav_count),
$favorite = $.ajax({
url: myTheme.page.urls.ajax,
type: 'post',
data: {
action: info.name, // derived from the module name "favorite"
verify: myTheme.page.verify, // https://developer.wordpress.org/reference/functions/check_ajax_referer/
post_id: post_id
// user_id of user who takes the action is not necessary
}
});
$favorite.done(function(data){
var fav_count = data.hasOwnProperty('fav_count') ? parseInt(data.fav_count) : 0,
fav_count_text = '',
is_favorite = data.hasOwnProperty('is_favorite') ? data.is_favorite : false;
if ( fav_count > 0 ) {
fav_count_text = '(' + fav_count + ')';
}
$fav_count.html(fav_count_text);
if ( is_favorite && !$favorite_link.is('.' + classNames.is_favorite) ) {
$favorite_link.addClass(classNames.is_favorite);
} else {
$favorite_link.removeClass(classNames.is_favorite);
}
$favorite_link.removeClass(classNames.disabled);
});
event.preventDefault();
});
},
ready: function ready(){
var selectors = this.options.selectors,
classNames = this.options.classNames;
this.$favorites = $(selectors.link).removeClass(classNames.disabled);
this.events();
},
setup: function setup(){
var setup = myTheme.info.is_user_logged_in && myTheme.info.post_type === 'my_custom_post_type';
return setup; // only for my post_type
}
PHP
add_action('wp_enqueue_scripts', 'myTheme_enqueue_scripts');
add_action('wp_ajax_favorite', 'myTheme_set_favorite');
// wp_ajax_nopriv_{action} is not necessary when feature is only for logged in users
function myTheme_enqueue_scripts(){
$data = array(
'id' => get_the_ID(),
'urls' => array(
'ajax' => admin_url('admin-ajax.php'),
'template' => get_stylesheet_directory_uri(),
),
'verify' => wp_create_nonce('myThemeOrAction_ajax_call'), // used for check_ajax_referer()
// ...
'info' => array(
// ...
'is_user_logged_in' => is_user_logged_in(),
'post_type' => get_post_type(),
),
);
// ...
wp_localize_script('actions', 'myTheme_data', $data );
}
function myTheme_set_favorite(){
check_ajax_referer('myThemeOrAction_ajax_call', 'verify');
if ( isset($_POST['post_id']) ) {
$user = wp_get_current_user(); // here we get the user ID of the current user
$post_id = filter_var($_POST['post_id'], FILTER_SANITIZE_NUMBER_INT);
$post = get_post($post_id);
// $fav_id = filter_var($_POST['fav_id'], FILTER_SANITIZE_NUMBER_INT);
// $fav_user = get_userdata($fav_id); // WP_User
$is_favorite = false;
if ( $post instanceof WP_Post ) { // post ID is valid
// for user favorites it would be
// if ( $fav_user instanceof WP_User ) {
$fav_count = intval(get_post_meta($post->ID, '_favorites', true));
$favorites = get_user_meta($user->ID, '_favorite_posts', true);
if ( !filter_var($fav_count, FILTER_VALIDATE_INT) ) {
$fav_count = 0;
}
if ( !is_array($favorites) || empty($favorites) ) {
$favorites = array();
}
$fav_key = array_search($post->ID, $favorites);
if ( $fav_key !== false ) { // is favorite, remove it
$fav_count--;
unset($favorites[$fav_key]);
} else { // is no favorite, add it
$fav_count++;
$favorites[] = $post->ID;
$is_favorite = true;
}
// set favorite counter
update_post_meta($post->ID, '_favorites', $fav_count);
// set favorite list
update_user_meta($user->ID, '_favorite_posts', $favorites);
// Output
$json = array(
'fav_count' => $fav_count,
'favorites' => $favorites,
'error' => false,
'is_favorite' => $is_favorite,
);
} else {
$json = array('is_favorite' => $is_favorite, 'error' => true, 'message' => 'Invalid Post ID');
}
} else {
$json = array('is_favorite' => $is_favorite, 'error' => true, 'message' => 'No post_id Post ID sent');
}
// wp_send_json sets the http header and ends the request
wp_send_json($json);
}
this are the things i noticed on the way:
verify referer with wp_create_nonce() and check_ajax_referer()
check JSON result data keys for existance with data.hasOwnProperty('key') to avoid possible JS errors
check valid WP_User or WP_Post object
current users ID with is not necessary to send with POST
wp_ajax_nopriv_{action} is not necessary when feature is only for logged in users
use wp_send_json() for ending the response
kind regards
tom

Error parsing JSON file - Incorrect Object

I've replicated a graph script from one Wordpress installation to another
It operates using graph_nat and defs.php - Defs stores the DB details
I have not altered the script after migrating but now I'm getting JSON error
I've checked to ensure after object it's true
I'm struggling to figure out the bug, error reporting doesn't include the JSON error only false positives for PHP
<?php
include ('../wp-load.php');
include ('defs.php');
// we need this so that PHP does not complain about deprectaed functions
error_reporting( 0 );
// Connect to MySQL
// constants stored in defs.php
$db = mysqli_connect("localhost", DB_NAT_USER, DB_NAT_PASS, DB_NAT_NAME);
// get user id
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
if ( $current_user_id == null || $current_user_id == 0) {
$message = 'User not authorized';
die( $message );
}
if ( !$db ) {
die( 'Could not connect to database' );
}
if (!isset($_GET['id'])) {
$message = 'Missing ID url parameter';
die( $message );
}
$id = $_GET['id'];
$practitionerId = $current_user_id;
$query = "SELECT results FROM submissions WHERE ID = ? AND practitionerId = ?";
$result = [];
if ($stmt = $db->prepare($query)) {
$stmt->bind_param('ss', $id, $practitionerId);
$stmt->execute();
$stmt->bind_result($results);
if ($stmt->fetch()) {
$result = $results;
}
$stmt->close();
}
// decode json from database
$json = json_decode($result, true);
$outputArray = [];
$healthIndex = 100;
if ($json) {
foreach($json as $key=>$val) {
$healthEvents = explode(", ", $val);
// filter out empty strings
$healthEventsFiltered = array_filter($healthEvents, function($value) {
if ($value == '') {
return false;
}
return true;
});
// points to decrease per event
$healthDecrease = (count($healthEventsFiltered))*2;
$healthIndex -= $healthDecrease;
if ($healthIndex<0) {
$healthIndex = 0;
}
// implode array to get description string
$arrayString = implode(",<br>", $healthEventsFiltered);
// age groups
$ageGroup = $key*5;
$ar = array("category" => "Age: " . $ageGroup, "column-1" => $healthIndex, "events" => $arrayString);
array_push($outputArray, $ar);
}
echo json_encode($outputArray, true);
} else {
$message = 'Could not decode JSON: ' . $result;
die( $message );
}
// Close the connection
mysqli_close( $db );
?>
Figured it out, I wasn't passing USER ID in url. It was undefined. I should go back to school

Send SMS if found changes in json file

I have this json file that I need to make a cron job for and receive SMS notification when data changes http://www.soyoustart.com/fr/js/dedicatedAvailability/availability-data.json
I need to find out if some server is on stock, so I found this code:
<?php
$cellphone = '15551234567';
$a_track = array('143sys12');
$s = file_get_contents('http://www.soyoustart.com/fr/js/dedicatedAvailability/availability-data.json');
$tmp = json_decode($s, true);
$a = $tmp ['availability'];
$data = array();
foreach ($a as $item) {
if (!in_array($item ['reference'], $a_track)) {
continue;
}
foreach ($item ['zones'] as $zone) {
if ($zone ['availability'] == 'unavailable') {
continue;
}
$data [$item ['reference']] .= $zone ['zone'];
}
}
foreach ($data as $item => $availability) {
$message = "SYS STOCK: $item: $availability";
mail('my#email', 'OMG BUY THIS NOW!', $message);
$url = "http://rest.nexmo.com/sms/json?api_key=xxxx&api_secret=yyyy& from=nnnnnnnn&to=$cellphone&text=" . urlencode($message);
$discard = file_get_contents($url);
}
The problem is that when I trigger it I receive SMS no matter if server is on stock or not and the SMSs keep coming with false positives. I also got this message :
]# /usr/bin/php /home/sys.php
PHP Notice: Undefined index: 143sys12 in /home/sys.php on line 22
I changed your code around a bit and moved the sending of the message in a function to be called when the reference is found.
Take a look:
<?php
$a_track = array('143sys12');
$s = file_get_contents('http://www.soyoustart.com/fr/js/dedicatedAvailability/availability-data.json');
$tmp = json_decode($s, true);
foreach ($tmp['availability'] as $item) {
if (in_array($item['reference'],$a_track)) sendMeAnEmail($item);
}
function sendMeAnEmail($item){
$cellphone = '15551234567';
$message = "SYS STOCK: ". $item["reference"] . PHP_EOL;
$gotStock = 0;
foreach ($item["zones"] as $zone)
if ($zone["availability"] != "unavailable" and $zone['availability'] != 'unknown' ) {
$message .= "Available in the " . $zone["zone"]. " zone, with the " . $zone["availability"] . " status." ;
$gotStock++;
}
$url = "http://rest.nexmo.com/sms/json?api_key=xxxx&api_secret=yyyy&from=nnnnnnnn&to=$cellphone&text=" . urlencode($message);
if ($gotStock > 0) {
print $message . PHP_EOL; // to check
mail('my#email', 'OMG BUY THIS NOW!', $message);
$discard = file_get_contents($url);
print "Got stock, sent mail and SMS" . PHP_EOL;
}
}

Counting clicks with jQuery and displaying with Ajax

I'm hacking away at some code in order to have it register a click on an invisible div element, which expands an article to reveal it's excerpt while adding a +1 to the number of time's it's been clicked by anyone. Afterwards it updates an element with ajax with the number of clicks it's received.
At least, that's the goal.
The following code ends up breaking Wordpress and gives me the white screen of doom. This is taken from a simple click counter with an Ajax callback to update the number.
Where my problem lies is hacking away at this for it to register clicks on a different element.
Without wasting too much of anyones time, here's my question:
Wouldn't I just need to rename all post_like to post_reader? Someone's been telling my in person that it should work so check your server but that is ridiculous... it seems.
Note, below where you see post_reader, it had said post_like previously.
// post click to expand button
$timebeforerevote = 1;
add_action('wp_ajax_nopriv_post-like', 'post_reader');
add_action('wp_ajax_post-like', 'post_reader');
wp_localize_script('like_post', 'ajax_var', array(
'url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('ajax-nonce')
));
function post_like()
{
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
die ( 'Busted!');
if(isset($_POST['post_reader']))
{
$ip = $_SERVER['REMOTE_ADDR'];
$post_id = $_POST['post_id'];
$meta_IP = get_post_meta($post_id, "voted_IP");
$voted_IP = $meta_IP[0];
if(!is_array($voted_IP))
$voted_IP = array();
$meta_count = get_post_meta($post_id, "votes_count", true);
if(!hasAlreadyVoted($post_id))
{
$voted_IP[$ip] = time();
update_post_meta($post_id, "voted_IP", $voted_IP);
update_post_meta($post_id, "votes_count", ++$meta_count);
echo $meta_count;
}
else
echo "already";
}
exit;
}
function hasAlreadyVoted($post_id)
{
global $timebeforerevote;
$meta_IP = get_post_meta($post_id, "voted_IP");
$voted_IP = $meta_IP[0];
if(!is_array($voted_IP))
$voted_IP = array();
$ip = $_SERVER['REMOTE_ADDR'];
if(in_array($ip, array_keys($voted_IP)))
{
$time = $voted_IP[$ip];
$now = time();
if(round(($now - $time) / 60) > $timebeforerevote)
return false;
return true;
}
return false;
}
function getPostReadLink($post_id)
{
$themename = "toolbox";
$vote_count = get_post_meta($post_id, "votes_count", true);
$output = '<div class="post-read">';
if(hasAlreadyVoted($post_id))
$output .= ' <span title="'.__('I like this article', $themename).'" class="qtip like alreadyvoted"></span>';
else
$output .= '<a href="#" data-post_id="'.$post_id.'">
<span title="'.__('I like this article', $themename).'"class="qtip like"></span>
</a>';
$output .= '<span class="count">'.$vote_count.'</span></div>';
return $output;
}
The function called when clicked:
jQuery(".expand").click(function(e){
e.preventDefault();
readers = jQuery(this);
// Retrieve post ID from data attribute
post_id = readers.data("post_id");
// Ajax call
jQuery.ajax({
type: "post",
url: ajax_var.url,
data: "action=post-reader&nonce="+ajax_var.nonce+"&post_reader=&post_id="+post_id,
success: function(count){
// If vote successful
if(count != "already")
{
heart.addClass("readered");
heart.siblings(".count").text(count);
}
}
});
return false;
})
Invoking it within the appropriate div.
<?php echo getPostReadLink(get_the_ID());?>

Categories