0

I was wondering how can I insert a DB row (not related to WordPress tables) only when I update or add a new post. Right now I have this...

add_action( 'save_post', 'insertIntoDBatPost');
function insertIntoDBatPost()
{
  global $wpdb;
  global $post;

  $wpdb->show_errors();

  if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
    return;
  if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
    return;

  $ios_version_changelog = isset($_POST['ios_version_changelog']) ?    $_POST['ios_version_changelog'] : '';
$ios_version_release_date = isset($_POST['ios_version_release_date']) ? $_POST['ios_version_release_date'] : '';
$ios_version_download_link = isset($_POST['ios_version_download_link']) ? $_POST['ios_version_download_link'] : '';
$ios_version_log = isset($_POST['ios_version_log']) ? $_POST['ios_version_log'] : '';

if($ios_version_log != '')
{
    $wpdb->insert(
        'posts_details',
        array(
            'post_id' => $post->ID,
            'post_changelog' => $ios_version_changelog,
            'post_release_date' => $ios_version_release_date,
            'post_download_link' => $ios_version_download_link,
            'post_ios_version' => $ios_version_log
        )
    );
}
}

and WordPress auto-saves from time to time, which inserts a lot of rows in my database.

Any ideas?

0

Add the following right at the top of your function code, it will exit the function if it's doing an auto save:

if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;

You may find you also need to use the following aswell:

if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
return;
  • Not really working. – Iulian Bozeanu Jan 15 '14 at 22:45
  • Could you elaborate more? The above will kick you out of the function if wordpress press is currently autosaving – MichaelJames Jan 15 '14 at 22:47
  • I added both codes and started a new post. After 2-3 minutes, i already had 2 entries in the db. – Iulian Bozeanu Jan 15 '14 at 22:49
  • Updated. Please note that I used this as a new post. Maybe there is some special condition for drafts? – Iulian Bozeanu Jan 15 '14 at 22:52
  • Place it right at the top of the script after the opening { and can you confirm you don't have any other post edit screens open in other tabs and that the new rows in the DB match the id of the post your editing on. – MichaelJames Jan 15 '14 at 22:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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