add_action() not defined error - wordpress plugin - php

i'm working on a simple plugin to count FB shares of post and
i want to create instance of the plugin class using a cron job.
the main part of the plugin is this:
class PostShareCount
{
public function __construct()
{
global $wpdb;
$this->db = $wpdb;
add_action('hourly_event', 'updateAllPostsShares');
add_shortcode('social-count', array($this, 'social_shares'));
}
public function updateAllPostsShares()
{
$this->db->query('CREATE TABLE IF NOT EXISTS wp_facebook_shares(
post_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
post_shares INT NOT NULL,
post_url VARCHAR(255) NOT NULL
)');
$posts = $this->db->get_results('SELECT ID, post_date, post_name FROM '.$this->db->posts.' WHERE ID < 3');
$fb_graph = 'http://graph.facebook.com/?id=';
$site = 'http://www.example.com/';
$posts_shares = [];
foreach ($posts as $post) {
$post_url = $site.$post->post_name;
$posts_shares[$post->ID] = array();
$posts_shares[$post->ID]['post_id'] = $post->ID;
$posts_shares[$post->ID]['post_url'] = $post_url;
$api_call = $fb_graph.$site.$post->post_name;
if (isset($this->get_response_body($api_call)->shares)) {
$posts_shares[$post->ID]['post_shares'] = $this->get_response_body($api_call)->shares;
} else {
$posts_shares[$post->ID]['post_shares'] = rand(80, 1200);
}
$this->db->replace('wp_facebook_shares', $posts_shares[$post->ID], array('%d', '%s', '%d'));
}
return $posts_shares;
}
}
and for a test to my cron i created this simple file:
<?php
require_once ('post-share-count.php');
$obj = new PostShareCount();
$obj->updateAllPostsShares();
?>
but whenever i try to run it i get this error:
Call to undefined function add_action() in ..
any idea what is causing this and how can i fix it? thx

There is simpler way, how to test your cronjobs:
Install WP Crontrol plugin.
Now, you can run your crons from administration.
Go to WordPress Administration: Tools -> Cron Events
If your plugin is working properly, you should see your scheduled hook name here.
Click on Run Now
Calling function directly from PHP file
If you need for some reason to call plugin functions directly from testing PHP file, don't forget to include wp-load.php.
Example (file is in same directory as wp-load.php):
<?php
include ('wp-load.php');
$obj = new PostShareCount();
$obj->updateAllPostsShares();
?>

Related

Uncaught Error: Call to a member function get() on null (easy photography plugin Wordpress)

I have a website with an old theme no longer supported and with a photographic plugin for the portfolio. The backend of the website is a blank page if the plugin is active, when the plugin is not active, all work fine (except for the homepage because use the plugin).
I just read all the similar question but I don't have so many knowledge on php for understand what is the problem and if there is a solution or I have to change the theme.
The problem is in line 286 and this is what I see:
private function get_queried_object_id() {
$id = (int) get_queried_object_id();
if ( ! $id ) {
$id = (int) $this->original_query->get( 'page_id' );
}
return $id;
}
Thanks in advance!and sorry if I miss something but is my first post here.
Recursion
if you want to call same function side of function (recursion).
$this is use to call recursion in side of class.
private function get_queried_object_id() {
$id = (int) $this->get_queried_object_id();
if ( ! $id ) {
$id = (int) $this->original_query->get( 'page_id' );
}
return $id;
}
I think this code help you!!

Custom Session Handler not working on PHP5.6 but does on PHP7

