Custom cron job doesn't scheduled in Wordpress - wordpress

I read several questions here and from Google search results, but I wasn't able to make it work. I have a function I want to run once every day which will fetch data from external source and store it on options page.
add_action( 'wp', 'update_stock_market' );
add_action( 'get_stock_market_daily_data', 'get_stock_market_data', 1, 1 );
function update_stock_market() {
if ( ! wp_next_scheduled( 'get_stock_market_daily_data' ) ) {
wp_schedule_event( time(), 'daily', 'get_stock_market_daily_data', array($company) );
}
}
function get_stock_market_data($company ) {
//do something here to get $data;
update_option( 'stock_market_data', $data);
}
However, no matter what happens, I cannot find the scheduled cron in the wp-options table under the option-name of cron

This code is working for me on a clean instance of WordPress, instead of looking directly in the database have you tried using the plugin WP Crontrol? Alternatively, with debug enabled, try adding a log entry to you update_stock_market function to check that the sechudled event is being called.
add_action( 'wp', 'update_stock_market' );
add_action( 'get_stock_market_daily_data', 'get_stock_market_data', 1, 1 );
function update_stock_market() {
error_log( 'triggered' );
if ( ! wp_next_scheduled( 'get_stock_market_daily_data' ) ) {
wp_schedule_event( time(), 'daily', 'get_stock_market_daily_data', array($company) );
}
}
function get_stock_market_data($company ) {
//do something here to get $data;
update_option( 'stock_market_data', $data);
}

Related

Setting up a cron job corectly within wordpress plugin

