Stripslashes in textarea in a WordPress plugin option

Working on a WordPress plugin today I found that when HTML was added within a ‘textarea’, backslashes (\) were being added to the code wherever there was an apostrophe or quotation mark.

After hunting down a solution by searching for things like:

wordpress text stripslashes
wordpress stripslashes in textarea
wordpress slashes in textarea
wordpress plugin options textarea slashes

etc. etc. etc.!

I tried a suggestion which is supposed to disable PHP magic quotes, found in this article:

Getting rid of unwanted backslashes in WordPress form input from fearlessflyer.com

<?php 
if ( get_magic_quotes_gpc() ) { 
$_POST = array_map( 'stripslashes_deep', $_POST ); 
$_GET = array_map( 'stripslashes_deep', $_GET ); 
$_COOKIE = array_map( 'stripslashes_deep', $_COOKIE ); 
$_REQUEST = array_map( 'stripslashes_deep', $_REQUEST ); 
} 
?>

Unfortunately this didn’t work, and there’s a warning at WordPress.org about this stripslashes_deep method being unreliable:

“Please Note: On any page load where WordPress itself loads, the above example will be unreliable. Very early in its execution, WordPress intentionally adds “magic quotes” for the sake of consistency. This is regardless of the return of get_magic_quotes_gpc(). Core code, and plugins all over, expect the values of $_REQUEST etc to be escaped.”

The solution to the problem of backslashes in a textarea in a WordPress plugin…

I eventually found the solution from this post on the WordPress forum where Rev. Voodoo was having the backslashes problem on text input, but NOT on textareas – so I just took a look at the method he used on the textarea’s and copied that.

When you echo the option in to the textarea, that’s where you add your ‘stripslashes’ code, like so:

<textarea name="myplugin_options[mytextarea-option]" rows="7" cols="57" type='textarea'><?php echo stripslashes($options['mytextarea-option']); ?></textarea>

And voila! Backslashes are no more :)

But then – I had a problems displaying the options in my theme on the front end of the site. First, the HTML code was printing as escaped entities (I think that’s the correct way to describe it…) – meaning on my page I could see the ‘< p >‘ and ‘< a href' etc. as text rather than them being displayed as a regular HTML paragraph and anchor, and I was getting backslashes again. This is the code I was originally using to display the option in my theme:

<?php 
$options = get_option('myplugin_options');
$mytextareaoption = $options['mytextarea-option'];
echo "{$mytextareaoption}";
<?php>

And this is the updated code I used to display the option in my theme, without any HTML escaping errors or backslashes:

<?php 
$options = get_option('myplugin_options');
$mytextareaoption = $options['mytextarea-option'];
esc_html( $mytextareaoption );
echo stripslashes ( "{$mytextareaoption}" );
?>

And voila again! No HTML errors or backslashes on the front end :)

For reference: this article about Data Validation at WordPress.org is really informative. Although, there are so many options it can a bit overwhelming understanding which one is best to use in a situation. Nevertheless, it’s definitely worth a read to help us learn more about WordPress development.

Animal rescue custom post type plugin for WordPress

screenie_plugin_animals-cpt_add-postI’ve worked on a number of animal rescue WordPress websites and recently developed a basic ‘custom post type’ plugin so that animals for adoption can be posted separately from regular ‘posts’. Posts can then be reserved for news, events and general blogging.

I’m making my ‘animals custom post type’ plugin available for download here (it’s free, released under GNU General Public License):

Download Animals Custom Post Type Plugin

Download the .zip file and:

  • upload it via FTP to your wp-content/plugins directory, or in your WordPress admin panel, go to Plugins > Add New > Upload, to upload the file manually, then
  • activate the plugin on the ‘Plugins’ page and the ‘Animals’ option should then appear in the menu

Note: In some cases, the permalink structure must be updated in order for the new template files to be accessed when viewing posts of a custom post type. To do this, go to Administration Panels > Settings > Permalinks, change the permalink structure to a different structure, save the changes, and change it back to the desired structure.

What’s included in the ‘Animals’ custom post type and custom taxonomies plugin?

Once the plugin has been installed and activated you will see an ‘Animals’ option appear in the list on the left of the WordPress admin dashboard.

Here you can add posts for any type of animal for adoption, and there are 6 types of custom taxonomy included with the custom post type, which are:

  • Species
  • Gender
  • Age Group – included so that you can group animals of similar ages together, e.g. 0-1 years, 2-5 years etc.
  • Age – so that you can also add a more specific age
  • Rehoming Status – you can add custom rehoming statuses such as ‘Available for adoption’, ‘In foster’, ‘Rehomed’ etc.
  • Rehoming Options – you can add custom rehoming options such as ‘Can’t be homed with children under 10’, ‘Can live with dogs’ etc.

All of these taxonomies can then be easily accessed from the front end of the site, for example in a menu, a tag cloud widget or an advanced search system so that people can perform very specific searches on animals for adoption.

(If you want to add more custom taxonomies here’s a very useful ‘Custom Taxonomy Code Generator‘.)

Why use a custom post type for animals for adoption?

Using a custom post type has many advantages over using regular posts:

  1. It makes the administration process easier for the rescue owner/website manager – it’s a much better user experience if you can see the ‘Animals’ section in the admin panel and click on ‘add new animal’ instead of using ‘add new post’ for animals AND regular posts alike.
  2. You can use different taxonomies for each post type, so whereas your ‘posts’ might just have the tags and categories taxonomies available, your ‘animals’ can have custom taxonomies like age, gender, breed etc. and it’s much simpler for the end-user than if these custom taxonomy options are presented to them on the post edit page when they’re simply writing a regular news/blog post.
  3. It’s easier to distinguish and display the animals for adoption on the front end of the site – your animals for adoption can be given their own style based on the custom post type – many WordPress themes add a special CSS class to the ‘body’ html tag based on the custom post type of the archive or single post being viewed, and special custom post template files can be included in your theme, so the layout of the page can be completely customised.
Update July 2014
I’ve had a few queries in the comments about how to display your animals custom posts. I found this tricky when custom post types were first introduced too!

You can basically access the custom posts via a URL and you can include the URL(s) in your menu on the front end of your site. So for example:

To view all animals:
http://yourwebsite.com/animals/

All animals marked as ‘available for adoption’:
http://yourwebsite.com/rehoming_status/available-for-adoption/

All animals of a certain species, for example – dogs:
http://yourwebsite.com/animal_species/dog/

All animals of a certain gender:
http://yourwebsite.com/animal_gender/male/

All animals of a certain age:
http://yourwebsite.com/animal_specific_ages/2-months/

So whatever terms you have used for taxonomies you can view all posts marked with those taxonomies.

Another method suggested by Jennifer Mann in the comments (thanks Jennifer!) is to use the ‘Display Posts Shortcode plugin‘ which makes it super easy to create a page and simply add in a shortcode to display any list of posts within that page.

So for example, to display a list of all animals posts created using this ‘animals custom post type’ plugin, you would use this shortcode:

[display-posts post_type=”phanimals”]

 

To find out more about different options for the list using this method (such as showing images and excerpts), see their arguments document here: https://github.com/billerickson/display-posts-shortcode/wiki

I love helping animal rescues get more from their WordPress websites, so hopefully this will be the first of many posts dedicated to the topic :) Soon I will add more information and code examples on how to display the custom taxonomies on your animals for adoption posts on the front end of your site using the terms function.

Do let me know in the comments if this plugin was useful for you or if you have any questions.

New WordPress default theme Twenty Thirteen, let’s take a look

screenie_twentythirteenNow that Twenty Thirteen is officially released and is now the default theme for WordPress, I thought it was high time I took a look under the hood.

Before I dig in to the code I must be honest and say I’m not very fond of the default design of Twenty Thirteen. I like the general colour scheme but I think the background image on the header is quite ugly!

