0

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?

3 Answers 3

1

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.

0

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. :-)

2
  • For me the part of how to execute the php file is unclear. Create a PHP function for fetching results and putting them into xml file and then execute the function?
    – jam
    Aug 7, 2020 at 10:17
  • Oh, no, you need to copy / paste the code into the functions.php of your theme. Preferrably you're working with a child theme so even after you update the parent theme, the code will stay there. For more on that, check the documentary - developer.wordpress.org/themes/advanced-topics/child-themes Alternatively, you can use a plugin that allows you to execute php code, but I'm not the biggest fan of that solution. Child themes are the way to go. :-) Aug 12, 2020 at 12:02
0

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"
            
            })
            
            
            
        }   
    
     } );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.