I have a form for registered users to submit a post from the front-end of my site. The post is registered in a custom post type, all works.

But now that I have to add a button for the user to delete the post, I noticed something.

In the admin panel, the author is the user, all good. When I pull the posts from that user on the front-end, all the posts are there, all good. But on that list, on the front-end, if I try to check the ID of the author, the one that is shown is the same as one of the admin's.

Apparently, that is preventing the user from deleting a post he created. When the user clicks to delete the post, the page refreshes, and nothing happens to the post.

So, my user has the permissions:

  • 'publish_posts'
  • 'delete_posts'
  • 'delete_published_posts'
  • 'delete_private_posts'

Here is the page that creates the post:

$title     = $first_name_article . $tipo . $marca . $modelo;
$post_type = 'cadastro_anuncios';
if ( isset($_POST['publicar']) ) :
    $postStatus = 'publish';
elseif ( isset($_POST['gravar_rascunho']) ) :
    //draft can't be used here, hence we use 'private'
    $postStatus = 'private';
//define the arrays for the new post
$idDoUsuario = $_POST['idDoUsuario'];
$new_post = array(
'post_title'    => $title,
'post_status'   => $postStatus, 
'post_type'     => $post_type,
'post_author'   => $idDoUsuario,
//insert the the post into database by passing '$new_post' to 'wp_insert_post'
//store our post ID in a variable $postID
$postID = wp_insert_post($new_post);
$newTitle = array(
    'ID'           => $postID,
    'post_title'   => $title . ' - ' . $postID,
    'post_name'   => $title . ' - ' . $postID,
// Update the post into the database
wp_update_post( $newTitle );

Here is part of the page that has the form filled by the user:

<div class="btns-cadastrar-anuncio col-md-12">
    <input type='hidden' name='idDoUsuario' value='<?php echo get_current_user_id(); ?>'>
    if ( !in_array( 'loja', (array) $current_user->roles )):
        wp_nonce_field( 'publicar','nonce_anuncio' ); 
    <input type="submit" class="btn-pub-ad cadastro-anuncio" id="publicar" name="publicar" value="PUBLICAR">

Here is the code that generates the link to delete the post:

 if ( $queryAdsAll->have_posts() ) : while ( $queryAdsAll->have_posts() ) : $queryAdsAll->the_post();
$idDoPost = $post->ID;
<a class="btn-base btn-ativo btn-apagar-anuncio" href="<?php echo get_delete_post_link( $idDoPost ); ?>">APAGAR</a>
  • Are you sure that 'current_user' variable is defined in that scope? – Krzysiek Dróżdż Dec 19 '18 at 13:52
  • Yes. I even forced the author property of the post when creating it to get the ID. – Marcelo Henriques Cortez Dec 19 '18 at 13:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.