WPMU DEV's Blog - Everything WordPressWordPress Tutorials - WPMU.org http://premium.wpmudev.org/blog The WPMU DEV WordPress blog provides tutorials, tips, resources and reviews to help out any WP user Fri, 01 Aug 2014 06:18:32 +0000 en-US hourly 1 http://wordpress.org/?v=3.9.1 Making Your WordPress Images More Than Just Eye Candy http://premium.wpmudev.org/blog/making-your-wordpress-images-more-than-just-eye-candy/ http://premium.wpmudev.org/blog/making-your-wordpress-images-more-than-just-eye-candy/#comments Thu, 31 Jul 2014 12:00:00 +0000 http://premium.wpmudev.org/blog/?p=131036 Why do you include images in your WordPress posts?

Is it just to break up the text, make it look a bit prettier, a bit more inviting? Or are they an integral part of the story you are trying to tell?

Here’s how to elevate your WordPress images from eye candy to storytelling juggernauts with descriptions that overlay on click, automatically appear when the image is visible or form a CSS-inspired image maps.

Featured image
Make your images an integral part of your storytelling

I’ve mentioned The Brief before, the tablet-based digital magazine from the Innovation unit of the Australian public broadcaster, the ABC, when I wrote about horizontal-scrolling content.

What’s fascinating about the product is that every issue seems to incorporate yet another novel way to deliver content. The Brief’s treatment of images is the inspiration for this post and whilst I’m only going to scratch the surface, it does show just how unnecessarily boring and static traditional web content can be.

I’m going to show how to better integrate your images into your content by providing on-image information.

Using a small plugin, jQuery and CSS, we’ll add the capability for your WordPress site to:

  • Overlay a description on an image by clicking on the image
  • Create a CSS image map to allow displaying of multiple items of information by clicking on hotspots in the image
  • Automatically overlay a description on an image when the image is scrolled fully into view in the browser window

How It Works

The solution makes use of the caption shortcode so obviously the images have to have captions.

Extra attributes are added to the img tag to describe how the information is to be styled, the effect to be used to reveal the information and how the reveal is triggered.

A simple WordPress plugin adds the necessary scripts and CSS to the page output using the wp_enqueue_scripts action and also hooks into img_caption_shortcode to rewrite the HTML adding a description if necessary.

For the sake of compatibility I’ve used pretty much the same HTML as the default shortcode but really this solution should use the HTML5 figure and figcaption tags.

That’s all that takes place in WordPress itself; the rest of the solution is client-side, where a small script sets up event listening and handling. The inview trigger is provided by the Inview jQuery plugin, so a big thank you to author Christopher Blum.

The CSS is all fairly straight-forward but it’s probably worth pointing out that the image wrapper, div.wp-caption has its position set to relative whilst the description wrapper, div.wp-image-description is set to absolute. This makes it possible to keep the description within boundaries of the image.

Walking Through The Examples

Let’s walk through an example of each of the 3 techniques. Before doing anything else, though, install the plugin.

A Simple Overlay

Screengrab of an image with the description overlayed
Click on the image to reveal the description; click again to hide

This is the simplest technique and so is a good introduction.

First, jump into the WordPress Admin interface, go to Media, select an image to edit and some content to the Description. Make it of a reasonable length so that you’ve got something to work with.

Now go and create a post, click on Add Media, select that image you just edited and select none for the link. Insert the image.

Swap to Text view and on the <img> tag add the following attributes:

  • data-desc-style=”box-overlay”
  • data-desc-reveal=”fadein”
  • data-desc-trigger=”click”

Publish the post and view it. Clicking on the image should display your description in a 75% opaque box that’s probably the full-width of the image.

Go back to the post edit screen and add another attribute:

  • data-points=”10px,10px,60%”

Your caption shortcode should look something like this:

Click Update, refresh the post view and click on the image. This time you should find that the box only goes two-thirds of the way across the image and is slightly indented.

If you supply the data-points attribute, then the client-side script uses it to create a style attribute (top, left, width, height) which it then adds to description <div> thus overriding the box-overlay styling.

Not bad. Let’s get a little more complicated and build an image map.

Building A CSS Image Map

Screengrab showing the hotspot and the information displayed
Hotspots on the image control the information displayed

Remember the old HTML image maps? You could define hotspots on an image that could be hyperlinked. Well, this is providing the same sort of functionality but with CSS and jQuery and we are just going to use it to display different information depending on where the visitor clicked on the image.

Go to Media and pick a different image and edit it. Add some content to the Description but this time wrap it in a <div> as follows:

1
<div data-points="1%,1%,100px,100px">Your content....</div>

The data-points attribute defines the hotspot: in this case you’ll find it near the top left corner of the image. It’s very much trial and error to get the hotspot in the right place but doesn’t take long to get the hang of. I would recommend using % for top and left, otherwise you’ll find that any scaling of the image will throw out your hotspots.

Add as many hotspots as you like, coded exactly as above.

OK, back to the post, add the image via Add Media (making sure there’s a caption and the image is not linked) and then in text view add the following attribute to the img tag:

  • data-desc-style=”map”

Here’s the caption:

Update the post, refresh the view and scroll to the image. Now as you move your mouse over the image, the hotspots will show up as you mouseover. Click on a hotspot and the description will appear in the box-overlay at the bottom of the image.

This is a simple but really engaging technique. it works best for images where you’ve got a lot of points of interest. For example, The Brief used it to provide short bios on 7 new politicians by hotspotting their faces.

Those two examples were both based on the reader taking action but what about an automatic reveal?

Revealing A Description When The Image is In View

Screengrab showing the description on a fully viewable image
Description is only displayed when image is fully in view

So the idea here is to use the same box-overlay as the first example but for it to automatically appear when the image has fully scrolled into view (i.e. both top and bottom are visible).

It’s really like a lazy load but instead of loading the image, we are displaying a description, thanks to the Inview jQuery plugin.

If the image you used on the first example is a reasonable size then let’s reuse it; if not set up a new image. Remember, the image should be of a size where the whole image can fit in the viewport.

Once you’ve got the caption shortcode in your post, go to the Text view and ensure the <img> tag has the following attributes:

  • data-desc-style=”box-overlay”
  • data-desc-reveal=”fadein”
  • data-desc-trigger=”inview”
  • data-points=”10px,10px,60%”

The caption looks like this:

As you can see, it’s very similar to our first example, the only difference is that the trigger is now inview rather than click.

Update the post, refresh the post view and start scrolling. When the image first comes into view, the description should not be visible but as the bottom of the image comes into the viewport, the description will fade in.

If you keep scrolling (so that the top moves outside the viewport) then the description will disappear.

Extending The Solution

This solution is just begging to be extended, especially the reveals. The value of the data-desc-reveal gets added as a class to the div.wp-image-description when the trigger takes place, so adding new transitions is just a matter of adding the appropriate class.

There’s no rocket science here just some simple but effective techniques for elevating your images from eye candy to an integral component of your storytelling.

]]>
http://premium.wpmudev.org/blog/making-your-wordpress-images-more-than-just-eye-candy/feed/ 1
How To Stop Your WordPress Intranet Becoming An Unmanageable Mess http://premium.wpmudev.org/blog/how-to-stop-your-wordpress-intranet-becoming-an-unmanageable-mess/ http://premium.wpmudev.org/blog/how-to-stop-your-wordpress-intranet-becoming-an-unmanageable-mess/#comments Mon, 28 Jul 2014 12:00:00 +0000 http://premium.wpmudev.org/blog/?p=130546 Given its popularity, it’s only natural that organizations should look to WordPress as a potential intranet solution.

It’s far too easy, however, to get carried away and load up a site with every plugin imaginable and end up with an unmanageable mess.

So how you can avoid disaster and ensure that your WordPress intranet is fit for purpose, is solving your organization’s problems and is not going to have co-workers muttering about you over the water cooler?

Promo image
Avoid the urge to install every plugin imaginable and keep it simple

Intranets Are Different

Intranet’s are curious beasts and building one requires a very different approach to that used to build a public site.

The good news is that both the owner and the audience are clearly defined and easily accessible. The bad news is that both the owner and the audience are clearly defined and easily accessible.

Everything you do as the “intranet builder” will be done in front of a good many more people than when building a public site (whose audience you rarely, if ever meet), especially if you work in the organization concerned. Whilst triumphs will largely go unnoticed – such is life in web projects – mistakes will be on view to a large audience who potentially all have access to you. There will be nowhere to hide.

Of course, it’s not all bad news. You are also dealing with a controlled environment where there should be no surprises and that you may be able to influence. For example, you’ll have a pretty good idea of the operating system and browser that visitors will be using to access the site and may well not have to worry about supporting a wide-range of different set-ups.

(Although perhaps if the organization in question is still using IE7 or worse, IE6, you might want to reconsider!)

A clearly defined audience means that it’s relatively easy to get wants and needs but also means that it’s also easy to get swamped with requirements as every employee produces a list of every feature and function they’ve ever needed resulting in the dreaded and potentially debilitating Scope Creep.

The major driver for this creep is that intranet development is generally underpinned by an inclusive approach. In theory, such an approach makes sense – you have a defined and accessible audience so why not go straight to the source and find out what people want?

The issue is that you will be the only person on the project thinking about that organization as a whole: everyone else will be thinking about themselves first and foremost – what do I want the intranet to do? – and perhaps their immediate team or department. But certainly not the whole organization and why would someone in Accounts care about the Sales team being able to share product specs?

A key component of building an intranet is being a feature wrangler. Not an easy job as there’ll be plenty of them and saying “no” to people that you may deal with on a regular basis is difficult. Might as well realize now that you cannot and will not please everyone.

A final difference, and perhaps the most significant, is that intranets are much harder to place a value on (and consequently calculate a return-on-investment) than public sites. Intranets are nebulous by nature (the term doesn’t really mean anything other than an internal website) and unlike their public-facing cousins don’t always have a clearly defined business purpose with goals and plenty of analytics to check that the site is delivering.

Things To Consider

When it comes to designing your intranet solution, there are a number of considerations.

Difficulty increases exponentially with number of plugins

If you’ve already built a few WordPress sites then you’ll be (perhaps painfully) aware of the pitfalls of loading up your installation with a million-and-one plugins:

  • Every plugin has some management overhead, so more plugins means more overhead
  • Greater chance of plugin conflict, more plugins means more code and the chance that naming conflicts or simply functional conflicts (one function undoes the work of another) will arise
  • More interfaces to integrate and make consistent, this is perhaps the biggest issue when building a site, that each plugin that creates output will need to be integrated to a common look and feel
  • More back-end entry data screens, each with its own particular nuances and behavior when it comes to the user interface

The aim, therefore, is to have as few plugins as possible and for those plugins that you do use to be well-coded with a good track record for support and updates.

Front-end v Back-end Content Creation

The more users you can involve in creating content the more successful the intranet will be. As well as going a long way to ensuring that the intranet contains a constant flow of new and updated content, a large cohort of users spreads feelings of ownership.

How content is created is, therefore, a key consideration. Do you allow users access to the admin interface? What level of access do you give them? Or do you avoid the admin interface altogether and keep content creation only in the familiar front-end (perhaps using Gravity Forms)?

You’ll need to think about the users, the likely content creators and how important it is to distribute the content creation process (hint: very important).

Single Install v Multisite