I am having difficulty doing this and have checked over previous questions however they do not seem to be working.
So far i have disabled the default wordpress cron by adding below to my wp-config.php:
define('DISABLE_WP_CRON', true);
Then i have attempted to schedule my task to run every 5 mins from within my plugins main php file:
function my_cron_schedules($schedules){
if(!isset($schedules["5min"])){
$schedules["5min"] = array(
'interval' => 5*60,
'display' => __('Once every 5 minutes'));
}
if(!isset($schedules["30min"])){
$schedules["30min"] = array(
'interval' => 30*60,
'display' => __('Once every 30 minutes'));
}
return $schedules;
}
add_filter('cron_schedules','my_cron_schedules');
function schedule_my_cron(){
wp_schedule_event(time(), '5min', 'fivemin_schedule_hook');
}
if(!wp_get_schedule('fivemin_schedule_hook')){
add_action('init', 'schedule_my_cron',10);
}
function fivemin_schedule_hook() {
get_feed();
}
So the above appears to be scheduling my event within database however have 100's of entries when checking cron schedule with:
<?php print_r(get_option('cron')); ?>
I have also made sure to update my crontab with below:
* * * * * wget -q -O - http://wordpress.com/wp-cron.php?doing_wp_cron
However my task does not appear to be running and am concerned about the amount of entries within database for this 5min job.
Each entry looks like below:
Array ( [1524308364] => Array ( [fivemin_schedule_hook] => Array ( [40cd750bba9870f18aada2478b24840a] => Array ( [schedule] => 5min [args] => Array ( ) [interval] => 300 ) ) )
I have tried debugging wp-cron.php by echoing out the $hook when it tries to fire and my hook is shown when i visit wp-cron.php directly. The actual function however just does not seem to fire.
Try this:
Replace this:
function schedule_my_cron(){
wp_schedule_event(time(), '5min', 'fivemin_schedule_hook');
}
if(!wp_get_schedule('fivemin_schedule_hook')){
add_action('init', 'schedule_my_cron',10);
}
..with this:
function schedule_my_cron(){
// Schedules the event if it's NOT already scheduled.
if ( ! wp_next_scheduled ( 'my_5min_event' ) ) {
wp_schedule_event( time(), '5min', 'my_5min_event' );
}
}
// Registers and schedules the my_5min_event cron event.
add_action( 'init', 'schedule_my_cron' );
// Runs fivemin_schedule_hook() function every 5 minutes.
add_action( 'my_5min_event', 'fivemin_schedule_hook' );
//add_action( 'my_5min_event', 'another_function_to_call' );
//add_action( 'my_5min_event', 'another_function_to_call2' );
But a more appropriate/preferred way is to add this in the activation function for your plugin:
wp_schedule_event( time(), '5min', 'my_5min_event' );
Example:
register_activation_hook( __FILE__, 'my_plugin_activation' );
function my_plugin_activation() {
if ( ! wp_next_scheduled ( 'my_5min_event' ) ) {
wp_schedule_event( time(), '5min', 'my_5min_event' );
}
}
..which would be used in place of the following:
function schedule_my_cron(){
// Schedules the event if it's NOT already scheduled.
if ( ! wp_next_scheduled ( 'my_5min_event' ) ) {
wp_schedule_event( time(), '5min', 'my_5min_event' );
}
}
// Registers and schedules the my_5min_event cron event.
add_action( 'init', 'schedule_my_cron' );
And add this somewhere in the deactivation function for your plugin:
wp_clear_scheduled_hook( 'my_5min_event' );
Example:
register_deactivation_hook( __FILE__, 'my_plugin_deactivation' );
function my_plugin_deactivation() {
wp_clear_scheduled_hook( 'my_5min_event' );
}
See https://codex.wordpress.org/Function_Reference/wp_schedule_event#Examples for more details.

Woocommerce hook that fires after a product is updated via REST API

I am using this hook to run some code after the product is updated:
add_action( 'updated_post_meta', 'attach_variation_images_on_product_save', 10, 4 );
function attach_variation_images_on_product_save( $meta_id, $post_id, $meta_key, $meta_value ) {
if ( $meta_key == '_edit_lock' ) {
if ( get_post_type( $post_id ) == 'product' ) {
//do something
}
}
}
This is working as expected, the function is executed after the product is updated. I want to run the same function when a product is getting updated via the REST API. I hooked my function to woocommerce_rest_insert_product_object like this but it did not work:
add_action( 'woocommerce_rest_insert_product_object', 'attach_variation_images_on_product_update_via_rest', 10, 3 );
function attach_variation_images_on_product_update_via_rest( $post, $request, $true ) {
if ( get_post_type( $post ) == 'product' ) {
$product = wc_get_product( $post );
//do something
}
}
Am I not using the right hook? Is there another hook I can use?
EDIT 1: It seems that my code was not running because get_post_type($post) is type of post and not product. I am trying to attach an image to variations using add_post_meta($variation_id, '_thumbnail_id', $image_id); inside a loop. It seems the function attach_variation_images_on_product_update_via_rest( $post, $request, $true ) is executed till the end but it does not attach the image to the variations.
I ended up using this hook add_action( 'woocommerce_update_product', 'my_callback_function', 10, 1 ); that executes the callback function when you updating products from Woocommerce back-end as well from the REST API.

Automatically Deactivate Plugin After a Check

I'm trying to get my Wordpress plugin to deactivate automatically after a simple check. It seems to be calling the admin_notices method just fine, but the deactivate_plugin() method does not do anything. This is in the class constructor:
// End if the theme isn't compatible
if ( FALSE == $this->themesupport['support'] ) { // This test works fine
add_action( 'admin_init', array( &$this, 'deactivate_plugin' ) ); // Plugin doesn't deactivate
add_action( 'admin_notices', array( &$this, 'admin_notices' ) ); // I get notices
if ( isset( $_GET['activate'] ) )
unset( $_GET['activate'] );
return;
} // if()
The method is pretty straightforward:
public function deactivate_plugin() {
deactivate_plugins( plugin_basename( __FILE__ ) );
} // deactivate_plugin()
Putting an echo in that deactivate_plugin method and it gets called. I've also tried including the plugins.php file from core with no change.
The following works:
<?php
/**
* Plugin Name: (SO) Self-deactivate with $_GET['my_deactivate']
*/
add_action( 'admin_init', function()
{
if( isset( $_GET['my_deactivate'] ) )
{
deactivate_plugins( plugin_basename( __FILE__ ), true );
$url = admin_url( 'plugins.php?deactivate=true' );
header( "Location: $url" );
die();
}
});
After activating, enter any admin URL adding ?my_deactivate, e.g.:
http://example.com/wp-admin/users.php?my_deactivate
Reference:
Function deactivate_plugins does not exist
I was calling deactivate_plugins() from within a class, rather than the plugin file itself, which of course returned the wrong location for FILE

wordpress dashboard display custom error message upon custom condition

In edit-user.php of wordpress dashboard before updating meta information I am checking one condition and upon failure of that condition I want to display a error message. I tried to echo div with updated class and also tried WP admin_notices hook but no luck
add_action( 'personal_options_update', 'save_extra_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_profile_fields' );
function save_extra_profile_fields( $user_id ) {
global $wpdb;
if(CONDITION TRUE) {
update_usermeta( ........... );
}
else {
WANT TO DISPLAY ERROR MESSAGE
}
}
There is a hook for validating user extra fields. This hook will call before updating user details.
You can display error message like this:-
add_action( 'user_profile_update_errors', 'validate_extra' );
function validate_extra(&$errors, $update = null, &$user = null)
{
if (!$_POST['YOUR_FIELD'])
{
$errors->add('YOUR_FIELD', "<strong>ERROR</strong>: YOUR ERROR MESSAGE.");
}
}
add_action( 'personal_options_update', 'save_extra_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_profile_fields' );
function save_extra_profile_fields( $user_id )
{
global $wpdb;
update_usermeta( ........... );
}

wordpress set post_status as "draft" in 'save_post' action

I have a custom function that works with my custom post type. While porocessing save_post action:
add_action( 'save_post', 'my_custom_function' );
I would like to set post status as draft (in case of a problem with getting custom data from outside api).
In my my_custom_function function I have this little block:
if ($error == true) {
$override_post = array();
$override_post['ID'] = $post_id;
$override_post['post_status'] = 'draft';
wp_update_post( $override_post );
}
but it seems, that after save_post is being processed, then post_status is being set again.
Anybody have an idea, where should I hook into, so while saving post data I can modify its post_status, post_date and some other post data informations so they are not being overriten?
You should hook it to wp_insert_post_data. Then you could use a function like this to set your post status to draft:
add_filter( 'wp_insert_post_data', 'set_post_to_draft', 99, 2 );
function set_post_to_draft( $data, $postarr ) {
if ( your_condition ) {
$data['post_status'] = 'draft';
}
return $data;
}
I had to make a post type with only one post_status option, and it seem to fit your needs too, as it is works exactly with the save_post hook.
add_action( 'save_post', 'my_function' );
function my_function( $post_id ){
if ( ! wp_is_post_revision( $post_id ) ){
// avoid endless circle
remove_action('save_post', 'my_function');
// update the data before saving
wp_update_post( wp_slash([
'ID' => $_POST['ID'],
'post_status' => 'draft'
]));
// restore the saving hook
add_action('save_post', 'my_function');
}
}
The original solution found here:
https://wp-kama.ru/function/wp_update_post

Resources