I am writing a Wordpress plugin that uses sessions and have written my own custom session handler to save session data in a custom table in the wordpress database.
I have the following defined in my main plugin file
add_action( 'init','start_session',1);
function start_session() {
if(!session_id())
{
session_set_save_handler('open_session', 'close_session', 'read_session', 'write_session', 'destroy_session', 'clean_session');
session_start();
}
}
My session functions look like this
function open_session()
{
return true;
}
function close_session()
{
return true;
}
function read_session($sessionid)
{
global $wpdb;
$session_table_name = $wpdb -> prefix . "sessions";
$query = $wpdb->prepare(
"SELECT data FROM $session_table_name
WHERE id = %s",
$sessionid);
$result = $wpdb -> get_var($query);
if ($result)
{
return $result;
} else
{
return '';
}
}
function write_session($sessionid,$data)
{
global $wpdb;
$session_table_name = $wpdb -> prefix . "sessions";
$rowsaffected = $wpdb->replace(
$session_table_name,
array(
'id' => $sessionid,
'data' => $data
),
array(
'%s',
'%s'
));
return true;
}
function destroy_session($sessionid)
{
global $wpdb;
$session_table_name = $wpdb -> prefix . "sessions";
$rowsaffected = $wpdb->delete($session_table_name,array('id' => $sessionid),array('%s'));
$_SESSION = array();
return true;
}
function clean_session($expire)
{
global $wpdb;
$session_table_name = $wpdb -> prefix . "sessions";
$wpdb->query(
$wpdb->prepare(
"DELETE FROM $session_table_name
WHERE DATE_ADD(last_accessed, INTERVAL %d SECOND) < NOW()",
$expire
)
);
return true;
}
I have some pages created by the plugin, which I then replace the content for by adding a filter to the_content and checking the page ID.
add_filter( 'the_content', 'content_filter' );
function content_filter ($content)
{
...
if ($post->ID == $page_id)
{
$content = '';
$content = basket_page($content);
}
return $content;
}
function basket_page($content)
{
$_SESSION['test'] = 'test';
$content = $_SESSION['anexistingvariable'];
return $content;
}
Now this all works fine when running PHP7, however in PHP5.6 if I set a SESSION variable within the function basket_page() I'm getting a fatal PHP error that says 'Call to a member function replace() on null...' on line 39 of the session functions. This is the line that calls the replace method on $wpdb and is because the global $wpdb is empty.
What's weird is I am using Ajax in this plugin too, and writing session variables within my ajax callback functions is working fine even in PHP5.6. I can also read session variables from basket_page(), it just seems to be writes that are causing the problem.
My hosting provider only goes up to PHP5.6, so I need to get this working in that version. Any insight anyone can give would be greatly appreciated!
I have fixed this now myself, I needed to add a session_write_close(); to the wp_footer action hook. Everything now works in both PHP5.6 and PHP7. Hooray!

Custom Function not working in Wordpress

I am currently developing a WordPress theme based on _s because the project is pretty different than average WordPress projects.
I started a few days ago and have done designing and now I am stuck in one place for hours.
I am trying to create a function to generate video id from Youtube link (a custom field does the job for 'video' post type).
The output is something like this: a0uGWc170Jc.
The code I used is below:
$id = get_post_meta($post->ID, 'video_option_youtube-link', true);
$id = explode('?v=', $id);
if (empty($id[1])) {
$id = explode('/v/', $id);
}
$id = explode("&", $id[1]);
$id = $id[0];
echo $id;
This code works well only when I add it inside of WP Query. I tried to make a function and inserted this function to theme's function.php file and tried to echo inside WP_Query but it returns php error. The function I made is:
function my_videoid() {
$id = get_post_meta($post->ID, 'video_option_youtube-link', true);
$id = explode('?v=', $id);
if (empty($id[1])) {
$id = explode('/v/', $id);
}
$id = explode("&", $id[1]);
$id = $id[0];
return $id;
}
(also tried to echo instead of return)
So, what am I doing wrong?
I think you have missed the global $post, $wpdb;
Please try it.

Call to Member function on Array

