Post comments not allowed if comment metabox removed

Allow Comments in edit post

When building a site for clients it’s nice to clean out the Admin Dashboard screen of some of the unnecessary (and possibly dangerous) sections and checkboxes to avoid distractions when creating or editing their content. WordPress is flexible enough to allow sections, or meta boxes, to be easily removed through the use of the remove_meta_box function. The code can be added to the functions.php file.

One of the meta boxes that can be removed is the Comments or Discussion meta box. This box lives in the lower half of the Edit post screen. It allows you to set the post, or page, to accept or deny comments and trackbacks/pings. I’ve been working on a couple of sites for some clients and it was originally decided not to have comments at the launch. I removed the comments options from the post screen and removed the call to the comment template in the sites theme files.

Then the client changed their mind and would like comment functionality restored. Now, it’s some time into the life of the site and the previously created posts are showing that comments are closed and the client want to add the ability for all posts to allow comments. It is easy to edit the theme files and add back in the “comment_template()” code and that would be that. However, the posts still show “Comments are closed”.

In Settings, Discussion there are no restrictions for commenting so it’s a little confusing that comments are not showing.

After working a little further on this I found the trick, which can be a little time consuming if you have lots of posts. Either edit, or quick edit, each affected post and tick the box that says “Allow Comments”.

Allow Comments in edit post
Allow Comments in edit post

After doing that for each post you should find that normal comment functionality is restored for all posts and for new projects I always try and identify the comment requirements at the outset.

Slow WordPress tag queries

While working on a real estate project I encountered very slow response from WordPress on certain queries. These queries are multiple tag queries in the form:

http://www.site.com/tag/TAG_ONE+TAG_TWO

My application is using WordPress tags to annotate the content and I am providing links to those multiple tag queries throughout the site. Over time and while I was developing the site I noticed the site response getting slower and slower when I clicked on these links and yet there are times when the response was within the acceptable range. My hosting service was also affected and I was seeing high CPU usage when one of these queries was triggered. I decided to investigate.

I bounced between my Apache configuration, my MySQL configuration and the external database I was also querying. I had used the external database in a previous project and I was fairly confident I had not introduced any issues there. The queries I was performing were responding well within acceptable times and using mtop on my hosting console I was seeing WordPress queries hogging the resources.MySQL query

I changed the settings in my MySQL configuration file to increase buffers, heaps, table sizes and more. Improvements were minimal where there were any and in other cases no change. I didn’t think I was doing anything beyond the scope of WordPress (although I always like to learn) so I started searching to see if anyone else was experiencing the same or similar issues.

I found the usual and variable guides on how to speed up WordPress and more about taxonomy queries. I found there were reports of issues after a recent WordPress upgrade – support questions were posted here and here.

Digging deeper I did come across a WordPress Trac ticket http://core.trac.wordpress.org/ticket/16706 and that seemed to be very similar to my issue.  I have been keeping my installations up to date so I could see that I became affected at that same upgrade point. Reading the Trac ticket it seems a resolution to this issue is due in the next release of WordPress (3.2) but I wanted to find out if it really did fix my issue. I upgraded my site to 3.2 beta and applied the patch mentioned in the ticket. The difference is huge and the site response time is much closer to where it should be.

Reading through the Trac ticket the explanation of the issue and the fix is purely down to optimization of the query built when WordPress is required to display information based on multiple categories or tags.

**UPDATE**: It seems that these multi tag queries are operating efficiently after upgrading to WordPress 3.2+ and this hint/tip might no longer be valid or required.

Importing data into WordPress

WordPress Import Real Estate Listings

I’ve been working on a project that requires me to reference an external database of property listings – 106,000 of them – and display these listings in WordPress.

One way I thought of was to create a plugin to read the listing data into WordPress, create a post and custom meta fields (or even a custom post type) with all that listing information and then categorize / tag each post allowing themes to organize the listings as needed. I reviewed that idea didn’t think it was necessary to duplicate the real estate listing data in the WordPress database.

But, if I could create posts with ids that match the listing id then with the help of a shortcode, I could create posts and the shortcode would pull the listing data when a post is viewed.WordPress Import Real Estate Listings

I thought it would work so I reviewed the wp_insert_post function in the Codex and found it had a parameter “import_id”. Now, if I could make that import_id match the real estate listing id I could easily use the categorization and tagging capabilities of WordPress to organize the posts. When populating the WordPress site I query for and retrieve the listing ids from the database, get the id and create the post. Then, just after the post creation process I further query the listings database and create the categories and tags I need assigning them to each post id.

