Refresh page after WordPress form submission, without ‘Confirm Resubmission’ alert

I have my form doing what it needs to (add/remove tag from post depending on whether it’s there or not). But – once I submit the form the page doesn’t update as intended, the $buttonTitle doesn’t update unless I re-load the page in another tab. If I try to refresh I get the message ‘Confirm Form Resubmission’, I’m a complete noob to php forms, but here’s my code…

<?php

$idTag = $current_user->ID;
$spitOutTag = (string)$idTag;

if (has_tag( $spitOutTag, $post )) {
    $buttonTitle = 'REMOVE TAG';
} else {
    $buttonTitle = 'ADD TAG';
} ?>

<form name="primaryTagForm" action="<?php echo the_permalink() ?>" id="primaryTagForm" method="POST" enctype="multipart/form-data" >
    <fieldset>
        <input type="hidden" name="newtags" id="newtags" value="<?php echo $current_user->ID; ?>" />
        <?php wp_nonce_field( 'post_nonce', 'post_nonce_field' ); ?>
        <button id="btn-join" class="btn btn-lg" type="submit"><?php echo $buttonTitle ?></button>
    </fieldset>
</form>

<?php if ( is_user_logged_in() && isset( $_POST['newtags'] ) ) {

    if (has_tag( $spitOutTag, $post )) { 

        // Get all the tags as an array of names
        $tags = wp_get_post_tags( get_the_ID(), array('fields' => 'names') );

        // Remove the tag from the array
        $index = array_search( $idTag, $tags );
        unset( $tags[$index] );

        // Reset the tags
        wp_set_post_tags( get_the_ID(), $tags );

    } else {

        wp_set_post_tags(get_the_ID(), sanitize_text_field($_POST['newtags']), true );

    }   

} ?>

Related posts

1 comment

  1. The problem is that you’re assigning the tags after checking them, that’s why the button doesn’t change, you’ll need to arrange your code like this:

    First, checking if some tags were sent and apply it to the post:

    <?php if ( is_user_logged_in() && isset( $_POST['newtags'] ) ) {
      ............
    } ?>
    

    Then checking the Button:

    if (has_tag( $spitOutTag, $post )) {
        $buttonTitle = 'REMOVE TAG';
    } else {
        $buttonTitle = 'ADD TAG';
    } ?>
    

    Finally printing the HTML:

    <form name="primaryTagForm" action="<?php echo the_permalink() ?>"
       ....
    </form>
    

Comments are closed.