I’m sure the theme will look great on a mobile device, but on a desktop monitor everything looks a little on the large side – very large fonts (which are great as long as they’re not overused), a large header area with lots of wasted space and large empty areas to the left and right of the main content column in the center (perhaps sidebars can be added in the theme options? Haven’t checked that out yet).

Presumably the header background image can be customised by the site
admin which is an incredibly useful feature for the everyday WordPress user, but still I feel the area has been made far too large (I thought big headers were ‘so 5 years ago’).

screenie_twentythirteen_FONT

I do like the fonts used in Twenty Thirteen. It makes a change for a default theme to use a serif font for entry titles and a sans-serif font for the main body of text. It really helps the titles to stand out and is something you usually see a lot on professionally designed custom themes.

I like the idea of using a different background colour for posts of different formats – BUT – pretty much every site I’ve made/worked on so far, barring one, hasn’t used the post format feature, so this may be wasted on many sites. Maybe it would have been better to have background colours alternate on a per-post basis so that a long list of regular posts would still be able to make use of the effect.

Of course, design is subjective – so whilst there are things I do and don’t like about Twenty Thirteen, I can understand that many people will think it looks lovely, and that’s all good.

So we shall move on to the ‘under the hood’ portion of this Twenty Thirteen review:

Twenty Thirteen CSS and HTML

First impressions on the CSS of the theme are – “WOW, this is much cleaner than Twenty Twelve!” There’s less clutter and the code is laid out in such a tidy manner.

REM sizes are gone in Twenty Thirteen, yay!

I’m glad ‘rem’ sizes aren’t used in Twenty Thirteen as they were in Twenty Twelve. That always seemed overkill to me, but perhaps they will make a come back at a later date when the web design world is more prepared for them.

I’m glad that the basic structure and selector (CSS ID’s and classes) names have remained pretty much the same, albeit with minor changes here and there.

Looking at the HTML source of my demo page I see that some areas of the footer have ‘hard coded’ CSS elements within in the code, like so:

		<footer id="colophon" class="site-footer" role="contentinfo">
				<div id="secondary" class="sidebar-container" role="complementary">
		<div style="position: relative; height: 307px;" class="widget-area masonry">
			<aside style="position: absolute; top: 0px; left: 20px;" id="pages-2" class="widget widget_pages masonry-brick"><h3 class="widget-title">Pages</h3>		<ul>
			<li class="page_item page-item-495"><a href="http://www.pinkishhue.com/wpdemo/a-parent-page/">A parent page</a>

This is very unusual and as far as I knew – frowned upon. I’m not sure why this has been done. I can’t imagine the theme would contain errors so blatant, as they are tested by a lot of people before being officially released, so I wonder if the CSS is somehow dynamically generated, perhaps based on the users browser size? I’m still trying to figure that one out.

Twenty Thirteen colours

The colour scheme for Twenty Thirteen is warm and well put together (although as already mentioned I’m not very keen on the coloured circles header image).

One of the first things I do when playing around with the CSS for a child theme is edit the colours used for links. This was very easy in Twenty Twelve with most link colours easily change-able by just editing the single colour setting for anchors (the ‘a’ element) in the CSS. But I notice Twenty Thirteen has used quite a few different HEX colour codes for links, and 3 or 4 of them are very close variations of the same dark red, meaning the difference will probably not very noticeable so it would’ve been easier, and in my opinion less confusing to the end user, to use just the one dark red colour.

But this is a small complaint. Not even a complaint really, more of a comment :)

Twenty Thirteen Theme Options

Although I could understand the zen-like simplicity of NOT having a theme options page for Twenty Twelve, I’m glad to see this is back in Twenty Thirteen. I’m glad on behalf of all the non-web-designer WordPress users out there who’ve been crying out for ways to customise the look of their website without having to really deal with code, which is understandably not everyone’s cup of tea.

