简体   繁体   中英

Wordpress - Add a tag to an existing post, front-end

I'm been researching this all day and haven't found an elegant solution, what I'm trying to do is tag a user id onto an existing post on the front end (Using Wordpress). The process will be ad follows...

  • The post has a text input and submit button (front end).
  • The user (registered), enters a tag in the text field and submits
  • The tag is written to the post, (ideally without a refresh using ajax but not essential.)

It seems like it should be straight forward but I can't find any related info, thanks in advance.

EDIT: Working, final Code looks like this, thanks!

<form name="primaryTagForm" id="primaryTagForm" method="POST" enctype="multipart/form-data" >
    <fieldset>
        <input type="text" name="newtags" id="newtags" value="true" />
        <?php wp_nonce_field( 'post_nonce', 'post_nonce_field' ); ?>
        <button class="button" type="submit"><?php _e('Tag Product', 'framework') ?></button>
    </fieldset>
</form>

<?php 
    // If a user is logged in, and a form has been submitted with new tags
    if ( is_user_logged_in() && isset( $_POST['newtags'] ) ) {
    // Add the tags
    wp_set_post_tags(get_the_ID(), sanitize_text_field($_POST['newtags']), true    );
} ?>

Your question is way too broad and would require someone to build an entire form (including processing logic) for you. That's not what StackOverflow is for; so I'll answer the simple question that exists in your post title:

How to add a tag to an existing post, from the front-end

Answer:

Use wp_set_post_tags() to add tags to a post, when the form is processed. For example, if your form input is named newtags , you could use something like:

// If a user is logged in, and a form has been submitted with new tags
if ( is_user_logged_in() && isset( $_POST['newtags'] ) ) {
    // Add the tags
    wp_set_post_tags(get_the_ID(), sanitize_text_field($_POST['newtags']), true );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM