Try Tuts+ Premium, Get Cash Back!
Posting via the Front End: Editing and Deleting

Posting via the Front End: Editing and Deleting

Tutorial Details
  • Program: WordPress
  • Version: 3.0+
  • Difficulty: Intermediate
  • Estimated Completion Time: 30 mins / 1 Hour
This entry is part 2 of 3 in the series Posting via the Front End

Today, we will be continuing with our mini-series into insert posts via the front end but in this part we will be exclusively looking at how to edit and delete posts via the front end. We will be covering how to display all our posts, edit them, and delete them. So, let’s get ready and begin!


Introduction

We are now in part two of our mini-series, and if you have not read the first part then I advise you do because we will be picking up from where we left off. Our goal after completing this mini-series should allow the user to submit posts via the front end, along with editing and sending the posts to the trash; all without being in the WordPress Dashboard. These methods can be used in both a theme or plugin and be very adaptable to achieve very advanced and complex submissions.

The demo and the download files are a stripped down theme which has been created for just the purposes of this tutorial.

So open up your favourite text editor and let’s begin!


Step 1 Displaying Our Posts

We will begin by displaying all of our posts more effectively, this will give us better management over our posts and allow us to perform actions on each post. As we are using a theme to develop this, we will create a page template called template-view-posts.php. Also, we will create a new page via our WordPress Dashboard Pages -> Add New -> Page Attributes as assign the template to this page.

We now have our Page Template and Page created in our WordPress theme, we can begin outputting all of our posts. We will be creating a very simple table to output all the necessary information. Begin by creating a table with some headings, as follows:


<table>

	<tr>
		<th>Post Title</th>
		<th>Post Excerpt</th>
		<th>Post Status</th>
		<th>Actions</th>
	</tr>

	<tr>
		<td></td>
		<td></td>
		<td></td>
		<td></td>
	</tr>

</table>

Now that we have our table in place, we can start filling our table rows with information with regards to our posts. We will begin by first making a custom WordPress loop, to ensure that we are getting all the posts and all the post statuses, because we want to be able to see what posts are pending, drafts, published or even sent to the trash. We do this by inserting the following bit of code:


<?php
$query = new WP_Query( array(
	'post_type' => 'post',
	'posts_per_page' => '-1',
	'post_status' => array(
		'publish',
		'pending',
		'draft',
		'private',
		'trash'
	)
) );
?>

This is our query object with all of our custom parameters we have set. You can read about all the different parameters we can set from the WordPress Codex. Next we will run our WordPress loop just after our table headings, like this:


<?php
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>

<tr>
	<td></td>
	<td></td>
	<td></td>
	<td></td>
</tr>

<?php endwhile; endif; ?>

Brilliant! We have our table set, and our WordPress loop set. Now we just need to input our information which is related to our table headings. Replace our empty table cells with the following code:


<tr>
	<td><?php echo get_the_title(); ?></td>
	<td><?php the_excerpt(); ?></td>
	<td><?php echo get_post_status( get_the_ID() ) ?></td>
	<td><a href="#">Edit</a> <a href="#">Delete</a></td>
</tr>

The code we have just inserted first begins with outputting our post title, and the next item is outputting an excerpt of our post. We then get the current status of the post and pass the post ID to this function and finally, we enter two links Edit and Delete, we will use these later as our actions.


Step 2 Editing Our Posts

Brilliant, we are making good progress. We have set up our theme to view all of our posts via the front end. Next, we are going to edit the post. We begin this by creating another page template called template-edit-posts.php. Also, we will create a new page via our WordPress Dashboard Pages -> Add New -> Page Attributes and assign the template to this page.

Before we begin editing this template, let’s jump back to our template-view-posts.php file and ensure that we are passing the Post ID to the URL where we will retrieve the ID from our edit page. We do this by using the WordPress function: add_query_arg. We will insert the following code just before our Edit link:


<?php
$edit_post = add_query_arg( 'post', get_the_ID(), get_permalink( 61 + $_POST['_wp_http_referer'] ) );
?>

The code we just inserted, first sets the parameter’s name, and then following this is getting the ID of the post and then we are getting the ID of our Edit Page template and adding our custom URL argument. We will be using this to retrieve the information in our Edit template.

Finally, we will output this into our edit link, making our edit link as follows:


<a href="<?php echo $edit_post; ?>">Edit</a>

Now that we have it set for when the User clicks on Edit it goes to our Edit Template with the Post ID. We will go back to our template-edit-posts.php file and begin inserting our code.

We will copy over our Form from our template-insert-posts.php and insert this into our Edit Template. We are copying the following code into our edit template, and remove all the values from our inputs and textarea, making our form as follows:


<form action="" id="primaryPostForm" method="POST">

	<fieldset>

		<label for="postTitle"><?php _e( 'Post\'s Title:', 'framework' ); ?></label>

		<input type="text" name="postTitle" id="postTitle" value="" class="required" />

	</fieldset>

	<?php if ( $postTitleError != '' ) { ?>
		<span class="error"><?php echo $postTitleError; ?></span>
		<div class="clearfix"></div>
	<?php } ?>

	<fieldset>
				
		<label for="postContent"><?php _e( 'Post\'s Content:', 'framework' ); ?></label>

		<textarea name="postContent" id="postContent" rows="8" cols="30"></textarea>

	</fieldset>

	<fieldset>
		
		<?php wp_nonce_field( 'post_nonce', 'post_nonce_field' ); ?>

		<input type="hidden" name="submitted" id="submitted" value="true" />
		<button type="submit"><?php _e( 'Add Post', 'framework' ); ?></button>

	</fieldset>

</form>

Now that we have our Edit page form set, we will need to use the WordPress loop to go through all of our posts and only find our posts which match the post ID passed through to our URL. We will do this by running the WordPress loop at the top of our file:


<?php $query = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => '-1' ) ); ?>

<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>

<?php

	/*
		We will be inserting all of our information inside of here
	*/

?>

<?php endwhile; endif; ?>
<?php wp_reset_query(); ?>

For the WordPress loop to ensure that we are only retrieving the information of the specific post, we will insert the following code which ensures that we are getting the correct post ID, inside of our loop:


if ( isset( $_GET['post'] ) ) {
	
	if ( $_GET['post'] == $post->ID )
	{
		$current_post = $post->ID;
	}
}

What we have just inserted is to get the URL parameter and test it against the post ID, and when it has found a match we will assign that ID to our current_post variable. Following this we will insert some code to get our information with regards to our post, insert the following code just below our current_post assignment:


$title = get_the_title();
$content = get_the_content();

Our final code should look like this:


if ( isset( $_GET['post'] ) ) {
	
	if ( $_GET['post'] == $post->ID )
	{
		$current_post = $post->ID;
		$title = get_the_title();
		$content = get_the_content();
	}
}

This is great, we are making good progress. Now that we have all of our information, we just need to insert it into our form values, this is simple as we will just assign values for both of our fields. Along with this we will update the name of our button to Update Post. The following code is our updated form with the form populated with the title and the content of the editing post:


<form action="" id="primaryPostForm" method="POST">

	<fieldset>

		<label for="postTitle"><?php _e( 'Post\'s Title:', 'framework' ); ?></label>

		<input type="text" name="postTitle" id="postTitle" value="<?php echo $title; ?>" class="required" />

	</fieldset>

	<?php if ( $postTitleError != '' ) { ?>
		<span class="error"><?php echo $postTitleError; ?></span>
		<div class="clearfix"></div>
	<?php } ?>

	<fieldset>
				
		<label for="postContent"><?php _e( 'Post\'s Content:', 'framework' ); ?></label>

		<textarea name="postContent" id="postContent" rows="8" cols="30"><?php echo $content; ?></textarea>

	</fieldset>

	<fieldset>
		
		<?php wp_nonce_field( 'post_nonce', 'post_nonce_field' ); ?>

		<input type="hidden" name="submitted" id="submitted" value="true" />
		<button type="submit"><?php _e( 'Update Post', 'framework'); ?></button>

	</fieldset>

</form>

As you can see from the code, we have assigned our Post Title input value to output the title variable, and inside of our textarea we have outputted our content variable, but as you may have noticed that when we click Update Post nothing happens, this is because we have not handled this yet, and we will be doing this now.

We will need to jump back to our template-insert-posts.php file and we are going to copy our PHP form validation to our Edit Template. Now that we have copied over our form validation, we will make some changes and insert some code. We need to retrieve the current_post variable in our form validation, and we do this by setting a global variable and we insert this above our validation:


global $current_post;

Next, we will make a modification to our post_information array. As we are updating our post, we need to ensure that it will be updating the correct Post and not all posts, we do this by inserting an ID parameter into our post_information array. Making our array as follows:


$post_information = array(
	'ID' => $current_post,
	'post_title' =>  wp_strip_all_tags( $_POST['postTitle'] ),
	'post_content' => $_POST['postContent'],
	'post_type' => 'post',
	'post_status' => 'pending'
);

Finally, we will make one final modification which will ensure that we are updating the post and not inserting a new post. We do this by simply changing the function we use, instead of using wp_insert_post, we will be using wp_update_post. Making our final code as follows:


$post_id = wp_update_post( $post_information );

And that’s it for editing post’s via the front end. Finally, for this part of the mini-series we will go onto how to delete posts.


Step 3 Deleting Our Posts

Now there are many different ways to delete posts, and there have been many different discussions in the best method on how to achieve this, by some people this is probably the incorrect method but I feel that it works perfectly fine for this current situation. We will be using the function get_delete_post_link.

We will be passing this function to our Delete Link, along with passing the ID of the post, as follows:


<a href="<?php echo get_delete_post_link( get_the_ID() ); ?>">/Delete</a>

And it’s that simple to delete Posts via the front end. We will just expand this a little to ensure that we will not have any errors and give a little more user notification that we are deleting a post. We do this by inserting a very simple confirm function to our onclick, as follows:


<a onclick="return confirm('Are you sure you wish to delete post: <?php echo get_the_title() ?>?')" href="<?php echo get_delete_post_link( get_the_ID() ); ?>">Delete</a>

