I have created a php script (generate.php) which is querying posts on set criteria and then writing result in custom xml file. I would like to execute the generate.php everytime the post Save/Update button is pressed. Do you have any clue on how to do this? May be with cron jobs every X minutes would be better?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I believe you should look into status transitions: https://developer.wordpress.org/reference/hooks/transition_post_status/
There are a couple of examples below the explanation on top of the page. Here’s also some example code of mine:
add_action( 'transition_post_status', 'nxt_create_news', 10, 3 );
// Automatically create a news when a wiki post has been published
function nxt_create_news($new_status, $old_status, $nxt_wiki_post) {
if('publish' === $new_status && 'publish' !== $old_status && $nxt_wiki_post->post_type === 'wiki') {
... do something here
}
In your case, the old_status should be ‘publish’ and the new status as well. Make sure to find a way to prevent an endless loop, but I believe that the examples on the WP documentary should prove useful. 🙂
Method 2
Seems like you want the save_post hook which is called when a new post is saved or existing post is updated.
Make sure your PHP file is loaded (e.g. require or include) and has a function you can call, and then cause that function to be run when a post is saved or updated with:
add_action('save_post', 'your_function_name', 10, 1);
Note the last parameter there is the number of parameters you want from the hook, see the docs page.
Method 3
At the end, I solved with jQuery and ajax
jQuery( '.post-type-property #post' ).submit( function( e ) {
if(!(checkMetaFields() && checkCategories())){ //some validation functions
return false;
}else{
jQuery.ajax({
url:"https://demo.site.com/XML/6098123798/gen.php",
type:"post"
})
}
} );
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0