(And the options page will certainly come in handy when people want to change that butt-ugly header image! [/joke])

Twenty Thirteen conclusion – more study needed!

As this has been just a brief review and there’s a lot of features I haven’t even seen yet, I won’t give a full on conclusion here except to say that first impressions are good – it seems to be a friendly, uncomplicated theme.

More study will be required before I can officially (in my head) give it a placing in the ‘which is best’ list of the last 4 WordPress default themes.

Free Twenty Thirteen child themes will follow – the fruits of my study! Watch this space.

How to return the post ID in a WordPress shortcode

This should be so simple and it was it once I found the solution! (duh)

All I wanted to do is create a shortcode that will print (or echo or return – whatever you want to call it) the post ID of the current post.

So I would type something like: [mypostid]

and when the post was saved it would display just the post ID like: 1234

I tried using ‘the_ID’ and ‘get_the_ID’ and even $id, but none of those things worked.

I couldn’t find a straightforward answer to this question so I’m going to share the solution here. It’s really simple!

How to display the post ID in a shortcode:

You can put the code for this function in to the functions.php file of your theme, or preferably, add it to a plugin (details below). With a plugin you won’t lose the functionality of your shortcode if/when you change your WordPress theme.

*It’s a good idea to make a general Custom Functions plugin that is specific to your website and you can use it to house all these little extra functions that you will accumulate over time.

Here’s the basic code for the post ID shortcode:

//[thepostid]
function thepostid_func( $atts ){
         global $post;
         return $post->ID;   
}
add_shortcode( 'thepostid', 'thepostid_func' );

And below is the code to make a plugin out of this function. You should add this code to a plain text file called something like ‘my-custom-functions-plugin.php’, then either upload it to ‘wp-content/plugins/my-custom-functions-plugin/’ via FTP or, add the my-custom-functions-plugin.php file to a .zip file and upload it using the upload feature on the WordPress ‘Add New’ plugin page.

<?php
/*
Plugin Name: My Custom Functions
Plugin URI: http://yourwebsiteaddress.com
Description: A custom site functions plugin for yourwebsiteaddress.com
Version: 1.0
Author: Your Name Here
*/
 
//[thepostid]
function thepostid_func( $atts ){
         global $post;
         return $post->ID;   
}
add_shortcode( 'thepostid', 'thepostid_func' );

So, once you’ve added the code to your theme or plugin, you can simply type [thepostid] in to any post or page and voila! – the post ID will be displayed.

All my posts give 404 errors!!! Scary error from WP Super Cache update

I just had a scary experience – I went to edit a post on a WordPress install, everything was fine in the admin panel but when I hit ‘preview’ all I got was a 404 error! Whaaaaaat?!

Thinking maybe it was a one off server error I checked some other posts – they were all 404 too! Scary!

Assuming it might be caused by a plugin I had recently deactivated (I’ve been making an effort to clean up my plugin usage lately), I immediately went to the Plugins page and there I noticed a highlighted note about WP Super Cache being deactivated because I needed to save the settings.

I had recently updated WP Super Cache and I must have been in a hurry because I didn’t notice this note at the time.

I re-configured the settings and activated WP Super Cache and thankfully – no more 404 errors!

I think my posts were probably out of action for about a week so this could be very damaging to active blogs (luckily this was on one of my less active websites).

If you’re seeing all of your posts getting 404 errors and you’ve recently updated or installed WP Super Cache, you could be seeing the same error – so go ahead and check your settings!

WordPress error “Unable to create directory uploads/2013/04. Is its parent directory writable by the server?”

Today I was working on a WordPress site and received this error when I tried to upload an image:

“Unable to create directory uploads/2013/04. Is its parent directory writable by the server?”

I immediately went to my FTP program and changed the permissions on the uploads directory to ‘777’ – this didn’t fix it.

So I started googling to see if this was a known error and how it could be fixed. Other people were having the error and it was suggested that people go (in the WordPress admin panel) to Settings > Media and change the setting so that files are not stored in date based folders.

