From Wordpress plugin data is not getting inserted into custom table - wordpress

I have created a plugin to insert and fetch records. When I save record, record is getting saved from localhost but when I try it on online server it is not getting saved. Here is what I am trying to do.
function data_custom_ajax(){
global $wpdb;
$tbl = "tripplan";
$table_name=$wpdb->prefix . $tbl;
$custom_val = $_POST['text'];
$totaltime = $_COOKIE['totalduration'];
$totaldistance = $_COOKIE['totaldistance'];
$origin_address = $custom_val['originaddress'];
$end_address = $custom_val['destinationaddress'];
$waypoints = $custom_val['waypts'];
$wpdb->insert($table_name,
array(
'startpoint' => $origin_address,
'endpoint' => $end_address,
'waypoints' => json_encode($waypoints),
'totaldistance' => $totaldistance,
'totalduration' => $totaltime
),
array('%s','%s','%s','%f','%f')
);
echo "data has been saved";
}

function data_custom_ajax(){
global $wpdb;
$tbl = "tripplan";
$table_name=$wpdb->prefix . $tbl;
$custom_val = $_POST['text'];
$totaltime = $_COOKIE['totalduration'];
$totaldistance = $_COOKIE['totaldistance'];
$origin_address = $custom_val['originaddress'];
$end_address = $custom_val['destinationaddress'];
$waypoints = $custom_val['waypts'];
$data = array(
'startpoint' => $origin_address,
'endpoint' => $end_address,
'waypoints' => json_encode($waypoints),
'totaldistance' => $totaldistance,
'totalduration' => $totaltime
)
$lastInsertedId = $wpdb->insert($table_name,$data);
if($lastInsertedId != '')
{
echo "data has been saved";
}else{
$wpdb->print_error();
}
die();
}