With all the listings referenced in WordPress I can search on and display posts by category and tag or include some external searching capability to get the IDs I want and then use WordPress to display the listings that matched the search.

For the purposes of the project this method worked, but with one side effect. All the menus, pages and other WordPress elements are numbered like the posts. So, at some point, there may be a clash between a numbered menu item and a real estate listing with the same id but I’ve yet to hit it.

Adding Child Theme filters and Twenty Ten

Working on a child theme project for a client I found that my filter modifications for both ‘excerpt_length’ and ‘excerpt_more” were not being processed. My child theme is based on Twenty Ten and the filters I was using had already been filtered by the parent theme. So, I had added my custom filters and the Twenty Ten filter removal code to my child themes functions.php.

However, these custom filters were not being actioned. To help me debug what was happening I even added PHP error logging to check the return values from the remove_filter functions and that proved the filters were not being removed prior to mine being added but I still couldn’t work out why.

Finally by searching the WordPress forums I came across this post and read the reply from lordarkad. It made sense. In my child theme I had to wait for the parent themes setup to finish before declaring my filter changes and this made more sense because the child themes functions.php is loaded prior to the parent themes functions.php. So whilst these filters showed in the parent theme code I was removing them before they had been applied and, of course, then the parent themes functions.php was applying it’s filters in the theme.

To fix it I followed lordarkad‘s comments and created my filter additions in a child theme setup function. Then I added that function to the “after_setup_theme” action so my function is called after the parent theme has complete setup and then my filters are applied correctly.

This is a snippet of what I ended up with:

add_action( 'after_setup_theme', 'mytheme_theme_setup' );

function mytheme_theme_setup() {
	if (!function_exists('mytheme_new_excerpt_length') ) {
		function mytheme_new_excerpt_length( $length ) {
			return 20;
		}
	}
	remove_filter( 'excerpt_length', 'twentyten_excerpt_length' );
	add_filter( 'excerpt_length', 'mytheme_new_excerpt_length' );
etc...
} // end of mytheme_theme_setup

WordPress 3.0 and flush_rewrite_rules

I thought I would document this experience I had when upgrading some sites to WordPress 3.0.

After WordPress 3.0 came out I took some time to upgrade blogs I manage and was impressed how well the upgrades fared. No issues, fair warnings and ultimately upgraded sites. However, on one of my development sites, after the upgrade, I noted an error about “error re-declaring the function flush_rewrite_rules()”. I knew, for this site in particular, that I had written some custom code to rewrite the urls and in this case I had innocently included a function called “flush_rewrite_rules()”. Coincidentally, in WordPress 3.0 a new core function has been created called “flush_rewrite_rules()” and because that now exists my function is interfering with this and required fixing. The fix, in this case was to rename my custom function and test and I thought nothing more of it. (I know – I should have participated in the beta test).

I didn’t think anything of it after that until I was asked to assist with another clients site. This time the client had innocently upgraded their site to WordPress 3.0 and encountered a white screen with the long PHP error referencing “error re-declaring the function  flush_rewrite_rules()”. The difference this time was that it was in a plugin causing the issue and as such the site was rendered inaccessible.

For this client I connected via FTP and downloaded the plugin code, searched for the function named  “flush_rewrite_rules()” (along with any references to it) and renamed it through the code. After uploading the change the site was restored back to normal.

A simple fix for this site but also a simple lesson in heeding the warnings / suggestions given by the WordPress upgrade tool when upgrading to WordPress 3.0

WordPress, breadcrumbs and wp_reset_query

I came across weird behaviour recently relating to breadcrumbs. In a site I was working on the breadcrumb functionality (provided by a plugin) was not consistent – it was incorrect on single post pages but correct on category pages. It didn’t make sense. There are not many options for the breadcrumb plugin so it was difficult to see the fault lying there. I did notice that the site used a custom menu and that code was used on all pages. So, my troubleshooting took to dissecting the header and then menu code.

In the header was a call to the custom menu and in that file each menu element was created with a new WP_Query to get a subset of links / pages. I saw that the syntax to fire off each query was as I would expect  but I did notice that the $wp_query object wasn’t saved before these additional queries and subsequently restored afterwards. So, I figured that was messing things up and added that code in. No change. Now, I went a little deeper and added code in the menu to display the current categories after each menu (the categories are used in the breadcrumbs). Now, it was making sense. So, the categories were being messed up after each query in the menu code and that affected the single post pages.

The fix was simple and one line of code at the end of the custom menu code before returning to finish the header code:

wp_reset_query();

And, as per the codex for wp_reset_query() it is recommended to be used after a custom query. The breadcrumbs were now working as expected.