Even the smallest organizations will likely have multiple projects on the go, whilst larger organizations throw teams and departments into the mix.

A key initial consideration is whether to have a single installation or whether to go down the multisite path and allow individual teams and projects to have their own subsite.

Be very careful. It’s easy to get carried away and go for multisite but, as with plugins, every site is adding to the maintenance overhead. Think very hard about the implications of multisite and whether there are the time and resources to manage a network. If there isn’t, then don’t suggest it!

That said, there are clear-cut scenarios where multisite works well. Keeping in mind that single sign-on is an absolute given, then an intranet that consists of a blog, a knowledge-base and a shared calendar is likely to be better delivered as a multisite with each function operating in its own domain (and the main site acting as an aggregator) where it can run with its own theme, rather than trying to shoehorn all the functionality into the one site.

Internal v External Hosting

This is usually quite a vexed question. Likely, you will be the most ambivalent about whether the intranet is hosted internally or externally (you might actually have a preference for external simply because it might mean you can get something set up with a lot less hassle and lot quicker than waiting on an internal IT department) as your stakeholders grapple with fears about security conflicting with the desire to make the intranet readily available to those out-of-the-office.

Your role here is to advise. List the pros and cons of each approach and highlight any requirements that might be compromised or require tweaking by either approach.

Never play down the security aspect. It’s always better to assume that a breach of an externally hosted site will occur and therefore plan the content it will contain accordingly.

WordPress Is A CMS Optimized For Blogging

It’s disingenuous to call WordPress a blogging tool given its full-featured code base and extraordinary extensibility but it is a content management system that is optimized on a blogging content model and trying to implement anything other than a blog does attract a higher degree of difficulty.

When considering requirements it will always pay-off in the long-run to go for the solution whose content model is closer to the blogging model. For example, the best knowledge-base solutions (and there are some exceptional ones out there for WordPress) leverage the blog content model of post, category and tag and provide a far better experience than the wiki plugins.

WordPress Only Or Best Of Breed?

Which brings us to the other big question: should you base your solution entirely on WordPress or should you use best of breed applications and implement single sign-on across them (either via a bridge or perhaps LDAP given this is an internal application)?

If you need to provide a wiki, it would be hard to justify using a wiki plugin for WordPress over a purpose-built wiki application such as MediaWiki.

Clearly, though, increasing the number of applications, just like increasing the number of plugins, adds additional overload to the management of the solution, perhaps even more so given that this means another application to master.

Using just one application, WordPress, is clearly preferable and so the best course of action will ultimately be to suggest solutions that you know are appropriate for WordPress by paring back the requirement to its basic need. A wiki, for example, is not a requirement it is a solution: the requirement is for knowledge sharing and that could be achieved via any one of a number of WordPress-friendly knowledge-base or question and answers plugins.

Building A Solution

Collect Problems Not Requirements

When defining the solution’s needs, then, don’t gather requirements gather problems and issues.

If you gather requirements, you’ll find that you’ll end up with a list as long as your arm containing every feature and function that someone has ever felt they had the need for.

Problems and issues are harder to articulate and so what you’ll find that people are really motivated by the biggest pain points. This will automatically filter out a lot of the nice-to-haves, the one-offs and the just plain weird leaving you with a list of bona fide problems that need solving.

That filtering in itself might be justification in itself to focus on problems but what you’ll also find is that solving problems is a lot more fulfilling for you, makes the cost of the intranet project much easier to justify and delights users far more than simply meeting a request.

Scenario-driven Development

When you’ve got your list of problems, you’ll need to a create a scenario for each one that describes the user actions in an ideal scenario. For example:

Scenario Sales.1 – Messages to field sales staff

Current: Sales Manager communicates with his field sales staff via email. Difficult to track feedback as some staff reply-all and some just reply to sender. Difficult to keep track and access previous messages. Managing email distribution list a chore given sales turnover quite high.

Desired: Field sales staff comments are available to all field sales staff to view. Previous messages can be searched. Access to messages controlled as part of employee join / leaving process.

No doubt your brain is already coming up with a solution – clearly this is a straight-forward blog – and it’s fine to document this somewhere, but there is no need to share this with the Sales Manager or a Field Service Person. All you need to agree with them is the scenario.

One option you do have is to go more detailed. The above scenario could actually be split into at least 3 smaller, more specific scenarios, depending on whether the Sales Manager (SM) or a Field Sales Person (FSP) is performing the action:

1. SM sends message to FSP
2. FSP comments on message (variation: adding photo to comment)
3. FSP searches for older message

Thinking About Project Velocity

Project velocity is an agile term but is useful for any project regardless of the project methodology.

Critical to the success of virtually any project is to get early wins. Not only does that mean that you are solving problems but you’ll also be instilling confidence in you, the project and the intranet in general.

Project velocity, then, needs to be highest at the beginning of the project and that means carefully selecting those scenarios that are either easy to solve or related or preferably both. You might grade the scenarios on degree of difficulty before you put your project plan together but making sure you can release relatively quickly after the project starts is imperative to its success.

It won’t take long before news of an update to the intranet ceases to be news and that’s when you can slow down and tackle the thornier scenarios on your list.

Giving Yourself A Shot At Success

Intranet projects can be pretty daunting for all the reasons outlined so far but mostly because you are probably sitting amongst your users and you effectively have nowhere to hide if it all goes wrong.

So, here’s some tips to help you maximize your chance of success:

Keep It Simple (Don’t Shoot Yourself In The Foot)

This is the most important tip and by some margin because too many projects fail to live up to expectations simply because those implementing it make it unnecessarily complicated.

Your job is to find the simplest solutions possible to allow for the scenarios you have documented: nothing more, nothing less.

Don’t Make Decisions Alone – Use A Working Group

In any organization, no matter what the size, you’ll get competing priorities and decisions will have to be made that will leave someone feeling hard done by.

Don’t make those decisions by yourself. Depersonalize those decisions by putting together a small working group and have them make the decision. It’s a useful tactic to put the loudest critic on the working group – it’s amazing how collegiate such people can become when given the responsibility to make decisions for the organization as a whole.

Prioritize Quick Wins

We talked about project velocity earlier and it’s a real boost to a project to be able to get an early release out there to show that it’s really happening. Not to mention you’ll be solving problems as you go.

Multiple releases covering a distinct set of scenarios will bring those quick wins and stand the project in good stead.

Be Transparent About Progress

Your first task should be to create a blog for the project and post regularly and honestly about what’s happening. If something is going to be late, or a scenario has been moved to a later release then tell people and the sooner the better.

Have A Process For Assessing Last Minute, Out-of-the-blue Scenarios

One of the great spanners in the wheels of project management are those last minute scenarios that appear unexpectedly and almost inevitably are of drop-everything-else importance.

These decisions need to referred to your working group who should use a formal change management process to assess the impacts, costs and resource requirements of accommodating the request. Many requests simply end up not making it through the process as they tend

Don’t Promise The Moon

If you are going to maintain project velocity then you have to make sure that your deliverables are realistic, so don’t raise expectations by promising too much. It’s far better to find that your release was actually much easier than you anticipated and that you are ready to go earlier than you thought than to delay because you have over-promised, especially in those early releases.

Do a good job up front and you’ll find you’ll be cut a lot more slack with any subsequent releases that overrun.

Never Underestimate Training / Support Requirements

When planning releases it’s too easy to look at the project as simply a technical one: there’s a problem, here’s a solution, next!

Every time you introduce new functionality, you are going to need to train your users and support them. Whether it’s a screencast or a full-on demonstration, you need to make provision in your plan for creating training material and providing support.

Are Turnkey Solutions A Shortcut?

Simple Intranet is an turnkey intranet solution where for $95 (10 users), $195 (100 users) or $295 (unlimited users), you can implement an intranet quickly and easily with a host of features provided by base plugin and 23 additional plugins.

The list of features is pretty impressive and the cost relatively small and if you are in the market for a WordPress intranet then you should check out the demo.

However, turnkey solutions are not a magic bullet:

  • They implement a lot of functionality in one go. This truly is a big bang approach and the training and support requirement will be an order or magnitude greater than a multiple-release strategy. If nothing else, you’ll need to learn how the various components work yourself before you can train your users.
  • They don’t solve all your problems. Turnkey solutions have to pick the problems to solve and will therefore adopt a particular view of what an intranet will look like and how it should function. The appropriateness of the solution, and therefore how successful it will be, will depend on closely the turnkey solution’s view correlates with your own.
  • Customization may break the upgrade path. If you need to customize the solution, then you run the risk of future upgrades conflicting with your customizations making upgrading difficult or perhaps even impossible.

By far the best way to implement a turnkey solution is not to customize any functionality at all – just stick to the theme and general look and feel. This maintains your upgrade path and will make managing the installation and getting support from the vendor much easier.

The risk you run in taking such an approach is that too many of the existing problems remain unsolved.

The 3 Essential Features For A Highly Effective WordPress-Powered Intranet

Having said that every intranet is unique and you need to build it to solve the set of problems that you’ll identify in the planning stage, there are 3 essential features that you can keep in the back of your mind when fleshing out a solution.

P2-powered Blog(s)

Intra-organization blogs can be a quick and easy way to boost communication for projects and teams. P2 was built by Automattic and is still the leading collaborative blogging theme and is used, among others, by WooThemes and us here at WPMU DEV.

The P2 Guide provides a good introduction to the theme as well as listing derivative themes and useful plugins.

P2 is high on simplicity and low on training requirements and is a worthy core of any WordPress-powered intranet

Theme-driven Knowledge Base

Virtually every intranet will require some form of knowledge sharing. A wiki might seem like a good option but the wiki implementations for WordPress are generally not fantastic and although MediaWiki might provide the ultimate wiki option, you should try and steer clear of the multiple application pathway.

A better solution is to look at one of the knowledge base themes which will turn a WordPress blog into a fully-fledged knowledge repository.

These are premium solutions but as is usual with WordPress, premium is hardly going to break the bank, and some of the themes are very polished.

E-Forms With Gravity Forms

No organization is complete without a plethora of forms to be filled in: leave forms, travel forms, purchase requests, etc.

Moving these forms online can be a quick win of substantial benefit and when it comes to WordPress forms, the plugin of choice is Gravity Forms.

Gravity Forms has the flexibility to build virtually any type of form, including multi-page forms, and should be able to cover almost any requirement.

The only missing feature appears to be routing – if someone knows of a routing / approval / workflow add-on for Gravity Forms then let us know in the comments.

Ultimately, Success Is Down To How Not What

If you came here looking for a sketched-out solution for an intranet then no doubt you are disappointed.

The point is, there is no single solution – an intranet has to be designed to solve the problems of a particular organisation and so there is no one size fits all.

It’s also far too easy to overcomplicate a solution by adding plugin after plugin to provide functionality and features that no-one wants or needs.

Simplicity is the key. If a P2-powered blog (or a network of P2 blogs) will solve 80% of the identified problems then don’t try to make it any more complicated than that. Get that network up and running, get those quick wins and then move onto the next set of scenarios.

Implementing WordPress, installing themes and configuring plugins is not rocket science and almost anyone can do that. In an intranet project, the value you add is in listening to your users, helping them articulate their problems and then identifying the right components to provide the simplest solution to implement, to use and to manage.