Doing this made me realise what the actual error was – I had changed hosting servers a few months previously so the file path that WordPress had stored in the database was no longer correct! I had forgottten about the change and expected WordPress to just keep working as normal.

In the ‘Store uploads in this folder’ section of the Media > Settings page I updated the setting to my new server path:

home/myaccount/public_html/mynewpath/wp-content/uploads

and all is well :)

(*Update: As of WordPress version 3.5 there is no longer a ‘Store uploads in this folder’ option in the admin panel. There is a handy plugin from ‘RVOLA’ here that should do the trick: wp-original-media-path/ and some other suggestions in the comments below)

I thought I’d make a quick post about this here on my blog just in case it’s helpful to anyone else who has this problem. Hey we all forget things from time to time!

Add another widget area to Twenty Twelve front page template in a child theme

I’m having a lot of fun making child themes with Twenty Twelve now that I’ve gotten used it, however, there are some small changes I’ve made to multiple child themes now, and one of those is adding a third widget area to the Twenty Twelve front page (home page) template.

It’s incredibly simple to do and I’ve found for most of my recent projects it’s been much more helpful to have 3 columns of information on the home page instead of just the 2.

So without further ado, here’s…

How to add another widget area to the Twenty Twelve front page template in a child theme

You only need to add (or edit) 3 files to make this change, and they are:

functions.php
sidebar-front.php
style.css

First, we’ll add the following code to functions.php to register our new widget area (also known as a sidebar).

If you already have a functions.php file in your child theme you want to add this code anywhere between the opening <?php and closing ?>. If you don’t already have an functions.php file in your child theme, create a new file and put the code below between an opening <?php and closing ?> and upload it to your child theme directory.

*Change ‘my-child-theme’ to your child theme directory name

1
2
3
4
5
6
7
8
9
	register_sidebar( array(
		'name' => __( 'Third Front Page Widget Area', 'my-child-theme' ),
		'id' => 'sidebar-front-third',
		'description' => __( 'Appears when using the optional Front Page template with a page set as Static Front Page', 'my-child-theme' ),
		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget' => '</aside>',
		'before_title' => '<h3 class="widget-title">',
		'after_title' => '</h3>',
	) );

Next, we’ll add the code that displays your widget area on the front end of your site. Copy sidebar-front.php from the Twenty Twelve theme and add it to your child theme, then above this line:

1
</div><!-- #secondary -->

add this code:

1
2
3
4
5
	<?php if ( is_active_sidebar( 'sidebar-front-third' ) ) : ?>
	<div class="third front-widgets">
		<?php dynamic_sidebar( 'sidebar-front-third' ); ?>
	</div><!-- .third -->
	<?php endif; ?>

Then upload your new sidebar-front.php to your child theme directory.

Now, we’ll add some code to the stylesheet to tell the theme how the widget area should look. In the default Twenty Twelve stylesheet we have one widget area to the left and one to the right, instead we want three in a row.

This code is added in the media-queries section so that it displays the three areas in a row on wide browsers but remains a single column when viewed on mobiles and other small devices (with this new third column being displayed underneath the original 2).

*Note about Internet Explorer and CSS media queries:
All versions of Internet Explorer prior to version 9 DO NOT support media queries. To get around that you can use twenty twelve’s handy IE stylesheet, stored in css/ie.css – copy that folder and file to your child theme then add the CSS code below to that file, but without the first 2 lines and without the closing ‘}’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* Minimum width of 600 pixels. */
@media screen and (min-width: 600px) {	
	.template-front-page.two-sidebars .widget-area .front-widgets, 
	.template-front-page .widget-area .widget:nth-child(even),
	.template-front-page.two-sidebars .widget-area .front-widgets + .front-widgets {
		float: left !important;
		width: 30.3% !important;
		margin-left: 1.5% !important;
		margin-right: 1.5% !important;
    }
	.template-front-page .widget-area .widget:nth-child(odd) {
		clear: none !important;
	}
	.template-front-page .widget-area .widget:nth-child(3n+3) {
		clear: right;  
	}	
}

