在Wordpress前端发帖上使用现有标签

问题描述 投票:0回答:1

我有一个前端帖子,允许用户更新他们的帖子。目前我正在使用它来允许输入新标签:

这是我的 HTML 表单:

  <form id="featured_upload" method="post" action="#" enctype="multipart/form-data">
    <input type="file" name="new_image_upload" id="new_image_upload"  multiple="false" />
    <input type="text" name="newtags" id="newtags" value="" />
    <input type="hidden" name="post_id" id="post_id" value="" />
    <?php wp_nonce_field( 'new_image_upload', 'new_image_upload_nonce' ); ?>
    <input id="submit_new_image_upload" name="submit_new_image_upload" type="submit" value="Upload" />
</form>  

这是代码的一部分:

    // If the form has been submitted with new tags
    if ( isset( $_POST['newtags'] ) ) {
    // get existing tags
    $post_tags = get_the_tags();
    // concatenates both existing and new tags
    $concatenated_tags = array($post_tags, sanitize_text_field($_POST['newtags']));
   // Add all the tags to the post
    wp_set_post_tags(get_the_ID(), $concatenated_tags , true    );
    }

这样做的问题是在我的数据库上创建了许多不必要的标签,我需要我的用户看到我的数据库中已经存在的标签的建议。

所以,我需要

<input type="text" name="newtags" id="newtags" value="" />
使它们成为现有的标签建议,就像wordpress在帖子编辑后端所做的那样。请参阅下图以在我的前端表单上检查所需的结果:

php wordpress frontend tags
1个回答
0
投票

我建议在前端使用 Select2 javascript 库,特别是自动标记化标记功能。请参阅此处:https://select2.org/tagging#automatic-tokenization-into-tags

将 Select2 文件排入前端后,您可以执行以下操作...

您的前端表单: 请注意,我添加了

$has_tag
变量,它将自动选择当前帖子的所有已保存标签。参见
selected()

<?php $post_id = get_the_ID(); ?>
<form id="featured_upload" method="post" action="#" enctype="multipart/form-data">
    ...

    <input type="hidden" name="post_id" value="<?= $post_id; ?>">

    <select name="tags" multiple id="frontend-tagger">
        <?php if ( $tags = get_terms( [ 'taxonomy' => 'post_tag', 'hide_empty' => false ] ) ): ?>
            <?php foreach ( $tags as $tag ): ?>
                <?php $has_tag = selected( has_tag( $tag->term_id, $post_id ), true, false ); ?>
                <option value="<?= $tag->name; ?>"<?= $has_tag; ?>><?= $tag->name; ?></option>
            <?php endforeach ?>
        <?php endif ?>
    </select>

    ...
</form>

JS启动select2字段:

$( '#frontend-tagger' ).select2( {
    tags: true,
    tokenSeparators: [ ',' ]
} );

保存过程:请注意,因为我们现在将已保存的标签包含在有效负载中,所以我们不需要连接现有标签。我们现在可以将

wp_set_post_tags
的第三个参数更改为
false
,因为我们不需要附加标签。

$post_id = !empty( $_POST[ 'post_id' ] ) : (int)$_POST[ 'post_id' ] : null;

if ( isset( $_POST[ 'tags' ] ) ) {

    // Sanitize array values
    $tags = array_map( 'sanitize_text_field', $_POST[ 'tags' ] );

    wp_set_post_tags( $post_id, $tags , false );
}

上面的代码尚未经过测试,只是您工作的起点。

希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.