The what is certainly important. But the how is critical.

]]>
http://premium.wpmudev.org/blog/how-to-stop-your-wordpress-intranet-becoming-an-unmanageable-mess/feed/ 0
How to Quickly Remove WordPress Widget Titles http://premium.wpmudev.org/blog/how-to-quickly-remove-wordpress-widget-titles/ http://premium.wpmudev.org/blog/how-to-quickly-remove-wordpress-widget-titles/#comments Sun, 27 Jul 2014 15:30:00 +0000 http://premium.wpmudev.org/blog/?p=130934 Recently, I was adding widgets to the footer of a WordPress site I was putting together and the widget titles just didn’t look right with the theme. The Twitter widget I was using didn’t need a title – it was obviously displaying the latest tweet.

Unfortunately, there isn’t an option in WordPress to disable widget titles (now that would be a handy little feature), but there are ways and means of getting around it.

In today’s Weekend WordPress Project, I’ll show you how to stop widgets displaying titles on your website.

Widget titles
Hide widgets titles so they don’t display on your website.

Hiding WordPress Widget Titles

For this tutorial, we’re going to use the Remove Widget Titles plugin, available for free in the WordPress Plugin Repository.

This simple plugin remove the title from any widget that has a title starting with “!”.

For example, if you want to remove the title from the Search widget, add an exclamation mark:

Search widget
Remove the title from the Search widget.

And you can turn this:

Search
Search title.

Into this:

No search
No search title.

The great thing about this plugin is that you can still include titles for your widgets in the backend, allow you to quickly distinguish them in the widgets interface without having to open them.

]]>
http://premium.wpmudev.org/blog/how-to-quickly-remove-wordpress-widget-titles/feed/ 2
5 Awesome Free WordPress Shortcode Plugins http://premium.wpmudev.org/blog/5-awesome-free-wordpress-shortcode-plugins/ http://premium.wpmudev.org/blog/5-awesome-free-wordpress-shortcode-plugins/#comments Sat, 26 Jul 2014 15:30:46 +0000 http://premium.wpmudev.org/blog/?p=130297 Shortcodes provide an easy way to add custom content to your site. Whether you want to add tabs to a page or buttons to a post, shortcodes let you quickly insert elements you regularly use.

WordPress introduced the shortcode API with the release of WordPress 2.5 six years ago. Many themes and plugins (including many of our own) use shortcodes to allow users to customize their sites and display content where they choose.

In today’s Weekend WordPress Project we’ll look at five free options for adding shortcodes to your site.

Shortcodes Ultimate

shortcodes-ultimate

Shortcodes Ultimate is the most popular shortcodes plugin in the WordPress Plugin Repository with more than 780,000 downloads. It promises to “supercharge your WordPress theme with a mega pack of shortcodes” and it delivers.

Easily create buttons, tabs, boxes, sliders, responsive videos and other elements.

This plugin features a shortcode generator, 50+ shortcodes, responsive design, CSS3, custom CSS editor with syntax highlighting, custom widget and rich API.

There are also premium add-ons – extra shortcodes (15+ extra shortcodes), additional skins (60+ skins) and a shortcode creator for creating custom code.

WordPress Shortcodes

wordpress-shortcodes

WordPress Shortcodes is another popular option, with almost 150,000 downloads in the WordPress Plugin Repository.

Create SEO-ready tabs, sections/accordions, buttons, links to content, author cards, lists, layouts and other elements.

Other features include 26+ shortcodes, shortcode editor with instant previews, and customize the looks of shortcodes with custom CSS.

Shortcoder

shortcoder

Shortcoder allows you to create your own custom shortcodes with HTML and JavaScript for use on posts and pages.

This easy-to-use plugin is particularly handy when adding ads to your site, or even embedding videos and other media.

Features into a shortcode editor and the ability to globally disable shortcodes.

Easy Bootstrap Shortcode

easy-bootstrap-shortcode

Easily add Bootstrap style to your site with Easy Bootstrap Shortcode.

This Bootstrap 3.0.3 compatible plugin features 500+ Font Awesome and Glyphicons icon fonts, the ability to add icons to the editor, custom CSS, new sidebar widget and options to give custom shortcode prefix.

Simple Shortcodes

Simple Shortcodes

If you’re after a simple shortcode plugin without the bells and whistles, then Simple Shortcode is for you.

This easy-to-use plugin plugin adds a new icon to the visual editor that lets you insert commonly used elements like notifications, columns, buttons and tabs to your posts and pages.

While Simple Shortcodes was made specifically to work with themes from simplethemes.com, it still works with any theme.

]]>
http://premium.wpmudev.org/blog/5-awesome-free-wordpress-shortcode-plugins/feed/ 3
How To Add A New Yorker Style Header To Your WordPress Site http://premium.wpmudev.org/blog/how-to-add-a-new-yorker-style-header-to-your-wordpress-site/ http://premium.wpmudev.org/blog/how-to-add-a-new-yorker-style-header-to-your-wordpress-site/#comments Fri, 25 Jul 2014 12:00:00 +0000 http://premium.wpmudev.org/blog/?p=130889 The New Yorker does it and so does The New York Times, so perhaps it’s just a Big Apple thing.

But changing and then fixing the page header as the reader scrolls up seems like an entirely sensible approach to not only maintaining branding but also to providing consistent and easy access to the primary navigation.

In this post, I’ll show you how to do the same with your WordPress site, even if you don’t live in New York.

Post featured image
Sticky dynamic headers – not just for New York types!

There’s been quite a bit of coverage about the recently relaunched The New Yorker website in the WordPress community because, of course, it is powered by your favorite open-source content management system.

The design is actually quite conservative but one of the features I really like is the treatment of the header. When a page first fires up, this is what you see:

The New Yorker header on initial display
Initial header is big and bold – large title and space for advertising

A full-header (there’s also a banner-ad above the title) with a large title and the main navigation. As the header scrolls off the top of the screen though, it changes and fixes itself to the top of the page:

The New Yorker header after scrolling
The sleek, space saving, sticky menu allows branding and easy access to navigation

The title font-size is reduced to minimize the space, a shadow border is added to give the impression that the header is sitting on top of the page and the same main navigation is easily accessible. A benefit to both the publisher (permanent branding) and the reader (easier access to the main navigation than a scroll-to-top function), it works particularly well on the longer-form pieces that both these sites regularly publish.

Adding A “Sticky” Header To Your WordPress Site

Adding the feature to your own WordPress site is relatively easy thanks to the myStickymenu plugin. However, the plugin is preset for Twenty Thirteen and just for the menu, not the whole header, so if you are using any other theme then you’ll need to make some refinements.

So, let’s walk through an example using the Bosco theme – it has a really distinctive header – to see just what needs changing. To follow along, fire up a test site, install the myStickymenu plugin (but leave the settings as they are) and the Bosco theme and let’s get started.

The default Bosco theme header looks something like this:

Screengrab showing the standard Bosco header with title, description and navigation
Bosco has a big header – too big to be sticky without CSS tweaking

(I’ve made the font-size for the site-title a little larger just so that it can be made smaller later in the transition.) If you scroll down, nothing will happen as myStickymenu is looking for a specific class to get “sticky” with and it doesn’t exist in the Bosco theme, so we need to find the Bosco equivalent.

Here’s the header HTML:

Rather than just make the navigation sticky, we want to make the whole header sticky, so let’s grab the id from the header element, #masthead and head back to WordPress and the myStickmenu settings (Settings > myStickymenu) and replace .navbar with #masthead in the Sticky Class option.

Screengrab of the Sticky Class option
This option is critical – it determined which element becomes sticky

Click on Save Changes, refresh your site, scroll down and you’ll soon see something like this:

Screengrab of the default styling of the sticky header
It’s now sticky but it’s a big and ugly!

A little overwhelming, so let’s start configuring and adding some custom CSS to get the effect we want. Change the options as follows:

  • Sticky Background Color : #FFFFFF
  • Sticky Opacity : 100
  • Sticky Transition Time : 1 (a longer transition time works better)
  • Make visible when scroled (sic) : 75 (this will mean that the new header will appear almost immediately after the original scrolls out of view)
  • Fade or slide effect : uncheck (I prefer the fade effect)

Click on Save Changes and refresh the site again. We now have a sticky header that, at least, isn’t orange and the transition seems smoother. But it’s still too big, so let’s add custom CSS to:

  • reduce the size of the site title
  • hide the site description
  • add a full-width shadow border to the bottom of the header
  • remove excess padding

We can do this by taking advantage of the myStickymenu plugin adding a class of .myfixed to the element with id or class specified in the Sticky Class option (in our case header#masthead) when the sticky is activated. So, we just have to include .myfixed in the selectors and the styles will only be applied when the sticky is active.

That final statement for the wrapfixed class adds the shadow border. If you look at the header HTML earlier in the article you’ll see that no such class exists in the original HTML, so where did it come from?

The myStickymenu plugin actually wraps the target element in its own custom HTML (see below) and this class only gets added to the div#mysticky-nav when the scroll has taken place. This element is full-width, making it perfect for attaching the shadow effect to, and the dynamic adding of the style means that the shadow is only visible when the sticky is active.

Add the above CSS to the .myfixed css class options in the myStickymenu settings and click on Save Changes. Now when you view your site you should see something like this almost immediately after the heading scrolls out of view:

Screengrab of the smaller sticky Bosco header
A compact, good-looking sticky header that maintains branding and provides access to site navigation

You might want to play with the options in the myStickymenu settings to get a behavior which is more to your liking. You should also now be able to make the header “sticky” in any theme; you just need to follow the steps above.

In no time you’ll be keeping your branding, giving your readers easy access to your site’s navigation and joining illustrious East Coast company.

]]>
http://premium.wpmudev.org/blog/how-to-add-a-new-yorker-style-header-to-your-wordpress-site/feed/ 0
Creating A Mobile App For Your WordPress Site: A DIY Guide http://premium.wpmudev.org/blog/creating-a-mobile-app-for-your-wordpress-site-a-diy-guide/ http://premium.wpmudev.org/blog/creating-a-mobile-app-for-your-wordpress-site-a-diy-guide/#comments Thu, 24 Jul 2014 12:00:00 +0000 http://premium.wpmudev.org/blog/?p=129803 You’ve probably thought before about how good it would be to create a mobile app for your WordPress site. The advantage of having that icon on a home screen, a single tap to engagement, perhaps just the kudos of being able to say “of course we have an app”.

But you checked out the options and they are either too complicated or too expensive and so the thought got reluctantly tossed into the “too hard” basket.

Well, go rummage in that basket and retrieve that thought because here’s a DIY approach that will allow you, for little cost, to create that basic app.

PhoneGap Build + WordPress = Mobile App
PhoneGap Build offers a simple and cost-effective way to bring your WordPress site to a mobile app

The reasons for creating a mobile app have changed as the sheer volume of apps in the various app stores has exploded. Gone are the days of being able to use an app store as a form of marketing as the chances of your app being discovered sink ever closer to zero.

Today, it’s about giving your readers choice: letting them decide how and where they engage with your content. And, of course, with the continued rise of internet access via mobile devices (in the US in January 2014, access via mobile apps surpassed desktop access and was massively more popular than mobile web browsing) having a mobile app is becoming increasing popular.

The really good news is that also gone are the days of needing a hard-core developer, knowledge of Java or C and a large cash reserve to build an app.