Now go to your widgets page in your admin panel and add some widgets to see how it looks. Have fun!

If you find any issues with the code or need any help do feel free to leave a comment below.

An alternative to TDO Mini Forms for WordPress?

Updated May 2013

(scroll down to see my working solution with free download and instructions).

For a while now I’ve been using the WordPress plugin TDO Mini Forms on a directory website to collect listings in the form of posts from unregistered users.

It was working fine until about 6 months ago when an exploit was discovered and my website (along with other TDO Mini Forms users) was hit by malicious uploads.

I was able to get around this by disabling image uploads from the TDO Mini Forms plugin and asking people to simply email the images to me if they’d like one included in their listing. It wasn’t a perfect solution but it worked temporarily.

Unfortunately I’ve recently had more problems with TDO Mini Forms – submissions simply aren’t coming through. I will receive a couple a week but I have been emailed by multiple people who’ve submitted listings via my site but have received no notifications (and neither did I), and no post appeared in my admin panel.

It’s such as shame as the plugin had so many great features, including:

  • User submissions with no registration required
  • Email notifications to myself and the user submitting the post, both when they submitted it AND when it was published
  • The ability to include any number of custom fields on the form so I could add inputs for things like telephone numbers and lists of services AND the ability to have these display in the new post (without having to code the custom fields in to my template)
  • The ability to upload images via the form

Whilst looking for an alternative to TDO Mini Forms I have regrettably found that my options are very limited! Most WordPress plugins that allow posting for unregistered users from the front end are either:

  • too basic and don’t give all the options I need
  • too old and out of date to rely on
  • have too many bugs reported on the WordPress forums for me to want to try them

So, I’m stumped!

Here’s some links to possible alternatives to TDO Mini Forms for anyone reading this:

  • User Submitted Posts – wordpress.org/extend/plugins/user-submitted-posts/
    I have tested this on WordPress v3.4.1 and it seems to work great but unfortunately it doesn’t the ability to add custom fields to the form which is something I definitely need. There may also be a security issue as I believe it doesn’t include nonce
  • Gravity Forms – http://www.gravityforms.com/
    This is a premium plugin but it seems like the $39 low level version would be worth the money if that’s all you needed although you get a license for 1 year, beyond that you need to pay again for updates and support
  • Post From Site – wordpress.org/extend/plugins/post-from-site/
    I’ve tested this on WordPress v3.4.1 and it worked as it’s supposed to and seemed like you could incorporate custom taxonomies, but it didn’t let me choose multiple tags (no tags were added when I selected multiple) and it didn’t allow the poster to add their own tag which is something I need. Another one for the ‘no’ pile unfortunately
  • WordPress Guest Post – wordpress.org/extend/plugins/wordpress-guest-post/
    This plugin had too many serious sounding bug reports in the support forum for my liking, but if you know a bit more about plugin editing you may be able to make something out of it
  • One Quick Post – wordpress.org/extend/plugins/one-quick-post/
    This plugin is marked ‘broken’ as of WordPress v3.4.1 so it should be avoided but it’s possible it will be fixed at a later date so I’ve included it in this list. I’m not sure whether it allows non-registered users to post

I have considered paying for Gravity Forms. It provides the features I need in that unregistered users can submit a post via a form on the front end of WordPress BUT – the ability to incorporate Paypal so that users can pay for listings appears to only be available on the expensive (about $200) developers license so I’m not sure this would work in the long term as I would like to eventually make my directory a pay for listing type system.

I’m always reluctant to pay for plugins because often there’s a good free alternative and you never know how long the plugin is going to be supported. If I buy something now and 2 years (and multiple WordPress versions) down the line it doesn’t work – I have eaten in to my very slim or usually non-existent profit margin for nothing!

