cronjob for wordpress runs infinitely - wordpress

I have this code:
// set up cron job
wp_schedule_event(time(), 'hourly', 'test_event');
add_action('test_event', 'testFunction');
function testFunction()
{
$query = new WP_Query(array(
'post_type' => 'tour',
'post_status' => 'publish'
));
while ($query->have_posts()) {
$query->the_post();
$post_id = get_the_ID();
echo $post_id . "a<br>";
}
}
And of course, I disabled the Wp cronjob define('DISABLE_WP_CRON', true);.
When I go to http://my-domain/wp/wp-cron.php?doing_wp_cron in the browser (the domain is local, so can't set the real cronjob in the crontab yet with wget), it outputs post IDs multiple times, like this:
1
2
3
1
2
3
Sometimes even more, and sometimes it causes memory error. It seems to me like the cronjob is running infinitely. I can't figure out why.
Not a WP pro, so any suggestion is appreciated!
Thanks.

wp_schedule_event registers a cron task with your WordPress installation.
So, what you're doing here, is every time you're running your cron you are telling WordPress to run your function an additional time to the last time.
If you've visited the cron page 10 times then your cron will be running 10 times per visit.
You can unschedule the event using wp_unschedule_event if you need to.

When you call wp_schedule_event, a new event is registered. You should only call that function once (events persist through multiple visits, globally), the documentation recommends scheduling after plugin activation.
"To schedule an hourly event in a plugin, call wp_schedule_event on activation (otherwise you will end up with a lot of scheduled events!)"
You'll want to use wp_unschedule_event to clear your current bindings, then call the function once. If it is part of your theme, use them activation and toggle your theme to something else and back.

Related

Scheduled Actions Disable Logs By Group - Wordpress 6.0.3

I know that to reduce the days and eliminate the records, this is done
function wca_reduce_action_scheduler_retention() {
return WEEK_IN_SECONDS;
}
add_filter( 'action_scheduler_retention_period', 'wca_reduce_action_scheduler_retention' );
However what I need is to discard the logs of the group rocket-preload
To be more precise it skips saving logs for that group. Since I don't need them.
This is possible?
This on the Wordpress Scheduled Actions page (/wp-admin/tools.php?page=action-scheduler)

Check if the specific cron-job is active

I'm wondering whether if I can check a specific cron job is working or not. For example, I would like to send myself an email if the wpse_twicedaily_cron and wpse_oncedaily_cron is not active/ running in the WP.
I can setup the email, but I just need to figure out how to detect if certain cron job is active. I will need to check if the cron jobs are working every 5 minutes.
Thank you!
To view all scheduled tasks, you can use the code below that utilizes _get_cron_array(). Sample code is taken from here
function bl_print_tasks() {
echo '<pre>'; print_r( _get_cron_array() ); echo '</pre>';
}
bl_print_tasks();
You can then create your hook and function and add it as a cron to wordpress.
add_action( 'wpb_custom_cron', 'wpb_custom_cron_func' );
function wpb_custom_cron_func() {
// Check whatever here and then email
wp_mail( 'you#yourdomain.com', 'Cron Alert Email', 'Automatic scheduled email from WordPress to test certain cronjobs');
}
To add your own cron or simply see / trigger other crons, you can use WP Control plugin. Here is how to add your cron from Tools » Cron Events
Screenshot and sample mail code taken from here

Resolve woocommerce hook woocommerce_email_footer function causing recursion