You can build an app using freely available tools and get it onto an Android device at no cost; on iOS, Apple being Apple means that they have to inject themselves into the process somewhere, so you’ll need to spend at least the $99/yr to join the iOS Developer Program so that you can build and distribute your app (either directly or via the app store).

Let me also make something else absolutely clear: this is about creating a mobile app to get your WordPress content into the hands of your readers’ mobile devices. It’s not about creating “proper” apps using WordPress as an application framework.

How It Works

PhoneGap Build logo
PGB makes building apps much more streamlined

This solution is based on creating the simplest mobile app possible, using the PhoneGap Build service (PGB) which really does live up to its claim to:

Take the pain out of developing mobile apps.

The app’s sole purpose is to fire-up the device’s inappbrowser and point it to the homepage of your site. Almost as if your reader was using a mobile web browser.

The beauty of this approach is that everything is effectively controlled in WordPress and using tools, techniques and technologies you are already familiar with. If you want to tweak the look and feel it’s a matter of updating the WordPress theme, no need to roll out an update to the app itself.

The solution is, then, 1% app, 99% WordPress which means that you must, must, must pay attention to what your WordPress site is delivering. Even the most responsive of themes is likely to fall short of an expectation that with mobile apps is far higher than it is with mobile web. You have to make sure you are optimizing for the mobile experience which means thinking about the theme, the content, menus and the interaction.

This post is going to focus on the building of the app and setting up WordPress, so I would encourage you first to take a look at the following couple of articles to ensure that you are on the right track:

Get WordPress right first – you can test that by simply browsing on a mobile device or using a simulator – before you build the app.

And, always remember that deleting an app from a home screen is easier than putting there in the first place.

4 Steps To A Mobile App

Let’s walkthrough how to build the app. As Android is easier and doesn’t require any signing-up to programs we’ll concentrate on that OS but keep in mind that the process for any OS is pretty much the same.

For this post, I built an app for an old podcast that I used to produce and co-host, A Game Of Two Halves, as it had plenty of publicly available content. You can download the .apk from the app’s public page on PhoneGap Build.

Before You Start

Whilst web apps are easily tested using emulators, mobile apps are much easier to test on an actual device. As I mentioned above, Android is the easiest OS to test with, so if you don’t have an Android device use this as an excuse to go get one, or to make use of an old device that’s gathering dust somewhere.

If you haven’t used PGB before, you’ll need to create an account. PGB has a free plan that allows for a single private app (which you can create by uploading a zip file) or unlimited open source apps (which must be pulled from a public GitHub repository).

If you are starting out with PGB then I would recommend using it in conjunction with GitHub as it makes the process of updating and rebuilding your app much smoother. It also means that you can use your GitHub credentials to sign into PGB.

Step 1. Create The PGB App Files

Directory listing showing layout for the app
Most of the files for this app are logos and splash screens!

The structure is very simple, with a root directory containing an index.html, the all-important config.xml, a couple of default icon files in png format and a res directory that contains OS specific icons for home screens and splash pages.

You can download this app to use as a starter for your own app.

Step 2. Create The App Icons

The app icons are important: they are what the app will use when adding an icon to the device’s home screen and what it will use as a splash screen when the app is opened.

To generate the icons, use a service such as App Icon or Make App Icon. They tend to use the same file names, so it should be a matter of uploading your raw icon design (png format, 1024×1024 for both services), letting the service run and then downloading the appropriate images to the correct folder.

Step 3. Configuring The App

All the configuration is contained within the config.xml file. For your own app, you’ll should change the following:

  • widget @id – convention is to reverse your site’s domain name and add a suffix of .app
  • name – the title of your site.
  • description – a short description for your site
  • author (@email, @href) – your details
  • content @src – change this to the home page of your site
  • access @origin - this determines which websites the app can browse. The 2 extremes are to enter your domain name and therefore restrict the app to only browsing your website or to use ‘*’ and allow any website to be browsed

There are a number of gap:plugin elements in this configuration file, most of which you don’t need. However, it’s worth building the app with these plugins as this will allow you to take advantage of features such as geolocation down the track without needing to rebuild, and thus update, your app.

You’ll also notice that there are a number of icon and gap:splash elements which the app will use for the device’s home screen and for the apps splash page. If you’ve moved your generated icons into the correct folders then you should find that there’s nothing to change here.

Just be aware, though, that the names are case-sensitive!

Step 4. Kick-off The PGB Build Process

Go to the PGB website and sign in. You’ll be presented with the Apps screen which will be empty, of course.

Screenshot of the create app screen
PhoneGap Build is much easier when used in conjunction with GitHub

Assuming that you’ve signed in with your GitHub account and that you are going to build an open-source app. All your GitHub public repositories will be available in the “find existing repo”, so click on the arrow, select your repo and click on pull from GitHub repository.

PGB will pull in your repository and then present you with an app details screen

The app screen showing the ready to build button
Once PGB has pulled in the files from GitHub, you are ready to build

Click on Ready to build.

The page now changes to give you progress on how the build is going. By default, PGB tries to build an app for iOS, Android and Windows 8. Red means the build has failed, whilst blue indicates a successful build.

The PhoneGap Build app screen
PGB will try to build for Android, iOS and Windows. Blue is success.

iOS will always fail unless you have provided PGB with your iOS developer certificates which requires the joining of the iOS Developer Program that I mentioned earlier.

Hopefully, though, the Android build has been successful and you are ready to test!

You can download the .apk by clicking on the Android icon. Otherwise, and perhaps an easier way to get the .apk onto an Android device is to navigate to the app’s public page on an Android device (there’s a QR code to help) and tap on the Android link. This will download the .apk to the device, so it’s just a matter of jumping into Downloads and tapping on the file to install the app.

Yet another alternative is to access the PGB website on an Android device.

Whichever method you used, you should now find your app’s icon on your home screen (if the icon is not what you were expecting then it’s likely you’ve got the URL wrong in the config.xml file).

Tap on the icon and the app will open and you will be greeted with the splash screen and then the front page of your website (depending on the spec of your device there may be slight delays in moving from the splash screen to the website).

Congratulations you’ve built your first app!

How good it is, will depend entirely on how you’ve set up your WordPress site but the advantage now is that you only need to work in WordPress to make improvements.

If for some reason, such as an incorrect image URL, you need to rebuild the app then:

  1. Update the files in your GitHub repo
  2. Go to the app page in PGB and click on Update code – this will pull in the files from your GitHub repo
  3. PGB should automatically start the rebuild process – if it doesn’t click on Rebuild All

Barest Of Bones

This is the barest of bones type of mobile app, which naturally means that there’s going to be the odd “if only it….” or two.

The major missing component is notifications which is annoying as they can be incredibly useful. Whilst it entirely possible to add them to a PGB app (AppPresser has done so via the Pushwoosh service but you’ll need to buy their $199/yr Starter Plan) it is beyond this post.

In fact, if you want to take more advantage of the mobile device capabilities then it’s worth taking a closer look at AppPresser.

But if you are just wanting to provide your readers with choice by providing them with a mobile app then this process does the job. It’s even simple enough for us WordPress implementers!

]]>
http://premium.wpmudev.org/blog/creating-a-mobile-app-for-your-wordpress-site-a-diy-guide/feed/ 0
WordPress Security: The Ultimate Guide http://premium.wpmudev.org/blog/keeping-wordpress-secure-the-ultimate-guide/ http://premium.wpmudev.org/blog/keeping-wordpress-secure-the-ultimate-guide/#comments Wed, 23 Jul 2014 12:00:45 +0000 http://premium.wpmudev.org/blog/?p=130779 Like most website owners, security was never top of my priorities. It was only when one of my websites was hacked that I realised how common it was for websites to be compromised by malicious parties.

As the most popular web publishing platform on the internet (by a large margin), WordPress is a popular target for hackers and spammers. WordPress is known for being one of the most user-friendly website platforms available online, but out of the box WordPress is terribly vulnerable to attacks.

According to WP White Security, more than 70% of WordPress installations are vulnerable to hacker attacks and the total number of hacked WordPress websites in 2012 was a whopping 170,000. This figure is growing every year.

You may be wondering why anyone would want to attack your website, particularly if you have a low traffic website; however the vast majority of hackers are not looking to steal your data or delete important files. What they want to do is use your server to send spam emails.

I experienced this myself last year. A friend of mine had built a small content website using WordPress and hosted it on my hosting plan. Unfortunately, my friend stopped updating the website, which meant that WordPress was outdated. This made it possible for hackers to upload a script that sent spam directly from my server.

Due to this, my server IP address was blacklisted by all major ISP’s and email services; therefore newsletters that I was sending from a website I owned were not being delivered. Thankfully, I was able to clean my IP address from blacklists by using the blacklist checker from MXToolBox, though the whole experience cost me a lot of time and money.

MXToolBox
MXToolBox can check to see if your server has been blacklisted.

When it comes to website security, it pays to be proactive rather than reactive. Do not assume your website is secure because you have not been hacked in the past.

This article details what you need to do to make your WordPress website secure from threats. It has been divided into five main sections. Click of one the links below to skip ahead to the appropriate section:

I encourage you to bookmark this article for future reference as you will find it useful when you are securing other WordPress websites you develop :)

 

How Do Hackers Compromise Your Website?

It is important to understand how hackers gain entry into a WordPress website and have their wicked way. Although there are many different ways in which a hacker can break into a WordPress website, the main techniques can be grouped together into four categories. In an article last year, WP White Security reported the following statistics about hacked websites:

  • 41% were hacked through a security vulnerability on their hosting platform
  • 29% were hacked via a security issue in the WordPress Theme they were using
  • 22% were hacked via a security issue in the WordPress Plugins they were using
  • 8% were hacked because they had a weak password

As you can see, 41% of attacks are caused by security issues within your hosting platform. This covers a lot of techniques, such as using a URL parameter to process an SQL injection. This technique allows the hacker to add code to your database, which can allow them to change data (e.g. your password), retrieve data, or delete data (i.e. delete all your posts and pages).

A whopping 51% of attacks were made through a WordPress plugin or theme. Hackers can do things such as insert an eval base 64 decode code which allows them to run a PHP function from your website (e.g. to send spam). They may also leave a backdoor somewhere on your website. This is a technique they use to get access to your website in the future, even when you believe you have deleted all malicious files.

Last on the list is a weak password. Hackers continue to gain access in this way by using automated scripts that continually guess passwords until they gain entry; a technique that is known as brute force.

 

WordPress Security Best Practices

Hackers are not looking for a long battle to gain access to a website. They specifically go after WordPress websites that are vulnerable because of security holes. You can therefore effectively block 99.99% of attacks on your website by simply addressing these security issues.

In this section, I would like to walk through techniques that you can apply to your website in order to make it more secure. It should not take you more than 20 to 30 minutes to apply all of these techniques. All you have to do is modify a few key files such as .htaccess and wp-config.php. I will also speak about security best practices and recommend WordPress plugins that will help you make your website more secure.

Remember that prevention is better than the cure. If you follow the advice given in this section, a hacker will find it very difficult to gain access to your website in the first instance.

Host Your Website with a Good Hosting Company