I’ve also considered using a specific Directory WordPress plugin and browsed through a lot of them BUT most don’t use regular WordPress posts to display the listings, they use a custom post type. I have my directory set up to use regular posts and the basic WordPress category and tag system so I’d rather stick with that than have to re-vamp everything.

I may try some sort of hand coded solution to allow users to post from the front end which would avoid the need to reply on plugins, but this would require users to create an account on the site which is another thing I was hoping to avoid.

(*Note – in the end I did come up with a hand coded solution and users don’t have to log in – see the code example further down the page).

I will continue my hunt for an alternative to TDO Mini Forms and report back here if I find anything useful :)


Update 27th September 2012

It works!

After much tinkering and with huge, huge thanks to this “Posting from front end form” WordPress tutorial and some very helpful posts at StackExchange’s WordPress community – I managed to get a solution working.

This is a working alternative to TDO Mini forms, using a simple custom page template that you can put in to your theme and then assign to any page (or it should automatically assign it if you save the custom page template as page-mypagename.php, where ‘mypagename’ is the name of the page where the form will be displayed)

It doesn’t include all the features that TDO Mini Forms had (see my note about future updates at the end of this post) but this form allows anyone (including guests/unregistered users) to submit a new post from the front end including:

  • the post title
  • the post content
  • selecting a category (from existing categories)
  • adding tags
  • adding custom fields

(*This solution also contains some code for uploading files but that feature doesn’t seem to work. I’ve left the code in but commented it out. You’re safe to remove those bits if you want to)

There’s a downloadable custom page template available here – Download listingsubmissionform.php

or you can just copy & paste this code in to a new file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
<?php
    /*
    Template Name: Listing Submission Form
    */
?>
<?php
// Check if the form was submitted
 
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
 
        // Do some minor form validation to make sure there is content
        if (isset ($_POST['title'])) { 
                $title =  $_POST['title']; 
        } else { 
                echo 'Please enter a title';
        }
        if (isset ($_POST['description'])) { 
                $description = htmlentities(trim(stripcslashes($_POST['description']))); 
    } else {
        echo 'Please enter the content';
        }
 
	$nonce=$_REQUEST['_wpnonce'];
	if (! wp_verify_nonce($nonce, 'new-post') ) die('Well that was naughty.');
 
        $tags = $_POST['post_tags'];
        $customfieldone = $_POST['customfieldone'];
        $customfieldtwo = $_POST['customfieldtwo'];
 
	// You can add more custom fields by replicating the lines above and any other references to customfieldone and customfieldtwo, and changing them to your custom field values
 
        // Add the content of the form to $post as an array
        $type = trim($_POST['Type']);
        $post = array(
                'post_title'    => $title,
                'post_content'  => $description,
                'post_category' =>   array($_POST['cat']),  // Usable for custom taxonomies too 
                'post_status'   => 'pending',               // Choose: publish, preview, future, etc.
                'tags_input'    => array($tags),
                'tax_input'    => array( $type),
                'comment_status' => 'closed',
                'post_author' => '2', 	// Set to 1 for the main admin account as author, provided that is user ID 1
                'customfieldone'    =>   $customfieldone,
                'customfieldtwo'    =>   $customfieldtwo 
        );
        $post_id = wp_insert_post($post);
        wp_set_post_terms($post_id,$type,'Type',true);
	add_post_meta($post_id, 'metatestcustomfieldone', $customfieldone, false);
	add_post_meta($post_id, 'metatestcustomfieldtwo', $customfieldtwo, false);
        wp_redirect( home_url('/listing-submitted/') ); // redirect to this page after submit
        exit();
 
// This bit of code relates to image uploads and it's not working correctly so it's commented out for now
//	if ($_FILES) {
//		foreach ($_FILES as $file => $array) {
//			$newupload = insert_attachment($file,$post_id);
//			//$newupload returns the attachment id of the file that
//			// was just uploaded. Do whatever you want with that now.
//		}
//	}
 
}
 // endIF
 
