When i load page cron running good but we want auto run every 60 seconds in localhost.
Any one help me.
add_filter( 'cron_schedules', 'isa_add_every_three_minutes' );
function isa_add_every_three_minutes( $schedules ) {
$schedules['every_three_minutes'] = array(
'interval' => 60,
'display' => __( 'Every 1 Minutes', 'textdomain' )
);
return $schedules;
}
// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'isa_add_every_three_minutes' ) ) {
wp_schedule_event( time(), 'every_three_minutes', 'isa_add_every_three_minutes' );
}
// Hook into that action that'll fire every three minutes
add_action( 'isa_add_every_three_minutes', 'every_three_minutes_event_func' );
function every_three_minutes_event_func() {
$content = "some text here";
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/wordpressrootfolder/".time()."-myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
}
Wordpress CronJobs work a little different then traditional CronJobs. They will only run when WordPress is loaded, if the interval time has passed. As such, on localhost, you would have to find a way for the page to be loaded regularly.
This is easy if you have access to the server's crontab via SSH or cPanel.
You are able to set wp-cron.php to run in a normal cron task on your server and set this to run at an interval of your choosing. I personally don't let wp-cron.php run on many of my sites as once your cron tasks get bulky it can affect page load speed.
The cron task you want to run is wget -q -O - https://example.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1 where you want to replace example.com with your own domain.
For further details, I find this article quite useful https://kinsta.com/knowledgebase/disable-wp-cron/
Related
I create a plugin for send woocommerce data external system plugin i want create a cron run a one time like only run after plugin active success
this is i'm used cron code
add_action('wpse71941_cron', 'wpse71941_long_running');
function wpse71941_long_running($args)
{
// might need to call `set_time_limit` here
set_time_limit(0);
include 'customers.php';
include 'orders.php';
include 'products.php';
// return normal time limit
if($l = ini_get('max_execution_time'))
set_time_limit($l);
}
// schedule the event for right now
wp_schedule_single_event(
time(),
'wpse71941_cron',
array('args' => 'for', 'callback' => 'function')
);
any suggestions to send data in background process using corn or any?
i thought i would reach out to get some guidance on a little thing i am working on.
What i would like to do within Wordpress:
Call external API (with token header)
Get the results of the api and save it into a file in wpallimport's upload folder
I would assume i can just make a simple WP plugin and within the 'activate' hook for the plugin:
create a wp-cron (as i would like it to run every day) for the following:
$url = 'the-api-url';
$data = wp_remote_get( $url ,
array('headers' => array( 'Token' => 'tokenkey')
));
$jsonfile = $data['body'];
global $wp_filesystem;
if (empty($wp_filesystem)) {
require_once (ABSPATH . '/wp-admin/includes/file.php');
WP_Filesystem();
}
$file = '/wp-content/uploads/wpallimport/files/JSONFILE.JSON';
$wp_filesystem->put_contents($file, $jsonfile);
However i am not having success with the above (with the correct API url and token etc obviously)
Thanks in advance!
I am working on a Wordpress plugin embedding a Python script. I have uploaded the Python script to my server, and at first I got an error message on the web page, where my script is to be run, saying "permission denied" (I have redirected stderr to stdout to enable me to see the error messages). When I added execution permissions I instead get a "not found" message (done via Filezilla).
I can see the script is on the server in the correct folder, and it was apparently found earlier when the permissions were wrong. How can I get my plugin to find the Python file?
Here is the relevant PHP function in the plugin:
function embed_python( $attributes )
{
$data = shortcode_atts(
[
'file' => 'hello.py'
],
$attributes
);
$handle = popen( __DIR__ . '/' . $data['file'] . ' 2>&1', 'r' );
$read = '';
while ( ! feof( $handle ) )
{
$read .= fread( $handle, 2096 );
}
pclose( $handle );
return $read;
}
Turns out it was as simple as the server I was using (Loopia) needed the Python script in a certain folder to be able to find/run it, as well as several settings changed, see this Swedish page: https://support.loopia.se/wiki/python/.
I am trying to run a background script fired on a user action using wp_schedule_single_event, and although I have confirmed that the event is being scheduled and that wp_cron recognizes that the scheduled time has passed, it will not fire the event handler. To further complicate things, the code runs fine on my local WP install, but does nothing on my server.
To schedule the event, I am using:
if ( ! wp_next_scheduled( 'my_action_name' ) ) {
wp_schedule_single_event( time(), 'my_action_name' );
}
My handler action is defined as:
add_action('my_action_name', 'my_action_handler');
function my_action_handler () {
// do stuff
}
I have testing the wp core files and found that the following block (from wp-includes/cron.php:322) is where the script terminates:
var_dump('test1');
$cron_request = apply_filters( 'cron_request', array(
'url' => add_query_arg( 'doing_wp_cron', $doing_wp_cron, site_url( 'wp-cron.php' ) ),
'key' => $doing_wp_cron,
'args' => array(
'timeout' => 0.01,
'blocking' => false,
/** This filter is documented in wp-includes/class-wp-http-streams.php */
'sslverify' => apply_filters( 'https_local_ssl_verify', false )
)
), $doing_wp_cron );
var_dump('test2'); //exit here to test
wp_remote_post( $cron_request['url'], $cron_request['args'] );
On my local machine, the filter is applied, 'test2' is printed, and the script can continue to call wp_remote_post. On the server, however, the script terminates during the execution of apply_filter('cron_request'), printing 'test1' but not 'test2' and failing to reach wp_remost_post.
I have been unable to find the source for this filter to further debug. Wordpress.org says that the filter is defined within wp-includes/cron.php and that the one instance I have already cited is the only place it is ever applied, however, using Sublime multi-file search reveals that the string 'cron_request' appears only in the filter application I have cited.
I have read many post on wp_cron failing and have found no help other than non-descript 'Server configuration blocking wp_cron' answers. Any additional information on what type of server config or what else could be occuring here?
This action will trigger when someone visits your WordPress site, if the scheduled time has passed.
Maybe you can use
wp_schedule_event()
Instead of
wp_schedule_single_event()
How can I integrate Dropzonejs file uploader library in wordpress front end just like the built in one and have the uploaded one available in my media library?
Dropzonejs is a very extensive javascript library that provides a lot of options to handle media uploading.
To integrate dropzonejs with wordpress the process is pretty straight forward. Assume the following piece of code is where you want to appear your uploader.
<div id="media-uploader" class="dropzone"></div>
<input type="hidden" name="media-ids" value="">
Having a class dropzone will automatically attach the dropzone event with the element. That will stop us from overriding default parameters. So we would like to disable the auto discover feature of the library.
// Disabling autoDiscover, otherwise Dropzone will try to attach twice.
Dropzone.autoDiscover = false;
Now we will use jQuery to bind our configuration with the element.
jQuery("#media-uploader").dropzone({
url: dropParam.upload,
acceptedFiles: 'image/*',
success: function (file, response) {
file.previewElement.classList.add("dz-success");
file['attachment_id'] = response; // push the id for future reference
var ids = jQuery('#media-ids').val() + ',' + response;
jQuery('#media-ids').val(ids);
},
error: function (file, response) {
file.previewElement.classList.add("dz-error");
},
// update the following section is for removing image from library
addRemoveLinks: true,
removedfile: function(file) {
var attachment_id = file.attachment_id;
jQuery.ajax({
type: 'POST',
url: dropParam.delete,
data: {
media_id : attachment_id
}
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
});
In the code above what we have done is we attached dropzone with our element with some parameters-
url - location where we want to send our files to upload. I'll initialize the variable later.
acceptedFiles - since we are only interested in uploading images, we will limit the files to be attached only to images. You can find about more in the website of this library.
success - a callback that is fired when the file/image is uploaded successfully. It accepts two parameter the reference of the uploaded file itself and the response from the server. This is very important, here we stored the attachment id in our form. You can perform a validation here prior to store the id.
error - if the file failed to upload then you can perform any task here.
addRemoveLinks - add the remove file link below the preview panel, you can style it with your css.
removedfile - handles the operation while you click on the remove file link for an image in the preview panel. In this function we sent an ajax call to our server to remove the image from the library
Of course there are a lot of option available, but I found these are the most basic parameters I required to setup my drag-n-drop media uploader.
Now the most important thing is to decide about the file uploader url. You can have a custom file where you would want to process the operation. But I found another way.
From this question and the answer I found using admin-post.php file is pretty amazing.
Many people complained about this admin-post.php, so think sticking to the wp_ajax.php is the best option.
So I initialized the drophandler variable prior to my dropzone initialization as follows-
wp_enqueue_script('dropzone','path/to/dropzone', array('jquery'));
wp_enqueue_script('my-script','path/to/script',array('jquery','dropzone'));
$drop_param = array(
'upload'=>admin_url( 'admin-ajax.php?action=handle_dropped_media' ),
'delete'=>admin_url( 'admin-ajax.php?action=handle_deleted_media' ),
)
wp_localize_script('my-script','dropParam', $drop_param);
Now we are ready to send our images to the server. Here we will add some php code whether in the theme's function.php file or in our plugin file, but we need to be assured that it is loaded.
The following function will take care of the uploading the image and saving as an attachment in the library.
add_action( 'wp_ajax_handle_dropped_media', 'handle_dropped_media' );
// if you want to allow your visitors of your website to upload files, be cautious.
add_action( 'wp_ajax_nopriv_handle_dropped_media', 'handle_dropped_media' );
function handle_dropped_media() {
status_header(200);
$upload_dir = wp_upload_dir();
$upload_path = $upload_dir['path'] . DIRECTORY_SEPARATOR;
$num_files = count($_FILES['file']['tmp_name']);
$newupload = 0;
if ( !empty($_FILES) ) {
$files = $_FILES;
foreach($files as $file) {
$newfile = array (
'name' => $file['name'],
'type' => $file['type'],
'tmp_name' => $file['tmp_name'],
'error' => $file['error'],
'size' => $file['size']
);
$_FILES = array('upload'=>$newfile);
foreach($_FILES as $file => $array) {
$newupload = media_handle_upload( $file, 0 );
}
}
}
echo $newupload;
die();
}
The following action take care of the deletion of the media element. Second parameter of wp_delete_attachment() function allows us to decide whether we want to trash the image or completely delete it. I wanted to delete it completely so passed true.
add_action( 'wp_ajax_handle_deleted_media', 'handle_deleted_media' );
function handle_deleted_media(){
if( isset($_REQUEST['media_id']) ){
$post_id = absint( $_REQUEST['media_id'] );
$status = wp_delete_attachment($post_id, true);
if( $status )
echo json_encode(array('status' => 'OK'));
else
echo json_encode(array('status' => 'FAILED'));
}
die();
}
This will return the attachment_id in the response and we'll get it in the success function. In the media_handle_upload( $file, 0 ); I passed the reference of the file and a 0 because I didn't wanted to assign the media with any post yet (0 for no post, but if you want to assign then pass the post ID here. More reference in the codex.)
This is all for uploading media in wordpress.
Note: I haven't completed the removing uploaded file part. I'll complete this in a moment.
UPDATE
The post is updated. Now we can remove uploaded media elements from the uploader container. Thanks to this question and the answer I could figure out the actual process.
Those who are having problems getting this to work for non-admin users; please use admin-ajax.php instead of admin-post.php.
I had faced a strange issue that admin-post.php would work for non-admin users on my local server; but my live server refused to let non-admins upload files. php would echo entire page instead of the echoed value.
I replaced admin-post.php with admin-ajax.php and uploads work super cool.
I hope this helps.
The solution added to this post is incorrect unless I've misunderstood the question. Basically the solution won't work for anyone who isn't logged in as an admin. It took me 30 minutes to work it out plus the solution for removing images doesn't delete it from the media library.