With 41% of hacking attempts being caused by a security vulnerability on a hosting platform, it pays to host your website with a good quality hosting company. Look for a hosting company that places an emphasis on security. One that has:

  • Support for the latest versions of PHP and MySQL
  • Is optimized for running WordPress
  • Includes a WordPress optimized firewall
  • Has malware scanning and intrusive file detection
  • Trains their staff on important WordPress security issues

If you choose a shared hosting plan, make sure that your host provides account isolation. This ensures that one account cannot overload the server and cause problems for your website. Good hosting companies will also offer daily internal backups, but remember that you still need to backup externally regularly too (more on this later).

Pagely
Choose a hosting company that places an emphasis on security, such as Pagely and their trademarked PRESSARMOR WordPress security system.

Important Installation Settings

WordPress Security Keys were first introduced in WordPress versions 2.5, 2.6, and 2.7. The keys improve encryption of the information that is stored in a visitor’s cookies. They will also make it harder to crack your password as it adds random elements to them. A salt key phrase is added to make it even more secure.

The keys can be changed in wp-config.php. This is an important configuration file that can be found in the root of your WordPress installation. If you have not added security keys to your wp-config.php file already, the code will look like this:

1
2
3
4
5
6
7
8
define('AUTH_KEY', 'put your unique phrase here');
define('SECURE_AUTH_KEY', 'put your unique phrase here');
define('LOGGED_IN_KEY', 'put your unique phrase here');
define('NONCE_KEY', 'put your unique phrase here');
define('AUTH_SALT', 'put your unique phrase here');
define('SECURE_AUTH_SALT', 'put your unique phrase here');
define('LOGGED_IN_SALT', 'put your unique phrase here');
define('NONCE_SALT', 'put your unique phrase here');

Eight keys and salts can be generated through the WordPress Salt Keys Generator. Once the code has been generated, you simply replace the code above with the unique generated phrases.

It will look something like this:


* Note that the above code is just an example. You should generate unique codes for your website.

WordPress applies a table prefix to all database tables. The default table prefix is wp_. For example, wp_posts, wp_terms etc. Changing the table prefix can help prevent SQL injection vulnerabilities as hackers will need to guess the prefix; which, in turn, will stop people from gaining control of your database.

You will find the table prefix in your wp-config.php file:

1
$table_prefix = 'wp_';

Simply change the table prefix to something obscure that no person or script could guess. For example:

1
$table_prefix = 'asdfadsfa894sdms_';

Changing the table prefix in your wp-config.php file will not automatically change the prefix of your WordPress tables if you have already installed WordPress. Therefore, if you are changing the table prefix on an existing website, you need to update your database too.

One of the quickest ways of doing this is to install the plugin iThemes Security. The plugin can automatically do all the necessary changes for you.

Alternatively, you can do this manually. This is a more time consuming way to change the table prefix, however it may be necessary for you to do this if you cannot do it automatically via a security plugin.

There are two methods available to you through PHPMyAdmin (the process will be almost identical with other database managers). The first method is to use an SQL query to rename each table. Below is an example of how this is done:

1
RENAME table `wp_links` TO `newprefix_links`;

Obviously, you would change the reference to newprefix in the above example to the prefix you have defined in wp-config.php.

You need to run the above query for each database table including all core tables and any additional tables added by plugins.

The other way to do it is to click on the name of a table and then click on the operations tab. This tab allows you to change important table settings such as the table name. This step needs to be completed for each table.

Rename Table Prefix
Table prefixes can be changed through the operations tab.

Next, you need to update the references to the table prefix in the usermeta and options tables. You can do this using the PHPMyAdmin interface, however it is much quicker to simply use an SQL query.

To update the usermeta table (formerly wp_usermeta), enter the following SQL query through the PHPMyAdmin SQL tab:

1
UPDATE `newprefix_usermeta` SET `meta_key` = REPLACE( `meta_key`, 'wp_', 'newprefix_' )

To update the options table (formerly wp_options), enter the following SQL query through the PHPMyAdmin SQL tab:

1
UPDATE `newprefix_options` SET `option_name` = 'newprefix_user_roles' WHERE `option_name` = 'wp_user_roles'

Again, in both examples above, be sure to change the references to newprefix to the prefix you have defined in wp-config.php.

To recap, to update your WordPress database tables with your new prefix, you need to:

  1. Rename each WordPress table
  2. Update the usermeta table
  3. Update the options table

I would still recommend changing the table prefix in your WordPress table using iThemes Security as it allows the above changes to be made at the click of a button. You will, however, find the guide for applying the changes useful if the plugin cannot apply the necessary changes automatically.

Keep WordPress Updated

Every version of WordPress addresses security holes that have been identified in previous versions. Therefore, if you are using an older version of WordPress, your website is more susceptible to attacks. That is why it is important you always update WordPress to the latest version.

Major versions of WordPress contain many new features and are released twice a year. They are easily recognised as the version number increments by 0.1 with each release e.g. 3.7, 3.8, 3.9, 4.0 etc. Following every major release, WordPress release a few minor updates. The release numbers for minor releases increment by 0.01 e.g. 3.9.1, 3.9.2 etc.

Whereas major releases of WordPress introduce new features to the platform, minor releases address important security bugs and errors that have been found in a major release. It is therefore essential you apply these minor updates to your website.

WordPress introduced a new feature in WordPress 3.7 that updates WordPress automatically in the background. Many WordPress users wrongly believe that this feature applies to all WordPress updates, but by default WordPress will only automatically apply minor updates to your website.

It is possible to apply major and minor updates to your website. This will remove the need for you to ever update WordPress manually again. You can do this by adding this piece of code to your wp-config.php file:

1
2
# Enable all core updates, including minor and major:
define( 'WP_AUTO_UPDATE_CORE', true );

Safeguards are put in place to ensure your website does not break when your website is automatically updated, however there is always a risk that your website breaks after a major update. This is more likely if you use WordPress plugins that are not actively updated so you should be aware of this if you do apply major updates to your website automatically.

If you would prefer to handle all updates yourself because you are concerned your website will break with an automatic update (major or minor), you can disable all core WordPress automatic updates by adding this code to your wp-config.php:

1
2
# Disable all core updates:
define( 'WP_AUTO_UPDATE_CORE', false );

Plugin developers can improve automatic updates better by utilizing the add_filter function. They can do this by adding the following code to your wp-config.php file after the add_filter() reference.

1
require_once( ABSPATH . 'wp-settings.php' );

Check out “The definitive guide to disabling auto updates in WordPress 3.7” by Andrew Nacin for more information on disabling automatic updates.

WordPress Plugins and Themes

Security holes in themes and plugins represent more than half of all successful WordPress hacks. You therefore need to pay attention to the plugins you activate on your website.

  • Be ruthless when it comes to plugins. If you can do without the functionality a plugin offers, deactivate it and remove it.
  • Be wary of plugins that have not been updated within the last two years as they may have security holes in them that have not been addressed. If possible, only use plugins that are updated regularly.
  • All plugins are not created equal. Be conscious of the fact that a poorly coded plugin could make it easier for a hacker to gain access to your website.

It is important that your WordPress theme is up to date and well-coded, too. You can check the quality of the code in your theme using a plugin such as Theme-Check and check the code in plugins using Plugin-Check.

You should also be careful of downloading free WordPress themes from unknown sources as they may contain malicious code. If in doubt, stick to the free WordPress designs available at WordPress.org.

Hackers could insert malicious code into premium plugins and themes. It is highly unlikely that the original developer of a premium WordPress product would insert malware into it, though you do need to be careful when downloading a premium product from other sources.

Therefore, I implore you to do the right thing and support WordPress developers by buying plugins and themes from them directly. Downloading a premium plugin or theme from a torrent website hurts their business and there is a chance the uploader has inserted malware into the product, placing your website at risk of being attacked. You are safer downloading plugins from a source such as WPMU DEV. Not only are our plugins free from bugs, they also come with 24/7 support.

The WordPress updater can be configured to automatically update plugins and themes. To automatically update WordPress plugins, add the following code to your wp-config.php file:

1
add_filter( 'auto_update_plugin', '__return_true' );

To automatically update your theme, add this code to wp-config.php:

1
add_filter( 'auto_update_theme', '__return_true' );

Note that your WordPress theme has to support automatic updates in order for the above code to work.

Remember that updating plugins automatically may cause a website error and could happen when you are away from the computer. I recommend upgrading plugins and themes manually to ensure that if any problems occur during upgrade, you can deactivate the plugin and reactivate it when the developer has fixed the error.

The WordPress plugin and theme editor allows authorised users to modify your theme and your installed plugins. If a hacker was able to gain access to your WordPress admin area, they could crash your website in a matter of seconds by simply changing code, or removing code. To avoid this occurring, you can disable the plugin and theme editor by adding the following code to your wp-config.php file:

1
define( 'DISALLOW_FILE_EDIT', true );

You can also remove the option of updating and installing plugins and themes by adding the code below to your wp-config.php file. Applying this technique would stop an unauthorized party from being able to upload their own plugin to your website.

1
define( 'DISALLOW_FILE_MODS', true );

The above code will also deactivate the plugin and theme editor if it is added to your wp-config.php file.

Using Correct File Permissions

It is important that you configure your file permissions correctly. Setting a directory with permissions of 777 could allow a malicious party to upload a file or modify an existing file.

According to WordPress, you should use the following permissions on a WordPress website:

  • All directories should be 755 or 750
  • All files should be 644 or 640
  • wp-config.php should be 600

Check out the Changing File Permissions guide on WordPress.org for more information on how to change file permissions. If you are unsure as to whether you have set up your WordPress file permissions correctly, ask your host to check them for you.

Turn Off PHP Error Reporting

If a plugin or theme causes an error, the error message may display your server path. This information is useful to hackers, therefore it is better to disable error reporting altogether for a live website.

You can disable error reporting in WordPress by adding the following code to your wp-config.php file:

1
2
error_reporting(0);
@ini_set(‘display_errors’, 0);

If the above code does not work, speak to your web hosting company and ask if they can disable error reporting on your behalf.

Protecting WordPress Using .htaccess

The .htaccess file is a powerful configuration file that change the way your server operates. It is used to redirect URLs and configure pretty permalinks. The file can also be used to harden WordPress security.

The techniques below will strengthen your WordPress website significantly. Please note that he code has to be placed outside of the # BEGIN WordPress and # END WordPress tags, as anything between those tags can be updated by WordPress (e.g. during updates and permalink changes). Be sure to click on the option to see hidden files in your FTP client or file manager too. Otherwise, the .htaccess file will not be visible in the file list.

The wp-config.php is an important file as it contains your database connection settings, table prefix, security keys, and other sensitive information. You can protect the file by adding the following code snippet to your .htaccess file:

1
2
3
4
<files wp-config.php>
order allow,deny
deny from all
</files>

You can also relocate the wp-config.php file above your installation folder; however there is some debate as to whether this is beneficial.

To restrict access to your WordPress admin area to a specific IP address, use the code below (be sure to change the IP address to your own). In order to do this, you need to create a separate .htaccess file and upload it to the /wp-admin/ directory. Be aware that in order to access your WordPress admin area via a different IP address, you will need to modify the .htaccess file.

1
2
3
order deny,allow
allow from 192.168.5.1
deny from all

Additional IP addresses can be allowed by adding additional lines. For example:

1
2
3
4
order deny,allow
allow from 192.168.5.1
allow from 123.456.7.8
deny from all

