Calling a Function When New Entry Was Written
  • Now, I wrote a function to build a numbered list of entries. But it’s a little slow (I have near 3000 entries), so I thought I should store the array in a file and rebuild it only when a new entry is written.
    Please, how can I hook my function into execution when a new entry is written and the Publish button is clicked?
  • I think you should use the publish_entry hook in a plugin and the entry_exists function if an entry exists.
  • Publish_entry not found by a text search in the code, but I found publish_post.
    publish_post
    Receives the post ID as a parameter. Executes when a post is saved and its status is set to "publish", regardless of its prior setting. NOTE: to add a hook to this action in 1.2, be sure to specify a priority between 0 and 9. The generic_ping hook is buggy and prevents any lesser priority hooks from working.

    So, should I write add_action('publish_post', 'my_function_name') into the plugin initialization?
    But I don’t understand the priority part. Priority of what? Where to specify it?
  • you can ignore the priority part. It's related to WordPress, there is no "generic_ping" hook in FlatPress
  • OK… thank you… let’s give it a try.
  • It works! :)
  • Ouch. No, it doesn’t work, sorry. Apparently it’s calling the function before the operation. I’ve hooked it both to publish_post and delete_post. My numbered list is built properly, but when creating a new entry, it is missing from the list, and when deleting an entry, the deleted entry is present. So it’s obvious it calls the plugin function at the wrong place, before modifying the files on the disk.
    Is there another hook to be called, please?
  • I believe and hope I found a better way. I call it from admin_head, so it executes upon every admin page calling, but first it checks if it is necessary to rebuild the database. If the last entry in the directory is not the same as the last entry stored in the database, or if the last year or month is not the same as in the database, then there is a change and we rebuild the database.
  • Every admin panel triggers an hook.
    Useful hooks for the entry editor are admin_entry_write_onsave and admin_entry_write_onsavecontinue that are called when you press the save and the "Save & continue" button.
  • of you need the id, then use

    register_action('publish_post', 'my_function', 10, 2); // 10 = priority , 2 = parameters for the function

    then make your function look like

    // $id contains the entry ID
    // $entry is an associative array with the entry contents
    function my_function($id, $entry) {

    }


In this Discussion