Finally, we will wrap a condition around our delete link, to ensure that we can only delete a post if the current status of the post isn’t already in the Trash. We do this as follows:


<?php if( !(get_post_status() == 'trash') ) : ?>

	<a onclick="return confirm('Are you sure you wish to delete post: <?php echo get_the_title() ?>?')"href="<?php echo get_delete_post_link( get_the_ID() ); ?>">Delete</a>

<?php endif; ?>

And that’s it! You are able to send posts to the Trash. Just in case you were curious on the alternative method on how to delete posts, I will explain it very briefly.

The method is very simple to Editing Posts, by passing the Post ID to the URL along with adding a parameter of delete and checking if the value of this parameter is true, and if it is true then pass the wp_trash_post function to the link. This is very simple and very effective, but for our current situation the get_delete_post_link works perfectly fine.


Conclusion

That’s Part 2 complete! We are now able to insert posts, edit and delete Posts via the front end. We have covered a lot of content so far, and in the next part we will be digging a little further.

Within the next part, we will be having a look into custom fields and more.

I would like to say a HUGE thank you for spending the time to read my tutorial, I hope it helped. Please feel free to leave comments and I will try my best to assist and answer them, if not you can always contact me directly through my website: www.VinnySingh.co or Twitter @VinnySinghUK

Stay tuned for Part 3!


Other parts in this series:Posting via the Front End: InsertingPosting via the Front End: Advanced Submission
Tags: front end
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://pixeltuner.de Jonathan

    Great! It’s a nice feeling when you comes to an end after a long search!

  • Jan Beck

    Deleting a post via an url is not a good practice. URLs can get requested accidentally e.g. Bots or a browser that tries to preload all links in a page. Better use a form via post method. If thats not fancy enough for you, you can submit it via ajax. Remember: GET requests should never alter data on the serverside.

    • http://vinnysingh.co/ Vinny Singh
      Author

      I did only briefly explain this method and didn’t go into further detail, but If this method was used, you would obviously apply security checking and ensure that you wouldn’t be able to make multiple requests via the URL, by using nonces etc.

  • http://www.wp-tricks.co.il/ Rami

    The code you use in ” template-view-posts.php” shows all the content. I would recommend to show only posts belong only to the current user.

    global $current_user;
    get_currentuserinfo();
    $user = $current_user->ID;

    $query = new WP_Query( array(
    ‘author’ => $user, // Show Posts made only by the current user.
    ‘post_type’ => ‘posts’,
    ‘posts_per_page’ =>’10′,
    ‘paged’ => get_query_var(‘paged’)
    )
    );

    By the way, Vinny, great tutorial !!

    • http://twitter.com/mreonet Emre Caglar

      where do you put this code. i really need it but couldnt make it work

  • http://explorefieldtrip.com/viewposts William Mosley

    First, thanks for the post series. I’ve been looking for implementation of frontend editing for a while.

    current pages
    http://explorefieldtrip.com/newpost
    http://explorefieldtrip.com/viewposts
    http://explorefieldtrip.com/editpost

    I currently can not get the validation feature to work as well as the link between
    View Posts Page –> edit (action) to Edit Posts Page.

    It just refreshes to the same page (View Posts) with an extended URL of explorefieldtrip.com/viewposts/?post=1480

    Please help, I’d like to continue with your front end series. Thanks.

  • Pingback: วิธีสร้าง Wordpress Plugin โพสเนื้อหาผ่านหน้าเว็บไซต์ | JDesign's Blog

  • Martin

    Great tutorial Vinny! Is there a way to “unpublish” a post instead of Deleting. I want to keep that information instead of deleting it.

    Thanks!

  • Pingback: Posting via the Front End: Editing and Deleting | ThemeMountain

  • vaibhavmav

    can u add some code
    which on deleting the post redirects them to main page
    instead of giving them a 404error after deleting it
    (i use this code in Single.php)

  • ZacEckstein

    Hmmm, when updating a post it’s creating a new post even though I’ve changed the function name…

    Also, how do I get a custom post type to update to its current type? Does that happen automatically?

  • tc

    Hi, this tutorial is awesome. But I have one question, why are you using wp_query in edit post template? why don’t directly using the $_GET['post'] to get the meta value title value?

    Like this:

    $title = get_the_title($_GET['post']);

    $content = get_the_content($_GET['post']);

    $custom_one = get_post_meta($_GET['post'], 'vsip_custom_one', true);

    $custom_two = get_post_meta($_GET['post'], 'vsip_custom_two', true);

    Is there any particular reason you use the wp_query?

  • http://twitter.com/Payman2543 P♠ym♣n

    The best work I’ve seen on this topic, I was looking for a long time couldn’t find anything as good as this.

  • http://www.jameelbokhari.com/ Jameel Bokhari

    I found this tutorial very helpful thanks a lot!
    Some constructive criticism: Maybe it’s just me but the parts where you reference the first part of the tutorial annoyed me. Why not just post the code again? I used this as a reference for a project I’m working on, rather than doing your exact tutorial step by step, and didn’t want to have to jump back to other sections.
    Thanks!