The wp-login.php file that is found in the root of your WordPress installation can also be restricted to a specific IP address. The wp-login page will ultimately redirect any logged in users to the /wp-admin/ directory, therefore if anyone did login through wp-login.php, they would be blocked at /wp-admin/. However, you may want to restrict access to wp-login.php too for added security.

An alternative to protecting your admin area by restricting it to certain IP addresses is to password protect the directory. I am not a fan of this technique as it can cause problems with Ajax in plugins and is apparently not full proof.

If you find a person is consistently trying to access your WordPress admin area, you can block them from your website using the code below. Like the restrict by IP technique, additional IP addresses can be blocked using this technique by defining them in additional lines.

1
2
3
order allow,deny
deny from 456.123.8.9
allow from all

The /wp-includes/ directory contains a lot of important files that are required to run WordPress. There is no need for any visitor to view the contents of this directory. To protect the /wp-includes/ directory, add the following snippet to .htaccess:

1
2
3
4
5
6
7
8
9
10
# Block the include-only files
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^wp-admin/includes/ - [F,L]
RewriteRule !^wp-includes/ - [S=3]
RewriteRule ^wp-includes/[^/]+\.php$ - [F,L]
RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F,L]
RewriteRule ^wp-includes/theme-compat/ - [F,L]
</IfModule>

To prevent people from browsing the content of your directories, add the following code snippet to your .htaccess file :

1
Options All -Indexes

To protect the .htaccess file itself, add this to the file:

1
2
3
4
<Files .htaccess>
order allow,deny
deny from all
</Files>

The /wp-content/ directory can be protected using .htaccess too. In order to do this, you need to create a separate .htaccess file and upload it to the /wp-content/ directory. Then add the following code to the file:

As you can see, the above technique will protect the /wp-content/ directory but allow XML, CSS, Javascript, and images, to be processed. Be aware that this code has been known to break some WordPress themes as it does not allow PHP to be executed; particularly themes that use timthumb.php. If the code causes any problems with your website, it is best to remove the .htaccess file from the /wp-content/ directory.

Disable XML-RPC

Since WordPRess 3.5, XML-RPC has been enabled by default. The feature allows you to remotely connect via blogging clients. It is also used for trackbacks and pingbacks. Unfortunately, hackers have been known to use the file for DDoS attacks.

You can use a plugin such as Disable XML-RPC Pingback and Disable XML-RPC and reduce the change of your website being attacked.

Stronger Login Information

Weak passwords allow hackers to gain access to your website easily using a brute force automated script. You should therefore:

Many years ago, WordPress used the username admin as the default username for the primary administrator account. They now allow you to choose any username you wish during the installation process, however many people still choose the username admin.

The problem is that hackers know that admin was the default administrator username for a long time. This means that they only need to work out the password for the administrator account. Due to this, most brute force scripts attempt to gain access to your website using the username admin.

You should therefore change your administrator username if you are using admin or another basic username. This will make it much more difficult for a hacker to gain access.

You can do this by entering the following SQL query in PHPMyAdmin (or whatever database manager you are using). Be sure to change newusername to the new username.

1
UPDATE wp_users SET user_login = 'newusername' WHERE user_login = 'admin';

You could also run the above command directly through your admin area using the WordPress plugin WP-DBManager, but be sure to uninstall the plugin after using it as you do not want to give anyone the opportunity of accessing your database directly through the admin area.

Alternatively, use the plugin Admin renamer extended to change the username directly through your WordPress admin area.

Limit Login Attempts

Hackers use brute force attacks to try and gain access to your WordPress admin area; continually trying new random usernames and passwords. One of the best ways to protect your website against this kind of attack is to install Login LockDown or Login Security Solution. The plugins allow you to limit the number of login attempts from a given IP range.

Once a user has failed a defined number of times, they will be logged out of your website for a defined period of time. The default period of lockout can be increased to a more significant period of time if you wish. You can manually unban any legitimate users that have been locked out, so you need not worry about frustrating your staff.

The great thing about these plugins is that they record the IP address of anyone who fails a login attempt. You can use this information to block those people from your website indefinitely using the .htaccess technique I discussed earlier.

Login Lockdown
Limiting the number of failed login attempts that are allowed makes it difficult to use brute force scripts on your website.

Two-Step Authentication Solutions

A two-step login authentication process will make it even more difficult for hackers to access your website through a brute force attack. It forces everyone to use an authorisation code in order to login to your website. For example, you may have to provide a code that can only be accessed via your mobile phone.

Here are some useful authentication WordPress plugins that are available to you free of charge:

  • Google Authenticator – Requires you to enter a secret key or QR code that is provided to you via a Google Authenticator smartphone application
  • Clef – Allows you to login using a passwordless two-factor authentication system using your mobile phone
  • Clockwork SMS – Sends a SMS to your mobile phone with a key that you need to enter to login
  • Duo Two-Factor Authentication – Offers multiple ways to access your website such as a mobile phone application, a SMS, or a phone call
  • OpenID – Allows you to login using the OpenID protocol, which supports every major social media service
  • Authy Two Factor Authentication – Requires you to enter an API key from a smartphone application
  • Stealth Login Page – Login to your website using a secret login authorizaiton code

You may find a two-step authorization login process frustrating, however it is one of the most effective ways of preventing unauthorized parties accessing your website.

Two Step Authorization Process
Introducing a two step authorization login process will strengthen your website security considerably.

Hide Your Login Page

Malicious parties can attack your login page because they know that a default installation of WordPress can be logged in at www.yourwebsite.com/wp-admin/ and at www.yourwebsite.com/wp-login.php. Moving the location of your login files makes it very difficult for hackers to perform a brute force attack.

There are good plugin solutions available that allow you to do this easily:

  • Rename wp-login.php – A multisite friendly plugin that allows you to change your login page. Once activated, the wp-admin directory and wp-login.php page will be inaccessible.
  • Hide Login+ – Allows you to change name of your login page, admin area, logout page, and forgotten password page.
  • Lockdown WP Admin – Another useful plugin that can conceal your admin area and login page.

If you forget the new location of your login page and admin area, you can reset everything by simply deactivating the plugin in question. You can do this by renaming the name of the plugin folder contained within /wp-content/plugins/. Alternatively, you could delete the plugin and reinstall it once you have logged back in to your website.

Hide Login
It is difficult for a hacker to login to your website if they do not know where to login.

Remove the WordPress Version Number

By default, WordPress will place a meta tag in your website code that states the version of WordPress you are using:

1
&lt;meta name="generator" content="WordPress 3.9.1"&gt;

Unfortunately, this information is useful to hackers, particularly if you are using an older version of WordPress that has a security hole.

WordPress developer Paul Underwood shared a useful code snippet that lets you easily remove the WordPress version number from your website. You can do this by adding the following code to the top of your theme functions.php file:

1
remove_action('wp_head', 'wp_generator');

Alternatively, you can remove the WordPress version number by installing the plugin Remove Version.

Use Common Sense

When it comes to making your website more secure, a bit of common sense goes a long way. You can reduce the chances of your website being compromised by taking precautionary measures.

  • Do not login to your website on unsecured networks
  • Make sure your computer does not have any viruses by installing antivirus software such as AVG, Avira, or Comodo
  • Install a firewall on your computer for extra protection, such as Comodo or Zone Alarm
  • Only upload files to your website using a Secure FTP (SFTP) client such as FileZilla
  • Do not access your website in an internet cafe PC as someone could track your login
  • Be careful that no one sees you entering your login details in public locations such as coffee shops and airports, incase someone is watching you enter your username and password
  • Be wary of allowing people to upload files to your website via a form as hackers can use it to upload a malicious script – Even if you only allow image uploads, sneaky files such as image.jpg.php have been known to slip through
  • Do not ever give admin access to people you do not know and trust
  • Do not ever make someone editor if you do not know them well
  • If you are ever concerned about logged in users (editors, authors) doing something malicious on your website, use a plugin such as Simple Login Log or track Audit Trail their activity
  • Do not give people you do not know FTP access or access to your website hosting area unless absolutely necessary

Backup Often

The old idiom states that you should hope for the best, but prepare for the worst. This is particularly true with websites. Even if your website security has been hardened, there is no guarantee that your website will not be compromised by hackers. That is why it is important to backup your website frequently.

Most hosting companies provide daily backups of your website, however if the host’s data centre is damaged, be it through a power surge or flooding, your main website and internal backups could both be lost. That is why you need to backup your website externally too.

VaultPress
VaultPress offers one click backups and restores from only $5 per month per website.

There are automated WordPress backup services that make the process of backing up and restoring your website painless. This includes Automattic’s VaultPress, the backup and monitoring service CodeGuard, and the backup and migration service BlogVault.

If you prefer a plugin backup solution, check out BackupBuddy, Backup Creator, UpdraftPlus Backup and Restoration for WordPress, and WordPress Backup to Dropbox.

You should also check out our very own backup solution Snapshot. It can backup your database, your theme files, and your uploaded media. It is one of the few backup solutions that lets you select what tables are backed up.

Backups can be backed up via secure FTP or to Amazon S3 or Dropbox. Everything can be restored at the click of a button, which ensures that you can get your website back online as quickly as possible.

Snapshop Backup Solution
Snapshot is a great backup solution that has native support for BuddyPress and WordPress Multisite

Do not become complacent about backups. If your website has been hacked, your content could be modified or deleted completely, and an external backup could be the only thing that saves your website from being lost. Therefore, you need to have a disaster recovery plan in place.

 

Scanning Your Website

A lot of people wrongly believe that when your website is hacked, your whole website will be broken. However, that is rarely the case, as the goal of the hacker is usually to use your server to send spam mail.

If you know your website has been compromised, you will contact your hosting company and start removing the files the hacker uploaded. If, however, you are unaware of the hacker using your server to send spam, they can continue to use your server to relay their email messages without your knowledge.

The most effective way of discovering malware and suspicious files on your website is to scan your theme files regularly. There are many plugins and services available that help you do this.

  • Theme Authenticity Checker – The plugin will scan all installed WordPress themes for signs of malicious code. It will then highlight this code to you by showing you the path to the theme file, the line number, and a small snippet of the suspect code.
  • Ultimate Security Checker – A plugin that scans your website for hundreds of known threats and gives you a security grade on what it finds.
  • AntiVirus – A great plugin that scans your theme files and database for malicious code injections. Email notifications can be provided on a daily basis after each scan so that you are aware of anything suspicious.
  • WP Antivirus Site Protection – A server side scanner that can detect backdoors, rootkits, trojan horses, worms, PHP mailers, fraudulent tools, adware, spyware, and more. It can be run automatically on a daily basis.
  • Sucuri Sitecheck – The Sucuri scanner can scan your website for malware, spam, and defacements. It will also advise if your website is on any known blacklists.
  • CodeGuard – The CodeGuard service is used to backup your website on a daily basis. If they detect any changes on your website, they will email you with a notification of what was added, modified, or deleted.

Another great plugin you should check out is WP Changes Tracker. The plugin will keep a log of every change in WordPress, in your themes, and in your plugins. It is not a malware scanner, however if you notice anything different on your website, it allows you to look at a change log and see exactly what has changed.

Scan Your Website
Scanning your website regularly will help you detect malicious activity on your website.

 

All-in-One Security Plugins