?>
<?php get_header() ?>
 
            <div id="container">
                <div id="content" role="main">
 
		        <h1 class="page-title">Submit your listing</h1>
 
<!--SUBMIT POST-->
		        <form id="new_post" name="new_post" class="post_work" method="post" enctype="multipart/form-data">
			<?php wp_nonce_field( 'new-post' ); ?>
 
		                <p><label for="title">Title</label><br />
			                <input type="text" id="title" class="required" value="" tabindex="1" size="20" name="title" />
		                </p>
		                <p><label for="description">Description</label><br />
			                <textarea id="description" type="text" class="required" tabindex="3" name="description" cols="50" rows="6"></textarea>
		                </p>
 
		    		<fieldset class="category"> 
			                <label for="cat">Category:</label> 
			                <?php wp_dropdown_categories( 'tab_index=10&taxonomy=category&hide_empty=0' ); ?> 
				</fieldset>
 
<!-- CustomFieldOne --> 
				<fieldset class="customfieldone"> 
					<label for="customfieldone">Custom Field One:</label> 
			                <input type="text" value="" id="customfieldone" tabindex="20" name="customfieldone" /> 
				</fieldset>
 
<!-- CustomFieldTwo --> 
				<fieldset class="customfieldtwo"> 
					<label for="customfieldtwo">Custom Field Two:</label> 
					<input type="text" value="" id="customfieldtwo" tabindex="20" name="customfieldtwo" /> 
				</fieldset> 
 
<!-- This bit of code relates to image uploads and it's not working correctly so it's commented out for now -->
<!--
				<p><label for="attachment">Photos: </label>
					<input type="file" id="attachment">
					<div id="attachment_list"></div></p>
-->
 
				<p>Tags: <input type="text" value="" tabindex="35" name="post_tags" id="post_tags" /></p>
 
<!-- I'm not sure what domande means in the value below, but if I change it to post as you would assume it should be, the form doesn't work -->
				<input type="hidden" name="post_type" id="post_type" value="domande" />
				<input type="hidden" name="action" value="post" />
 
				<p style="text-align:right"><input type="submit" value="Submit" tabindex="6" id="submit" name="submit" /></p>
 
			</form>
 
<!-- This bit of code relates to image uploads and it's not working correctly so it's commented out for now -->
<!--			<script>
			    var multi_selector = new MultiSelector( document.getElementById( 'attachment_list' ), 8 );
			    multi_selector.addElement( document.getElementById( 'attachment' ) );
			</script>
-->
 
<!--SUBMIT POST END-->
 
	        </div><!-- .content -->
	    </div><!-- #container -->
 
<?php get_footer(); ?>

Save the file linked above or copy the code in to a new file and upload it to your active WordPress theme folder, i.e. yourwebsite.com/wp-content/themes/YOUR-THEME/ You may also need to assign the custom page template to your page from the WordPress admin panel.

About the page layout

You will see from the code example above that the form is inside 2 div’s – ‘content’ and ‘container’ – you may need to change this to fit your theme. If in doubt, open some files from your theme (preferably something like page.php or single.php) in a text editor and see what code was used there. You should be able to figure out what to use in your form’s custom page template.

Future updates

I’d like to work on getting the file uploads working in the future and, more importantly for my needs – email notifications when a new post is submitted, preferably one to me as site admin, and one to the person submitting the post (with the email address stored via one of the custom fields in the form).

I will be looking in to this when I get time so stop by at a later date if this is something you need, or leave a comment below and perhaps we can work it out together.

Ok, you’re done!

I hope this has been of help to anyone out there panicking like I have been about TDO Mini Forms not working! It was a great plugin while it lasted but I don’t think it’s going to make a comeback.

This is a good alternative for TDO Mini Forms because it’s built in to your theme instead of using a plugin, so you don’t have to worry about plugins becoming outdated and not being maintained like TDO Mini Forms did.

Good luck with it! Give me a shout in the comments if this was helpful to you or if you have problems with it.