So I'm utilizing a for each to try to generate a menu dynamically from a MySQL database. Because there's more than one it will always return an array. I use multiple files to generate the menu.
I use a class to create the menu
class menu extends db{
public function LoadMainMenu() {
global $db;
$query = <<<SQL
SELECT id,name
FROM menu
WHERE enabled = :active
AND location = :mainmenu
SQL;
$resource = $db->sitedb->prepare( $query );
$resource->execute( array(
':active' => '1',
':mainmenu' => '1',
));
foreach($resource as $row){
echo '<li>'.$row['name'].'</li>';
}
}
$menu = new menu();
My next file is my base.class.php file
function LoadMainMenu() {
global $menu;
$menu->LoadMainMenu();
}
Then I have my index.php file within my theme settings where I have it called
<ul class='topmenu'>
<?php LoadMainMenu(); ?>
</ul>
It then gives me the error that it's a call to a member function on an array on base.class.php; If anymore code would help please let me know.
Not Really an end all cure all, but it works. I added it within the db.class.php and then just added global $db and then called $db->GetMainMenu() within the main index.php Template and it seems to have worked. Other than that I'm not sure what else to do.

Return unique id when use INSERT and SELECT in one moment

i am writing a program using mvc , and because the program i am writing is for admitting bank transactions, the resaults this program gives me is very important to me. and i need this to work without any logical errors and everything should workout with needed focus and giving me the exact thing i expect it to give. the thing that i want it to do for me is that some information will be sent out to the program with web service (like price, info, etc...) and then using a controller it checks the information and calls for the module, and sends the information to it. the it puts the module information to a stdclass and then using the PDO module it creates a transaction. and while the transaction is at work an insert command is sent for the database, and then we have a SELECT command and the program works well even after the insert command but while SELECT is at work , we have repetitive IDs which is the problem here:
my code:
//WSDL Creattor And Class
<?php
ini_set("soap.wsdl_cache_enabled", 1);
set_time_limit(300);
class wsdl extends Controller
{
public function index()
{
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'POST') {
$servidorSoap = new SoapServer('http://' . $_SERVER['SERVER_NAME'] . '/wsdl');
$servidorSoap->setClass('wsdl');
$servidorSoap->handle();
}
}
public function request($pin = null, $amount = 1, $callback = null, $orderid = null, $desc = null)
{
if(empty($callback))
return -10; // call back is empty.
if (empty($pin) && $result->pin != $pin)
return -1; // pin invalid
$this->Model("payment");
$au = $this->mod->Request($result, $amount, $callback, $orderid, $desc);
return $au;
}
}
payment model:
<?php
class Payment_mod extends Model
{
public function Request($gateway, $amount, $callback, $orderid, $description)
{
// using pdo module
$this->DB->CONNECT->beginTransaction();
try {
$trans = new stdClass;
$trans->gateway_id = $gateway->id;
$trans->au = str_replace('.', '_temp_', microtime(true));
$trans->price = $amount;
$trans->order_id = $orderid;
$trans->ip = $_SERVER['REMOTE_ADDR'];
$trans->time = time();
$trans->call_back = $callback;
$trans->description = $description;
$this->DB->Insert("trans", $trans); // insert into table trans …
$id = $this->DB->Fetch("trans", "`gateway_id` =" . $trans->gateway_id . " AND `price`=".$trans->price." AND time = " . $trans->time)->id; // select id from trans where …
$u = new stdClass;
$u->t_id = $id;
$this->DB->Insert("test",$u); // insert into test . it for test table for check result
$this->DB->CONNECT->commit();
} catch (Exception $e) {
$this->DB->CONNECT->rollBack();
return -9; // return unknow error.
}
return $id;
}
}
for understanding where the problem exactly is and how many times each ID repeats itself, i added a table and i got the amount of return data of SELECT and put it into the database. and when i hold the f5 key for some seconds it shows that each ID repeats nearly 9 times.
screenshot:
http://uploads.im/biWEn.jpg
note: this picture shows the amount of repeat of IDs.
where is the problem? i need this to repeat a specific ID for each call.
i did the exact thing in YII framework and i had no problem there and the progam worked exactly as i needed it to. i'd be glad if you help me.

Categories