If you are not a technical person, you may want to consider protecting your website using an all-in-one security solution. These WordPress plugins can toughen your website at the click of a button by addressing common WordPress security issues. Some also add a firewall and scan your website on a daily basis for malicious files.

Let’s take a closer look at some great all-in-one security plugins.

BulletProof Security is a feature packed security plugin that offers .htaccess website security protection, file intrusion detection, login security, database backups, and daily monitoring. It also keeps a log of anything that is changed.

The plugin has many configuration options. If you don’t want to configure these options yourself, you can choose to harden your website with one click.

BulletProof Security
BulletProof Security can protect your website at the click of a button.

Acunetix WP Security is a security plugin that can check for vulnerabilities in passwords, theme files, and your admin area.

The plugin has many useful options such as removing the WordPress version, disabling PHP error reporting, removing update notifications, and more. A live traffic tool is also included.

Acunetix WP Security
Acunetix WP Security addresses common WordPress security holes.

Sucuri Security will scan your website and detect PHP mailers, injections, malicious redirects, phishing attempts, and more.

The plugin also includes one click hardening options such as protecting your uploads directory, removing the WordPress version number, disabling theme and plugin editors, and restricting access to the /wp-content/ and /wp-includes/ directories.

Sucuri Security
In addition scanning your website, Sucuri Security can also harden your website and make it more secure.

Formerly known as Better WP Security, iThemes Security is the most downloaded WordPress security plugin on WordPress.org.

The plugin addresses common WordPress security vulnerabilities such as renaming the admin account, changing the ID of the first user from 1, removing login error messages, and displaying a random WordPress version number to non administrative users. It also features a monitoring system that will detect bots and file changes.

iThemes Security
iThemes Security is one of the most effective way of securing a WordPress website using a plugin.

Wordfence Security features mobile phone two-factor authentication logins, a firewall to block common security threats, and a password strength checker.

The plugin can scan your website for backdoors, malware, and phishing attempts. It will also monitor your disk space usage to help detect DDoS attacks.

Wordfence Security
Wordfence Security protects your website from malware, bots, phishing attempts, and much more.

Final Thoughts

Securing your website is something you need to take seriously. If you don’t take any security precautions for your website, you run a high risk of being hacked. This could cause your website to be blacklisted because it sent out spam. In a worse case scenario, you could lose all of your data.

By just taking thirty minutes out of your day, you can make your WordPress website secure and make it less likely that a hacker will do something malicious on your website.

If you fail to prepare, prepare to fail.

In the event of your website being compromised, stay calm. The best thing to do is reset your password, scan your website for malicious content, and contact your host for help on putting everything back to normal. By backing up every day, you can avoid the risk of your website content being completely lost.

If you want to want to learn more about securing your website, check out our WordPress Security Essentials series of articles.

  1. WordPress Security Essentials: Say Goodbye to Hackers
  2. WordPress Security Essentials : Four Points Of Vulnerability
  3. WordPress Security Essentials: Password and Username Safety
  4. WordPress Security Essentials : Building A Layered Defense
  5. WordPress Security Essentials: Obscurity Tactics and Backups

Be sure to check out the Hardening WordPress guide at WordPress.org, too. It has a lot of useful information on how you can improve the security of your website.

Do you know of any other great security tips for WordPress? If so, please share them in the comments below.

Image credits: Moyan Brenn

]]>
http://premium.wpmudev.org/blog/keeping-wordpress-secure-the-ultimate-guide/feed/ 31
Simplify Your WordPress Theming With Twig And Timber http://premium.wpmudev.org/blog/simplify-your-wordpress-theming-with-twig-and-timber/ http://premium.wpmudev.org/blog/simplify-your-wordpress-theming-with-twig-and-timber/#comments Mon, 21 Jul 2014 13:55:45 +0000 http://premium.wpmudev.org/blog/?p=130871 In a recent article on future features that WordPress could consider, I included adding a templating language to the core.

One such language is Twig and an implementation already exists for WordPress via the Timber plugin.

So, what is a templating language, how does it work in a WordPress environment and is it worth the effort?

Twig logo
Templating languages can bring massive advantages to WordPress theme development

Twig, from SensioLabs, is a “flexible, fast, and secure template engine for PHP”.

In a nutshell, Twig provides a meta-language (it is compiled into PHP) specifically designed for turning data into formatted output. That output is generally HTML but it doesn’t have to be – it can quite happily be XML, JSON or any plain-text format.

The output is generated by providing the Twig engine with the requisite data (as a PHP object) and telling it which template to render. The engine takes care of the rest.

But why change? There are thousands of existing WordPress themes that seem to do okay (some more than okay) using PHP. What’s the big deal with templating languages.

Advantages Of Using A Templating Language

The Twig website lists 6 major advantages of using the Twig templating language:

  1. Concise – compared to PHP, Twig is very concise making it easier to write and maintain
  2. Template orientated – it is a language that is purpose-built for creating output, rather than being a multi-purpose language such as PHP
  3. Full-featured – Twig is powerful, with inheritance and blocks making modular design very easy.
  4. Easy to learn - you certainly don’t need to be a developer to get the hang of Twig
  5. Extensibility – developers can add plugins to ensure that Twig can cover any front-end requirement
  6. Fast – this advantage may depend on how you rate your PHP skills as Twig is compiled down to PHP. I think its highly likely that for me, at least, the resultant PHP will be better than what I can come up with.

Biggest Advantage Is Separation Of Data And Design

What I really like about Twig is that it completely separates data from design. Twig is a template engine: you provide it with data and tell it which template to render.

This means that the underlying application is now only concerned with collating that data, there’s no requirement for its own themes. For WordPress that also means that plugins become data focussed whilst front-end controls, such as sliders, become the domain of Twig.

What Does Twig Look Like?

Twig is designed to work with any PHP application and it’s very easy to bootstrap it for testing (another of its advantages). A simple PHP file to render a template might look like this:

And the actual Twig template:

All very straight-forward and a lot cleaner than the traditional PHP/HTML mix. In fact, there are several CMS, such as Pico, that use this kind of approach (or perhaps a little more sophisticated although it does describe itself as “stupidly simple”!) to generate sites.

Timber: Bringing Twig To WordPress

We are, of course, interested in Twig and WordPress and it’s the Timber plugin that brings the two together. For some reason, there are 2 plugins called Timber in the WordPress repository so make sure you get the right one!

The plugin is the impressive work of Boston editorial designers Upstatement and performs three main tasks:

  1. Integrates the Twig engine into WordPress
  2. Creates a foundation WordPress data set
  3. Handles the rendering of Twig templates

Whereas in a normal WordPress theme you are mixing the data collation and its subsequent formatting in the same PHP files (think The Loop), a Timber template splits the two functions. In its basic form, the template file is only concerned with collating the data and then using that data to render a template, or view if you like, that is held in a separate file.

An example will help greatly, so let’s walk through one.

Here’s the index.php file for the Bosco theme (I’ve picked this theme as it is fairly simple):

The theme contains the familiar WordPress Loop and uses the get_template_part function to generate the output for each post in the list. (For the example, we are going to assume that all posts are of the standard format.)

With Timber, though, the index.php is only concerned with collating the required data:

It uses pre-baked Timber methods to get the generic data and then renders the index.twig template:

Not much in this template as I’ve followed the same modular approach as the original (i.e. code that gets used in multiple locations is placed in its own file) but we can already see Twig’s concise nature and powerful features at work.

First, there’s the else on the for statement. It works like the else on an if statement and will execute if the posts variable is empty. No need to wrap the for in an additional if statement. It’s also possible to perform actions based on the index value of the loop, so outputting a header on the first iteration or a footer on the last iteration, for example.

Second, there’s the use of Twig inheritance. In this case, the index template is extending the base template and providing content for the content block.

Let’s have a look at the base template:

There’s an import statement at the top of the file which makes some custom macros available to all files. For the sake of brevity, I’ve kept the original get_header, get_sidebar and get_footer functions (but called using Timber) and so the only block is the content block.

So, let’s have a look at the content.twig template:

This is a bit more interesting.

This template is only concerned with outputting a single article element and it’s pretty easy to work out what’s going on, even without being familiar with the Twig language.

All the variables being checked in the if statements or being output in the {{ }} statements are assembled by the PHP file and are passed to the Twig template.

The Timber plugin not only collates most of the data itself it also provides a few WordPress-specific essentials. For example, a post’s content is accessible via post.post_content, however, this is the raw content and so Timber provides the post.content method which will return the content after applying all filters and running all shortcodes.

You’ll see at the bottom of this template that there’s a couple of calls to macros: to output the post meta and to output the posts categories and tags.

The macros are stored in a Twig file (I’ve called it macros.twig but it could be any name) which is imported in the base.twig template. They don’t automatically have access to the data, so this gets passed to the macros:

This is where the advantages of an extensible templating language start to shine. A macro could be anything from outputting post meta to elaborate menuing to a full-screen slider and rather than being added as a plugin, it simply gets added as a Twig macro. All that needs to happen on the PHP-side of things is to ensure that the macro has the data it needs.

OK, But PHP And Twig? Isn’t That Doubling-Up?

The general assumption is that a Timber theme will follow the general convention and create a PHP file for each template that a theme may require, using the WordPress Template Hierarchy as a guide.

As we know, the Template Hierarchy is a wonderful thing. It allows us to easily get very specific with our templates. If we want to output category post lists differently to the other archives, we create a category.php file and it automatically gets used. If we want to get even more specific and have our sport category post list displayed differently to other categories then we create a category-sport.php.

This allows for incredible flexibility without the need to do any reconfiguring – simply drop a template into the theme directory with the appropriate name and it will automatically take its place in the template pecking order.

With Timber and Twig because the PHP files are just collating data there tends to be quite a lot of repetition. It’s possible, therefore, to take advantage of the WordPress Template Hierarchy and create just a single index.php that can generate the data we need and then work out the correct Twig template to render:

Timber Deserves A Closer Look

This has been brief overview of what is a powerful and thought-provoking plugin and if it has whet your appetite then I strongly recommend installing the plugin, browsing the Timber and Twig documentation and either grabbing the Timber Starter Theme (part of the plugin package) or converting an existing theme to get a feel for how it all works.

I think what you make of Timber and Twig will probably depend on the type of theme you are trying to build. A sidebar heavy, widget laden theme is not the best choice and it’s interesting to note that Upstatement are very much focussed on news media organisations.

You might also find that you are short on data and you’ll need to either extend Timber or simply update the PHP components of your theme to ensure that all the required data (logged in user data, for example) is being provided to the Twig templates.

What I really like about the Timber and Twig combination is the separation of data and design which means that designing a theme for WordPress (or any other CMS that uses Twig, of course) doesn’t require any knowledge of PHP and perhaps not even that much knowledge of WordPress itself.

Agree on what data is going to be made available and developer and theme designer can truly work on a site simultaneously.

A Possible Addition To The WordPress Core?

The advantages of a templating language also make me think that it should be seriously considered as potential update to the WordPress core.

Much has been recently been written about the need for WordPress themes to return to being clean, design only and for functionality to be split out into plugins. If nothing else, Twig forces the theme developer down this path.

You can imagine that it would be relatively straight-forward to build the dataset and make it available to a templating engine such as Twig (perhaps the WP-API already provides much of this functionality?) although the huge library of existing themes and the massive install base might prove a massive hurdle.