What to do if your blog has been hacked

I’ve recently worked on a couple of blog sites that had been victim to malicious activity. The evidence was different in both cases and for one consisted of search results that promoted drugs that enhance performance. And we’re not talking about blog performance 🙂 For both sites there was hidden text and html code in all the posts containing offsite links to seeming random and unrelated websites. The job I had was to remove any sign of malicious code and sanitize the sites. Additionally I was getting browser warnings indicating malware was present on the page I was navigating to. The warnings suggested I don’t continue lest my PC be infected further.

Investigating a hacked WordPress site

With WordPress there are a few good ways to speed up the job of troubleshooting a hacked site and speed may be of essence with something like this. I asked the client when there were first signs of the malicious content or behavior – believe me it’s actually very useful to know the exact date & time you first experience the issue as you’ll see later. So, if that time information is not available or cannot be remembered viewing the server error logs promptly could give you some more information. Armed with that information and presuming you can get into the site’s admin dashboard you try the following fairly standard actions to help uncover the culprit and mitigate further issues:

  • Disable all plugins
  • Switch to default theme
  • Use Theme Authenticity Checker

The Theme Authenticity Checker plugin does a quick scan of all installed themes for unnecessary code – typically this code consists of statements or functions like “eval( blah blah);” code injected somewhere in any of a themes files. Pay attention to anything TAC highlights – perhaps removing un-needed themes. For any theme that is highlighted as containing potentially malicious code you’ll need to edit the affected file or remove and re-install the theme files from the originals. That’s a drag if you’ve made theme modifications but it means you can revert to being back online. In one of the cases here I was re-enabling the plugins one at a time and I found that a plugin was causing one issue (preventing the blog from displaying) and by removing it from the plugins folder I could continue.

However, perhaps your blog site is non-functioning and you can’t get into your site’s admin dashboard? Well, now’s the time you use FTP or SSH connect to the server hosting the website. Remember I said how useful it is to remember the date & time you first noticed the hacking / issue? Well, here’s where you can navigate to the following folders and look for files that have been changed around the same date/time:

  • wp-content
  • wp-admin
  • wp-includes
  • wp-content/themes/*
  • wp-content/plugins/*
  • the folder above wp-content – sometimes public_html or public

* The above folder list is not exhaustive but typically this is where the malicious code is to reside

In each of these folders look for other folders or files that have recently been created. These are sure indications that modifications have been made and you need to target those files or folders.

Fixing a hacked site

After searching in the above folders on the clients sites here’s what I found:

  • A folder called “backup” and in there was malicious file  “backup-loader” that had code to display an authentic looking message on the WordPress dashboard.
  • An include statement at the top or within the index.php
  • A file/folder combination called “__notes/notes” that was included in index.php
  • Malicious code in wp-includes/theme.php
  • Malicious code in functions.php – an eval statement that referred to a setting in the wp_options database
  • Malicious javascript code in the wp_options database

With FTP you can download, use a code editor, and then upload fixed files. With SSH using a code editor directly to removing the malicious code in the php files. Identifying the code to remove was pretty easy as often the code segments looked out of place and therefore easy to remove and test. The wp_options code required the use of a MySQL database client like PHPMyAdmin to manually edit the table and remove the code and the related entry / record to prevent re-infection.

Cleanse and Sanitize

I said before that one of the effects of this hacking was that all the posts and pages had been injected with additional HTML code. Again with a MySQL client I looked through the blog database tables and found that also infected were the “revision” records for each affected post or page. Each malicious link was hidden from view with a CSS “style display:none” command and each link was injected in random locations within the post content. This made cleansing a labor intensive job (I could have possibly written some code to scan and remove but time didn’t permit) as I had to manually edit each post in the database – copying and pasting to a code editor and then pasting it back into the database, view the page or post, view the source to ensure the malicious code was gone.

Check in with Google Webmaster Tools as well to see if Google has identified malware on your site. If it has then follow it’s suggestions as to how to get the information Google stores about the site updated to reflect the current, non-malware, site.

WordPress Security Review

Once your site is cleansed and working you might take a look at further locking down access to reduce the chances of this happening again. Changing your admin and FTP passwords regularly is always good practice but there are more hints and tips in my WordPress Security post.

I successfully managed to fix these sites using the techniques described above – if you ever experience similar incidents then this short guide will help you. I do recommend now after all of this, taking a database backup and upgrading to the latest version of plugins and WordPress as soon as possible.

Thoughts, ideas always welcome in the comments.

*Update* After I completed this project I came across an updated version of Exploit Scanner – more information here. A useful tool to assist in fixing a compromised WordPress installation.