I'm using Woocommerce hook woocommerce_email_footer() and inside my function, I need to call $email->get_content() which causes recursion and PHP memory error and WordPress exits with system error
Tried to remove the hook before calling the $email->get_content() and adding the hook back right after this call. However, this may not be a foolproof solution since some other session which hits exactly at the time when my function has removed the action might totally miss the hook custom action
I've written the following code in functions.php of my theme to capture the mail contents (mail body) into a local file just before it is being sent whenever a new order is received
//
// Capture the contents of the Emails sent and save into local files
// These Local files are used for further messaging through different channels
//
function Save_Email_Contents_into_Local_File ( $email ) {
if ( $email->id == 'customer_processing_order' ) {
// Remove the action temporarily so as not to cause Recursion while we refer to $email functions
remove_action( 'woocommerce_email_footer', 'Save_Email_Contents_into_Local_File', 20, 1 );
$TargetFilename = '/home/users/....../Sent_Mail.html' ;
$html_message = $email->get_content();
$formatted_message = $email->style_inline($html_message);
file_put_contents($TargetFilename, $formatted_message);
}
// Put the action back to original state
add_action( 'woocommerce_email_footer', 'Save_Email_Contents_into_Local_File', 20, 1 );
};
// add the action
add_action( 'woocommerce_email_footer', 'Save_Email_Contents_into_Local_File', 20, 1 );
Please note in the above function, I'm referring the $email->get_content() public function.
If I do not do the remove_action( 'woocommerce_email_footer', 'Save_Email_Contents_into_Local_File', 20, 1 ); this function becomes recursive and fails with a PHP memory error.
Although this is a workable solution, Removing the action can potentially cause another instance of the customer_processing_order from another user to miss the action and not come to this function if that session hits exactly at the time when this current session has removed the action and before adding the action again.
I'm sure I'm not doing it right! Is there any better way to accomplish what I need - basically I need the exact formatted mail content to be stored in a local file whenever the order is received. Similarly, I will need local file stored for Order completion and order hold, etc. but at later point of time.
Want to achieve storing formatted email into a local file a) without causing recursion / PHP memory errors b) without having to miss some instances of the execution missing the custom code attached to the hook.

Wordpress schedule daily cron run only after first visit?

function cronstarter_activation() {
if( !wp_next_scheduled( 'mycronjob' ) ) {
wp_schedule_event( strtotime( '00:02:00' ), 'daily', 'mycronjob' );
}
}
add_action('wp', 'cronstarter_activation');
function my_repeat_function() {
//My code the same information to database
}
add_action ('mycronjob', 'my_repeat_function');
Everything works great.
My problem is that I have php code in sidebar to recieve the storaged information from the database that saved from cron_job,
and the first time that a visitor visits the site in the new day after the 00:02:00 the recieved information is the previous day information.
I think that the first visitor of day, first see the sidebar's result, which is the previous day information, and after activate the cronjob.
Is that true? How can I run the cronjob without needed the first visitor?
Yes WP Cron have big caveat is that it requires someone to visit the site in order to run. For example, if you schedule your job to run at 2AM but no one visits at 2AM, it won’t run at 2AM. It will run when someone visits the site after 2AM.
More info Official : https://codex.wordpress.org/Function_Reference/wp_schedule_event
More info public blog:
http://brianshim.com/webtricks/cron-job-wordpress/
For more control on cron job use schedule at system level:
Use PHP to create, edit and delete crontab jobs?
Setup/configuration will differ based on your server & hosting type.

Change user_nicename after registration

Say we have a a mother site. Then we have a user registration form on a 3rd party site and a user register system which is processing the whole registration process and in the end will send the user login details in the mother site's database (mysql insertion, again no user_register function). Since there are 2 completely different browser sessions, no actions can be hooked on the mother site during or after registration.
So, let's say we will have stored the users in the database with logins like aaa#bbb.cc (weird, yes) and having a name and the user_nicename appearing like aaa#bbb.cc
Question:
What is the best aproach, wp action/function to be hooked, that once the user is stored in the mother site's database, to write a function to change the user nicename in something like aaa-bbb Automatically of course.
Is there a function/hook suggested for such cases?
The below code didn't helped me, since as I told above, I think the user_register action can't be triggered when a 3rd party site registration is processed:
add_action( 'user_register', 'myplugin_registration_save' );
function myplugin_registration_save( $user_id ) {
$info = get_userdata( $user_id );
$args = array(
'ID' => $user_id,
'user_nicename' => $info->first_name . '-' . $info->last_name
);
wp_update_user( $args );
}
The question as worded is really hard to understand. If I'm reading it correctly, you have two websites. Site One is where people are registering. When they complete registration on Site One something runs that creates a new user in the Site Two database by doing a direct sql insert, not by using any native WP functions.
If that's the case, why don't you simply manipulate the user login before you insert it into the Site Two db? You can't do it via a WordPress hook b/c WordPress is never being called. Hooks are just callback functions sprinkled through the WordPress code. When something happens, like a new user is created, there is a hook that you can assign a function to -- something "Send me an email." If WordPress doesn't handle the new user creation then the hook never gets called.
If you have to do the manipulation after the data has been inserted you'll probably need to look at using a cron job that runs every X amount of time looking for new records in the wp_users table.

Resources