After lot of reading and debugging I got to know the problem. My cookie was not getting saved correctly. Even though it was working on localhost, it was not working on website. After reading this [PHP cannot read javascript cookies and then after I modified my cookie while saving.
I was setting cookie like this and it was not working-
document.cookie="cookiename="+value
after setting this way it worked -
document.cookie = 'cookiename='+value+'; path=/'

Related

Show Content in a View if content Author has the same entity reference value as the logged in user

Title pretty much explains it. I have a user entity reference field (Node) called "Company". I want to show all content in a view where the author of that content has the same "company" value as the logged in user. I'm getting a little confused with the relationships to achieve this.
Ok, I was able to get this working based on Kien's answer. If using Entity Reference 7-x.1.5 Instead of 'field_company_nid', the correct column name was 'field_company_target_id'
/**
* Implements hook_views_query_alter().
*/
function your_module_views_query_alter(&$view, &$query) {
if ($view->name == 'article' && $view->current_display == 'page') { // replace 'article' and 'page' by your view's machine name and display's machine name
$author_join = new views_join();
$author_join->table = 'field_data_field_company'; // 'field_company' is machine name of the user's field referencing to Company
$author_join->field = 'entity_id';
$author_join->left_table = 'node';
$author_join->left_field = 'uid';
$author_join->type = 'left';
$view->query->add_relationship('author_company', $author_join, 'node');
$current_join = new views_join();
$current_join->table = 'field_data_field_company'; // 'field_company' is machine name of the user's field referencing to Company
$current_join->field = 'field_company_target_id';
$current_join->left_table = 'author_company';
$current_join->left_field = 'field_company_target_id';
$current_join->type = 'left';
$view->query->add_relationship('current_company', $current_join, 'author_company');
global $user;
$view->query->where[1]['conditions'][] = array(
'field' => 'current_company.entity_id',
'value' => $user->uid,
'operator' => '='
);
}
}
What you want seems a bit difficult to do by simply setting the view. You might need some custom code to alter the view query. Below is an approach using hook_views_query_alter():
Create a custom module (suppose it is your_module)
In file your_module.module, implement hook_views_query_alter():
/**
* Implements hook_views_query_alter().
*/
function your_module_views_query_alter(&$view, &$query) {
if ($view->name == 'article' && $view->current_display == 'page') { // replace 'article' and 'page' by your view's machine name and display's machine name
$author_join = new views_join();
$author_join->table = 'field_data_field_company'; // 'field_company' is machine name of the user's field referencing to Company
$author_join->field = 'entity_id';
$author_join->left_table = 'node';
$author_join->left_field = 'uid';
$author_join->type = 'left';
$view->query->add_relationship('author_company', $author_join, 'node');
$current_join = new views_join();
$current_join->table = 'field_data_field_company'; // 'field_company' is machine name of the user's field referencing to Company
$current_join->field = 'field_company_nid';
$current_join->left_table = 'author_company';
$current_join->left_field = 'field_company_nid';
$current_join->type = 'left';
$view->query->add_relationship('current_company', $current_join, 'author_company');
global $user;
$view->query->where[1]['conditions'][] = array(
'field' => 'current_company.entity_id',
'value' => $user->uid,
'operator' => '='
);
}
}
Enable the module you just created.

Cron Job In Custom Plugin Not Working In Wordpress

I have added this cronjob in my WordPress custom plugin but when I run the function manually it is working but through cronjob, it is not working. Here is my code! All the plugin files are loaded correctly not showing any error.
Can anybody help me to sort this out! I have tried a lot but still, it is not working.
<?php
if (!wp_next_scheduled('generateusedcarsfeed'))
{
wp_schedule_event(time() , '5mins', 'generateusedcarsfeed');
}
add_action('generateusedcarsfeed', 'generate_used_car_feed');
if (!wp_next_scheduled('generateusedcarsfeed'))
{
wp_schedule_event(time() , '5mins', 'generateusedcarsfeed');
}
add_action('generateusedcarsfeed', 'generate_used_car_feed');
// Getting all used cars with all data
function generate_used_car_feed(){
try{
// for opening the csv file
$file = fopen('all-cars-feed.csv', 'r');
fwrite($file, '');
$loop = new WP_Query($args);
chmod('all-cars-feed.csv', 0777);
// for creating array from csv file
$file="all-cars-feed.csv";
$csv= file_get_contents($file);
$array = array_map("str_getcsv", explode("\n", $csv));
$json_csv_arr = json_encode($array);
$my_array_csv = json_decode($json_csv_arr, true);
// for getting used car list from databse, only take publish used car
global $wpdb;
$query = "SELECT wp_postmeta.post_id, wp_postmeta.meta_value FROM wp_postmeta
INNER JOIN wp_posts ON wp_posts.id = wp_postmeta.post_id WHERE meta_key = 'car_registration_number'
AND post_status = 'publish'";
$result = $wpdb->get_results($query);
$json_reg_num = json_encode($result);
$my_array = json_decode($json_reg_num, true);
print_r($my_array);
foreach ($my_array as $value) {
$car_reg_array = $value['meta_value'];
$Post_id= $value['post_id'];
$isTrue=true;
$ch = fopen("all-cars-feed.csv", "r");
while($row = fgetcsv($ch)) {
if (in_array($car_reg_array, $row)) {
echo 'found</hr>';
$isTrue=false;
}
}
if($isTrue)
{
$wpdb->query(
'UPDATE '.$wpdb->prefix.'posts SET post_status = "trash"
WHERE ID = "'.$Post_id.'"');
}
}
//fclose($file);
}
catch(\Exception $e)
{
$txt = 'Message: ' . $e->getMessage();
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($fileLoger, $txt);
fclose($fileLoger);
}
}
I wonder if this 5mins interval really exists in your setup. Try adding this code to make sure this actually exists (if it does already, it won't break stuff):
function add_custom_cron_schedules($schedules){
if (!isset($schedules["5mins"])) {
$schedules["5min"] = array(
'interval' => 5*60,
'display' => __('Every 5 minutes'));
}
return $schedules;
}
add_filter('cron_schedules','add_custom_cron_schedules');
If you want to retrieve currently available schedules, you can also use wp_get_schedules() and check out if a certain key (like '5mins') exists.

google calendar watch notification getting nul

Hi have setup watch on google calendar
$channelID = "my-caledar-". date('His', time());
$channel->setId($channelID);
$channel->setType('web_hook');
$channel->setAddress('xxxxx');
and getting valid params after call this method
and when I create/delete any event on calendar , I am getting null on push notification url
if($_POST){
$msg = json_encode($_POST);
pg_query($pg_conn, "INSERT INTO postdata(post_data) values ('$msg')");
} else {
$result = pg_query($pg_conn, "SELECT * FROM postdata;");
}
$result getting empty filed
Notifiction not comes on url as a POST params , We can get it via $_SERVER variable like this
$msg = json_encode(array('HTTP_X_GOOG_CHANNEL_ID' => $_SERVER['HTTP_X_GOOG_CHANNEL_ID'],
'HTTP_X_GOOG_CHANNEL_EXPIRATION' => $_SERVER['HTTP_X_GOOG_CHANNEL_EXPIRATION'],
'HTTP_X_GOOG_RESOURCE_STATE' => $_SERVER['HTTP_X_GOOG_RESOURCE_STATE'],
'HTTP_X_GOOG_MESSAGE_NUMBER' => $_SERVER['HTTP_X_GOOG_MESSAGE_NUMBER'],
'HTTP_X_GOOG_RESOURCE_ID' => $_SERVER['HTTP_X_GOOG_RESOURCE_ID'],
'HTTP_X_GOOG_RESOURCE_URI' => $_SERVER['HTTP_X_GOOG_RESOURCE_URI']
));

Google API PHP Client - retrieve calendar list and events

The documentation for google calendar api is out of date, I am unable to get even a simple calendar list. Here is my code so far.
<?php
require_once "includes/partials/_header.php";
set_include_path(get_include_path() . '/google-api-php-client/src');
$client_id = 'xxxx.apps.googleusercontent.com';
$service_account = 'xxxx#developer.gserviceaccount.com';
$p12 = 'xxxx-privatekey.p12';
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
$client = new Google_Client();
$client->setApplicationName("Calendrier");
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
$key = file_get_contents($p12);
$client->setClientId($client_id);
$cred = new Google_Auth_AssertionCredentials(
$service_account,
array('https://www.googleapis.com/auth/calendar'),
$key);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$cal = new Google_Service_Calendar($client);
$events = $cal->calendarList->listCalendarList();
echo "<pre>";
print_r($events);
echo"</pre>";
while(true) {
foreach ($events->getItems() as $event) {
echo $event->getSummary();
print_r($event);
}
$pageToken = $events->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$events = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
?>
I got a lot of this code from different sites because the docs were out of date, now I'm totally stuck as I've been googling all day. Any insight?
All i get so far is a response like this with no "items"
Google_Service_Calendar_CalendarList Object
(
[etag] => "xxxxxxxxxxxx"
[itemsType:protected] => Google_Service_Calendar_CalendarListEntry
[itemsDataType:protected] => array
[kind] => calendar#calendarList
[nextPageToken] =>
[nextSyncToken] => 00001401741798955000
[collection_key:protected] => items
[modelData:protected] => Array
(
[items] => Array
(
)
)
[processed:protected] => Array
(
)
)
Allright, this is embarassing after all the time I spent on this. For some reason I never tried making the calendar public. I just assumed that with all the authorization steps that you could access the calendar from project account. Guess not.
Easy fix... just make the calendar public in its settings.
for events replace $cal->calendarlist part with
$cal->events->listEvents('calendarID', $optionalParams);
Note: I'm not even sure all the authorization/access token stuff in session is needed it seems the docs page of google cal still uses the old php client. I believe it should work using only the service account (setAssertionCredentials) the rest with the session im not sure.

I got a response from PayPal but I can't insert it in my database

I can receive a response from PayPal but I can't insert it in my database. I'm using WordPress. What's wrong with WordPress?
Jere's my code and this is working when I navigate to this page and this page where the PayPal IPN response will go but its not working I receive the PayPal response but it's not inserting in my database. It's only working when I go to my paypal_ipn module. What is wrong in PayPal and WordPress?
global $wpdb;
$txn_id = $_POST['txn_id'];
$payer_email = $_POST['payer_email'];
$prod_id = $_POST['custom'];
$tblname = "my_table";
$wpdb->insert($tblname,
array(
"id" => "$txn_id",
"email" => "$payer_email ",
"prodid" => "$prod_id"
),
array("%s", "%s", "%d")
);
Your passing strings to a decimal conversation with a space in it. I imagine that'd cause some issues. Also removed unneeded string concatination.
global $wpdb;
$txn_id = $_POST['txn_id'];
$payer_email = $_POST['payer_email'];
$prod_id = $_POST['custom'];
$tblname = "my_table";
$wpdb->insert($tblname,
array(
"id" => $txn_id,
"email" => $payer_email,
"prodid" => $prod_id
),
array("%s", "%s", "%d")
);

Resources