Advertisement
Creative Coding

Posting via the Front End: Editing and Deleting

by

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!

Related Posts
  • Web Design
    UX
    Impress Your Visitors With a Web 2.0 Hit CounterCounter thumb
    If there's one way to show off how successful your site is, it's by letting your visitors know how many others have been there before them. Let's furnish a web page with a hit counter!Read More…
  • Web Design
    eCommerce
    Taking Shopify Theme Development FurtherShopify thumb
    In this final part of our Shopify series we will look at how a deeper knowledge of Liquid will enable you to make your themes even more flexible. This will help you deliver richer and more imaginative store designs.Read More…
  • Code
    JavaScript & AJAX
    Working With IndexedDB - Part 2Indexeddb retina preview
    Welcome to the second part of my IndexedDB article. I strongly recommend reading the first article in this series, as I'll be assuming you are familiar with all the concepts covered so far. In this article, we're going to wrap up the CRUD aspects we didn't finish before (specifically updating and deleting content), and then demonstrate a real world application that we will use to demonstrate other concepts in the final article.Read More…
  • Code
    HTML & CSS
    Pure: What, Why, & How?Pure retina preview
    This tutorial will introduce you to Pure, a CSS library made of small modules, that can help you in writing completely responsive layouts, in a very fast and easy way. Along the way, I'll guide you through the creation of a simple page in order to highlight how you can use some of the library's components.Read More…
  • Code
    Plugins
    How to Create a WordPress Avatar Management Plugin from Scratch: Getting StartedPreview
    Avatar Manager for WordPress is a sweet and simple plugin for storing avatars locally and more. Easily. Enhance your WordPress website by letting your users choose between using Gravatar or a self-hosted avatar image right from their profile screen. Improved workflow, on-demand image generation and custom user permissions under a native interface. Say hello to the Avatar Manager plugin.Read More…
  • Code
    Business
    Making the Best of Google AdSense in WordPressGoogleadsensepreview
    Blog monetization is not a "must", but it's a very important source of motivation. Whether you're blogging alone or along with some authors you gathered, earning even a few bucks a month can change your and/or your authors' approach to your blog. Since Google AdSense is one of the easiest and most popular ways for blog monetization, we're going to see how to use it with a WordPress blog with multiple authors. (Although, this tutorial will also work for single bloggers.) We'll be covering how to set up profile fields for authors' AdSense ads and how to display those ads with a function, with a widget, with a shortcode and automatically inside posts.Read More…