Edit categories and tags in the front end of Wordpress

Asked

Viewed 466 times

4

I’m trying to put together a page for editing categories, tags and custom taxonomies via front end. However, now I cannot find the correct function to submit the update of the fields.

The code so far:

<?php

/*Template Name: Page Template Editar Cetegoria*/
get_header(); ?>

<section class="conteudo-geral">
<section class="conteudo" style="width: 990px" role="main">

<?php
$pid = $_REQUEST [ 'pid' ];
$taxonomia = get_term_by('id', $pid, 'category', 'ARRAY_A');

$nome_taxonomia = $taxonomia->name;
$descrição_taxonomia = $taxonomia->description;
?>      

<form action="" method="post">

<tr class="form-field form-required">
<th scope="row" valign="top"><label for="name">Nome</label></th>
<td><input name="name" id="name" type="text" value="4Cast" size="40" aria-required="true">
</td>
</tr>

<tr class="form-field">
<th scope="row" valign="top"><label for="description">Descrição</label></th>
<td><textarea name="description" id="description" rows="5" cols="50" class="large-text">    </textarea><br>
</td>
</tr>

<p class="submit"><input type="submit" name="submit" id="submit" class="button button-primary" value="Atualizar"></p>
</form>

</section>
</secrion>

<?php get_footer(); ?>

2 answers

3

The function you seek is wp_insert_term.

Remarks:

  • It is important to develop with the error report connected, you would see that $pid = $_REQUEST [ 'pid' ]; gives a Warning.
  • Missing add a security check, but any spam bot will abuse the <form>.
  • To form action have to point to own page.
  • Better use names of fields custom, not to risk conflicts with names used by Wordpress.

Here is a very simple example, using a small part of the structure of this tutorial (it is worth checking out the entire tuturial, note that it does not use nonce):

<?php
/**
 * Template Name: Page Template Editar Categoria 
 */    
get_header() ?>
    <div id="container">
        <div id="content">
            <?php the_post() ?>
            <div id="post-<?php the_ID() ?>" class="post">
                <div class="entry-content"><?php
                    /**
                     * Verifica se o FORM foi enviado
                     */
                    if( isset( $_POST [ 'submitted' ] ) ) {
                        /**
                         * Verifica segurança
                         */
                        if( wp_verify_nonce( $_POST['nonce_form_sopt_28484'], 'nonce_form_sopt_28484' ) ) {
                            # FALTA conferir se a categoria existe
                            # FALTA definir se pode ser categorias-filhas 
                            $term_id = wp_insert_term(
                              $_POST [ 'nome' ], // the term 
                              'category', // the taxonomy
                              array(
                                'description'=> $_POST [ 'descricao' ]
                              )
                            );
                            if ( !is_wp_error( $term_id ) ) {
                                # DEBUG
                                printf( 
                                    'Categoria <strong>%s (%s)</strong> inserida com sucesso. IDs:<br /><pre><code>%s</code></pre>', 
                                    $_POST[ 'nome' ],
                                    $_POST[ 'descricao' ],
                                    print_r( $term_id, true ) 
                                );
                            } else {
                                # DEBUG
                                printf( 'Erro ao gravar:<pre><code>%s</code></pre>', print_r( $term_id, true ) );
                            }
                        }
                    } ?>      
                    <form action="<?php the_permalink(); ?>" method="post">
                    <?php wp_nonce_field( 'nonce_form_sopt_28484', 'nonce_form_sopt_28484' ); ?>
                    <input type="hidden" name="submitted" id="submitted" value="true" />
                    <p>
                        <label for="nome">Nome</label>
                        <input name="nome" id="nome" type="text" placeholder="O nome da categoria" size="40" aria-required="true">
                    </p>
                    <p>
                        <label for="descricao">Descrição</label>
                        <textarea name="descricao" id="descricao" rows="5" cols="50" class="large-text" placeholder="Descrição da categoria"></textarea>
                    </p>
                    <p class="submit">
                        <button type="submit">Criar categoria</button>
                    </p>
                    </form>
                </div><!-- .entry-content ->
            </div><!-- .post-->
        </div><!-- #content -->
    </div><!-- #container -->

<?php get_sidebar() ?>
<?php get_footer() ?>

Upshot:
demo

  • Thank you very much for the answer, it will enable the improvement of many forms!!! However, the wp_insert_term function, to add a new taxonomy, the center of doubt is like editing taxonomy! In my code, I have already been able to create the editing page that retrieves the values of the name and description of the database taxonomy, the function I need now, is the one that updates these values in the database, after Submit!

  • Hi, so please update your question with the code you are using.

  • This is exactly the code I’m trying to build to edit the category. I’ll explain further: I have a page where the user can add a category, via front end. Ex: Category Name => Maria Category Description: Maria is a nice girl. On the category page there is a link that redirects to the page that contains the above code, which should be for the user to edit the category. Ex. Category Description: Maria is a nice girl. Change to: Maria is a boring girl. Click on Ubmit and the category is updated. That’s what I’m failing to realize.

1


After a lot of research problem solved! I will post the solution to help whoever wants to accomplish the same thing.

Edit link on the category page:

<?php
    $catID = get_queried_object()->term_id;
    //Obtem o ID da categoria visualisada.
?>

<form class="editar-categoria" action="<?php echo get_site_url(); ?>/editar-categoria/?editar-categoria=<?php echo $catID; ?>" method="post">
    <input type="hidden" name="editar-categoria" value="<?php echo $catID; ?>" />
    <input type="submit" value="Editar Categoria"/>
</form>             

Now the category edition page template:

<?php 
    /*Template Name: Page Template Editar Cetegoria*/
    get_header(); 
?>

<section class="conteudo-geral">
    <section class="conteudo" style="width: 990px" role="main">
        <?php
            $categoria_id = isset( $_GET['editar-categoria'] ) ? intval( $_GET['editar-categoria'] ) : 0;
            //pega o id da categoria da pagina anterior
            $terms = get_term_by('id', $categoria_id, 'category', 'ARRAY_A');
            //pega os dados da categoria

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

                $category_id = get_cat_ID($terms['name']);
                $category_link = get_category_link( $category_id );
                //pega o link da categoria para fazer redirecionamento da pagina no final   

                $term_name = $_POST['nome'];
                $term_description = $_POST['descricao'];
                //pega os dados dos campos de formulario

                $result = wp_update_term( $categoria_id, 'category', array(
                        'name' => $term_name,
                        'description' => $term_description ) );
                //função do wordpress para editar categoria

                if ( array_key_exists( 'term_id', $result ) ) {
                    echo true;
                } 
                else {
                    echo false;
                }

                wp_redirect( $category_link );
                exit;
            }
        ?>      

        <form action="" method="post">
            Nome da Categoria: 
            <br>
            <input type="text" name="nome" value="<?php echo get_cat_name($categoria_id); ?>" size="75" required/>
            <br>
            Descrição da Categoria:
            <br>                            
            <input type="text" name="descricao" value="<?php echo $terms['description']; ?>" size="75" required/>
            <br>
            <br>

            <!-- Caso precisar editar qualquer custom filed 
            Custom Field:
            <label for="category_custom_1order">Custom Field: </label>
            <br>
            <input name="category_custom_1order" id="category_custom_1order" type="text" value="<?php echo get_option( 'category_custom_1order_' . $categoria_id); ?>" /> -->

            <input type="submit" name="submit" value="Enviar" />
        </form>
    </section>
</secrion>

<?php get_footer(); ?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.