However, that doesn’t mean that Twig and its ilk should be summarily dismissed. Templating languages bring big advantages to theme development, not the least of which is a level of simplicity that is often missing from the traditional WordPress theme.

For that reason alone, Twig via the Timber plugin is worth investigating.

Do you have experience with using a templating language either on WordPress or another CMS?

]]>
http://premium.wpmudev.org/blog/simplify-your-wordpress-theming-with-twig-and-timber/feed/ 9
How to Inform Your Users When Comments Are Closing http://premium.wpmudev.org/blog/how-to-inform-your-users-when-comments-are-closing/ http://premium.wpmudev.org/blog/how-to-inform-your-users-when-comments-are-closing/#comments Sat, 19 Jul 2014 12:00:00 +0000 http://premium.wpmudev.org/blog/?p=130298 WordPress allows you to close comments after a certain number of days, but if you have visitors actively taking part in a discussion in the comments of a post, it might be a shock to them when they discover they can no longer comment.

In today’s Weekend WordPress Project, I’ll show you how to add a warning message to the bottom of your posts to alert visitors when comments are due to close.

Feature image
Let your visitors know when comments are closing on your posts.

Adding “Comments Are Closing” Message

Before we get started, we need to set comments to close. In WordPress go to Settings > Discussion and in the “Other comment settings” section, tick “Automatically close comments on articles older than” and enter the number of days you want to keep comments open for.

Comments
Set your comments to close automatically.

WordPress has a handy built-in function – human_time_diff() – for displaying relative time in a human-readable format, just like Twitter and Facebook.

For example, instead of your posts displaying, “Posted on January 23 at 10.30am,” you could display, “Posted 5 hours ago.”

We can take advantage of the human_time_diff() function to display a human-readable time in our alert message.

To add “Comments on this post will automatically close in XX”, just add the following snippet to your theme’s functions.php file:

1
2
3
4
5
6
7
8
9
10
add_action( 'comment_form_top', 'topic_closes_in' );

function topic_closes_in() {
global $post;
if ($post->comment_status == 'open') {
$close_comments_days_old = get_option( 'close_comments_days_old' );
$expires = strtotime( "{$post->post_date_gmt} GMT" ) + $close_comments_days_old * DAY_IN_SECONDS;
printf( __( '(Comments on this post will automatically close in %s. )', 'domain' ), human_time_diff( $expires ));
}
}

You posts will now display a message in the comments section that provides a countdown alerting visitors when comments will close.

Comments message
The alert message will display in the comments section of your posts.

If you would like to display a different message, simply edit line 8 in the code and add in your own message.

]]>
http://premium.wpmudev.org/blog/how-to-inform-your-users-when-comments-are-closing/feed/ 3
6 Steps To Optimizing Your WordPress Site For Mobile Devices http://premium.wpmudev.org/blog/6-steps-to-optimizing-your-wordpress-site-for-mobile-devices/ http://premium.wpmudev.org/blog/6-steps-to-optimizing-your-wordpress-site-for-mobile-devices/#comments Fri, 18 Jul 2014 12:00:00 +0000 http://premium.wpmudev.org/blog/?p=130724 It’s tempting to think that catering for your mobile audience is as simple as installing a responsive theme.

Even if your theme does look good on a mobile device (and there’s plenty that do), there’s still plenty more you can, in fact, should, do to optimize your mobile visitors’ experience.

Here’s 6 steps to delivering the perfect mobile WordPress experience.

WordPress logo in an iPhone in landscape and an iPhone in portrait
Optimizing the mobile experience is more than just the right theme

Mobile web browsing may not match the dizzying heights of mobile app usage but it’s not a trend that can be ignored.

More significantly for those of you that publish regular email newsletters is that according to Pew Research’s latest Mobile Technology Fact Sheet, 52% of US smartphone owners read email on their device. You work hard to get those precious clickthrus, don’t let them be undermined by content and design that doesn’t work on the device.

Whilst the right theme is obviously a critical step in the delivering the optimal mobile experience, it isn’t the only one.

You also need to look at:

  • mobile-specific menus – desktop menus rarely translate well to mobile, either because they are simply too large or contain links to content that is a low priority or even irrelevant for mobile users.
  • adaptive content - it’s virtually impossible to create post titles and excerpts that work well on expansive desktops and constrained mobiles, so don’t try, instead create versions for both
  • adaptive images - smaller screens work perfectly with smaller images so save your visitors’ time and bandwidth by sending them mobile-optimized images
  • theme switchers – if you opt for a mobile-specific theme rather than sticking with your current theme you are also going to have to look at a theme switcher to ensure that your mobile visitors get the correct theme
  • testing the mobile experience – no matter which approach you take you are going to need to test how your mobile site looks and behaves

In fact, we are going to start with the last on that list, testing the mobile experience.

Step 1: Set-up A Testing Environment

Screen shot of the iOS Simulator and Android Emulator running on OS X
Installing the iOS and Android simulators can be fiddly but is worth the effort

There’s no point going through all these steps if you can’t properly test the end result, especially if you want to build and test on a local machine.

Whilst you can do fairly extensive testing using browser plugins and simply changing the screen size it’s far better to actually test on a mobile device itself or if you don’t have access to the real device, a simulator.

Before you move on to Step 2, read this post on setting up a mobile test environment. You don’t have to install all the simulators listed: I usually just work with the iOS simulator that will provide both tablet (iPad) and mobile (iPhone) testing capability.

Step 2: Choosing The Theme

Add themes
Now you need to add mobile experience to your criteria when evaluating a theme

As any site owner knows, picking a theme is difficult, not least because the choice is so enormous.

Regardless of whether you already have an existing theme (responsive or otherwise) or are trialling new themes (mobile or desktop) you need to test them to ensure they are going to provide the sort of experience that you are comfortable with.

Many responsive themes make choices that you need to make sure that you are comfortable with and therefore extensive testing is imperative.

Hopefully, you’ve installed the iOS simulator, so fire it up, change the hardware to the iPhone and browse to your site to assess the theme’s performance using this small checklist:

1. Does it fit?

The issue of “fit” is not just about whether the content stays within the confines of the screen but also covers the amount of content your visitors will be able to see. Remember that the more visual clues there on a screen, the less your visitors have to guess or scroll:

  1. Are there any scrollbars, particularly horizontal scrollbars?
  2. Do all images sit within the screen?
  3. Is text (titles, headings, body) appropriately sized?
  4. Can you see at least the title of the first post on the home page?

If you have an existing site then this will be relatively easy to test. If you don’t then set up a test site and import the test content from wptest.io.

2. Do the menus work?

They come in all shapes and sizes so check that the menu works how you would like it to:

  1. Is accessing the menu obvious?
  2. Can you immediately see all the important menu options?
  3. Is it easy to scroll the menu?

3. How are sidebars handled?

If your theme has sidebars then the decisions that responsive themes make in dealing with them is hugely important – and my chief bugbear.

Themes generally have three options: hide the sidebar; move it to below the content as sort of additional footer; or turn it into a slide out element.

You need to pay particular attention to:

  1. Does essential content become hard or impossible to locate?
  2. If the sidebar is moved beneath the content does this create an ugly doubling up of footers?

It’s often the case that the best responsive themes are those that don’t use sidebars at all.

If Your Current Theme Isn’t Up To Scratch

So, you’ve played with your current (or preferred) theme on a mobile and you’re not entirely happy with it. What are your options?

  • Just live with it – perhaps justified if your mobile traffic is low but this is really just parking the problem
  • Change your theme – go the whole hog and switch to a new theme that handles mobile more to your liking
  • Use a mobile theme – use a theme specifically designed for mobile devices (requires a theme switcher plugin also). You will likely need to go premium to get a decent theme.
  • Use Jetpack’s Mobile Theme Feature – Automattic’s multi-faceted plugin Jetpack includes a feature to use its own mobile theme
  • Use WPtouch – one of the most popular WordPress plugins (5 million plus downloads), WPtouch is like Jetpack but better. Available in both free and premium versions, the free version will allow you to create a pretty decent mobile experience very quickly
  • Custom-build a mobile theme – if you’ve got the time and a modicum of HTML and CSS skills then you can build your own theme.

Step 3: Add Mobile-specific Menus

Being able to display menus specifically created for a mobile device is an essential component in the overall experience.

Navigation is a key component on any site and the chances are that the menu you designed for your desktop site is not going to work anywhere near as well on a mobile site simply due to the available screen real estate.

A potentially more important, and often overlooked consideration, is whether your mobile visitors have the same content priorities as your desktop users. For example, a Contact Us page with a location map might be a high priority, whilst a link to archives may not.

How do you create mobile-specific menus?

If you go down the WPtouch path then it’s built into both the free and premium version of the plugin.

Otherwise, you will have to “roll-your-own” but its not that difficult – here’s a tutorial that shows you how to create your own adaptive menus.

Step 4: Make Content Adaptive

Photo of publication in various formats
There’s a lot to learn about content and mobiles

(Find this excellent book at A Book Apart)

Just like menus, not all your content will scale down appropriately to a mobile device particularly:

  • Long titles and excerpts
  • Infographics and images that contain text or numbers
  • Multi-page content

We need to make content that is going to look good on a mobile but how do we do that without compromising how it looks on a desktop? By making it adaptive.

Adaptive content allows for content to be targeted at a particular platform either by creating alternatives (such as a short title custom field to replace title on mobiles) or by controlling whether content is visible at all (via shortcodes).

The controlling visibility is important. Some content, particularly infographics, may be unintelligible on a mobile simply due to the screen size; in such cases it’s better to not deliver the content at all.

Implementing some simple adaptive content techniques will help enormously in optimizing your mobile site compelling whether you use a responsive or mobile-specific theme.

Step 5: Add Adaptive Images Capability

A significant issue when delivering images to mobile devices is that the file that is delivered to the device is far larger than is required.

This is where adaptive images comes in. Basically what happens is that a request for an image file is analyzed to determine the type of device making the request. An image file is then dynamically delivered that is optimized for that platform.

This means that you don’t have to worry about explicitly creating images for each platform, it’s all taken care of for you.

Implementing adaptive images will have a noticeable impact on page download speeds and is highly recommended.

Step 6: Install A Theme-Switcher

If you are not using a plugin such as Jetpack or WPtouch to provide your mobile theme, then you will need to install a theme-switcher: a plugin that detects the device making the request and makes WordPress use a predefined theme when building the response.

The level of control varies from plugin to plugin so you need to pick one that will allow you to cover the platforms and devices that you are targeting. The Any Mobile Theme plugin is certainly worth looking at, allowing individual assignment across a wide range of mobile devices, including some tablets.

Screenshot of the plugin's settings page
Switch themes by device and operating system

Now You Have A Mobile Site

It may have taken a fair amount of work but if you’ve followed the 6 steps you’ll now have a mobile site that will be delivering an optimal experience and won’t look and feel like an afterthought.

And even if you go for using Jetpack or WPtouch (particularly the free version) then the steps covering menus, adaptive content and adaptive images are still relevant.

Your mobile traffic may not be significant at the moment but it will grow as the inevitable shift to access the web on mobile devices continues and you will need to address it at some point.

Better to do it now and be 6 steps ahead of your competition.

]]>
http://premium.wpmudev.org/blog/6-steps-to-optimizing-your-wordpress-site-for-mobile-devices/feed/ 0