【问题标题】:Refresh page after WordPress form submission, without 'Confirm Resubmission' alertWordPress 表单提交后刷新页面,没有“确认重新提交”警报
【发布时间】:2015-11-16 23:50:01
【问题描述】:

我的表单正在做它需要做的事情(从帖子中添加/删除标签,具体取决于它是否存在)。但是 - 一旦我提交表单,页面不会按预期更新,除非我在另一个选项卡中重新加载页面,否则 $buttonTitle 不会更新。如果我尝试刷新,我会收到“确认表单重新提交”消息,我完全是 php 表单的菜鸟,但这是我的代码...

<?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 );

    }   

} ?>

【问题讨论】:

  • 您需要渲染一个新页面。您无法删除该警告,因为页面是从发送的变量生成的,因此为了刷新它,浏览器需要重新发送这些变量以再次呈现页面
  • 好的,谢谢,你知道我在哪里可以获得更多信息吗?

标签: php wordpress forms


【解决方案1】:

问题是您在检查标签后分配标签,这就是按钮不改变的原因,您需要像这样安排代码:

首先,检查是否发送了一些标签并将其应用于帖子:

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

然后检查按钮:

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

最终打印 HTML:

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

【讨论】:

  • 啊太好了,这解决了更新问题是的。我仍然收到“确认重新提交表单”消息,但我猜这是一个单独的问题。
  • 是的,如果您手动刷新,这种情况总是会发生。这就是网络的工作方式。如果有效,请选择此作为答案;)
猜你喜欢
  • 2016-05-14
  • 2014-05-21
  • 1970-01-01
  • 2012-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多