Category: Tutorial

Simple Function Using wp_remote_get()

There isn’t a good amount of information on wp_remote_get() in the codex. Take a look to see what I mean:

https://codex.wordpress.org/Function_Reference/wp_remote_get

After you’ve used the function, the information it returns also has to be formatted in a certain way or you won’t be able to do anything with it.

wp_remote_get() Basics

Let’s start with a simple function:

$response = wp_remote_get( 'http://yoursite.com/api/somecallhere' );
if ( is_wp_error( $response ) ) {
   echo 'There be errors, yo!';
} else {
   echo 'It worked!';
}

With this function, we’re using wp_remote_get() to retrieve our URL. If there’s an error, we display the first sentence. If it worked, we display the second sentence.

Not much value in that so we need a few more lines of code.

What Comes Next?

Once we retrieve data from the URL, we need to format it correctly.

$response = wp_remote_get( 'http://yoursite.com/api/somecallhere' );
if ( is_wp_error( $response ) ) {
   echo 'There be errors, yo!';
} else {
   $body = wp_remote_retrieve_body( $response );
   $data = json_decode( $body );
}

if ( $data->Data ) {
   echo 'We got data, yo!';
}

After we retrieve our data, we use wp_remote_retrieve_body() and json_decode() to process it and get what we need.

We can even go one step further and display our data.

$response = wp_remote_get( 'http://yoursite.com/api/somecallhere' );
if ( is_wp_error( $response ) ) {
   echo 'There be errors, yo!';
} else {
   $body = wp_remote_retrieve_body( $response );
   $data = json_decode( $body );
}

if ( $data->Data ) {
   print_r( $data->Data );
}

This we’ll display the array of data that was returned.

Conclussion

When you need to hook into an API or retrieve data from a URL, wp_remote_get() is the function you need. Just remember that you’ll also have to take a few more steps in order to get to the actual data you want.

If you have any questions or feedback on this post, please use the comments below to start a discussion.

The post Simple Function Using wp_remote_get() appeared first on bavotasan.com.

Displaying Different Logos with WPML

Displaying Different Logos with WPML

WPML Languages

Living in Montreal, I often have to create multi-lingual websites for clients. That means finding the right plugin for the job. I don’t always use WPML, but it’s one of my go-to plugins when it comes to creating websites with multiple languages.

A recent client requested that their site display a different logo for each language. In order to make this happen, I had to code a simple conditional statement using PHP. But I needed to know which language was selected to display the right logo.

I wasn’t sure if WPML stored the current language selection so I had to do a bit of research. Thankfully, I discovered it did.

The Language Code

When a visitor selects a language, a two-letter language code is stored in the constant ICL_LANGUAGE_CODE. Using this and a little PHP, I wrote the following block of code to give my client what they wanted.


	

	

	

I placed that in header.php and used the class site-logo to style the CSS to match the client’s requested design.

Is there a better way?

If you take a closer look at the code above, you’ll notice that all the filenames have the language code as a prefix. That means you can simplify things even more which is always a better approach when it comes to coding.



Using the WPML plugin’s ICL_LANGUAGE_CODE constant lets you create all kinds of custom code specific to each language. Displaying different logos is just the tip of the iceberg.

NOTE: Konrad from WPML mentioned in a comment below a better way to get the current language code. It’s probably a good idea to use that one instead.

The post Displaying Different Logos with WPML appeared first on bavotasan.com.

Working with the WordPress admin_body_class function

Working with the WordPress admin_body_class function

WordPress admin_body_class function

For some reason, there are multiple functions in WordPress that do similar things but require different approaches. On the surface, you’d think the admin_body_class function would work the same as the body_class function, but you’d be wrong.

When you modify the body_class function, you hook into the filter like this:

add_filter( 'body_class', 'category_id_class' );
// add category nicenames in body and post class
function category_id_class( $classes ) {
	global $post;
	foreach ( ( get_the_category( $post->ID ) ) as $category ) {
		$classes[] = $category->category_nicename;
	}
	return $classes;
}

If you break that down, you’ll notice that adding a new class name requires extending the $classes array. Straightforward enough, though for some reason when you attempt to work with the admin_body_class function, this approach causes the following error:

Fatal error: [] operator not supported for strings

That’s because it uses a string instead of an array.

As long as your aware of this difference, working with the admin_body_class function is just as straightforward.

add_filter( 'admin_body_class', 'custom_admin_body_class' );
function custom_admin_body_class( $classes ) {
        $classes .= 'custom-class';

	return $classes;
}

I’ve found the above filter useful when I needed to customize the admin after I activated a plugin. With a simple check, the function added a class name to the admin body tag which made it easier for me to use CSS on the page.

Conclusion

The difference is slight but important to understand how to use the admin_body_class function correctly. Then you can easily customize your admin with JavaScript or CSS using that new class name.

You can read a little more about the function in the WordPress codex.

The post Working with the WordPress admin_body_class function appeared first on bavotasan.com.

Creating a New Language File for a Theme Translation

Creating a New Language File for a Theme Translation

Recently, I’ve had a lot of customers asking me about creating a theme translation file for some of my themes. What I always assumed was a straightforward process actually has a few little kinks that could confuse most people. It takes a couple of steps, but once you get the hang of it, it won’t seem so difficult.

First off, let’s discuss the software I use to translate my themes.

PoEdit translation software

Working with PoEdit

PoEdit is free, though there is a premium version you could buy. I opted for the premium version since I use it all the time and those extra features do really come in handy.

Once you load up a POT file, you will see all the translatable strings. Select your language and translate away. Once the strings have all been translated, click save and PoEdit will create the PO and MO theme translation files you need with the appropriate filenames.

Filenames are important and will help WordPress know which language file to use. You can read more about naming conventions here: https://make.wordpress.org/polyglots/teams/

You can see on that page that a Canadian English language file should be named en_CA.po and a French language file should be named fr_FR.po. Look through the list to see the correct name for your language.

Wordpress General admin setting

Switching WordPress into your language

This step of the process has become easier ever since the setting option was added to the General admin page. Before you had to edit wp-config.php but now you can just select your language from the drop down list.

Adding your theme translation file to the right folder

This is the one step that I actually didn’t really know much about. I thought you just had to add the new theme translation file to the theme’s languages folder. Though, this creates an issue if you ever update, since that folder is replaced and the custom language files are deleted.

The correct and safe way to store a language file is to create a languages folder in your wp-content folder. The hierarchy should look like this:

- wp-content
- - languages

Since you’re creating a translation for a theme, you need one more folder.

- wp-content
- - languages
- - - themes

We’re almost there. The languages folder we’re going to use is now outside of the theme folder, so we need to let WordPress know which files link to which themes. That means we have to change up the naming convention a little to connect things.

If you’re creating a French language file for the theme Arcade, this is how the folder/file setup should look:

- wp-content
- - languages
- - - themes
- - - - arcade-fr_FR.po
- - - - arcade-fr_FR.mo

You need to add ‘arcade-‘ to the name of the language file. If you were using Magazine Premium, you would have to add ‘magazine-premium-‘ to the file name.

Here’s another way to see the hierarchy:

/wp-content/languages/themes/arcade-fr_FR.po
/wp-content/languages/themes/arcade-fr_FR.mo

OR

/wp-content/languages/themes/magazine-premium-fr_FR.po
/wp-content/languages/themes/magazine-premium-fr_FR.mo

There’s the rub

It takes a few extra steps, but setting up a new languages folder this way will keep your theme translation files safe when you update.

If you’ve create language files for any of my themes, feel free to link to them in the comments below so everyone can benefit from your hard work.

The post Creating a New Language File for a Theme Translation appeared first on bavotasan.com.

Increase JPEG Quality in WordPress

Increase JPEG Quality in WordPress

Increase JPEG Quality in WordPress

When you upload an image to WordPress it’s processed and compressed to 90% of its original JPEG quality. This is a default setting that’s in place to automatically optimize every image, which in turn can hopefully speed up your site’s loading time.

It’s a nice enough little feature, but the fact that it happens behind the scenes without anyone really knowing it’s going on can cause some users a lot of grief. Especially photographers who see a drop in JPEG quality every time they upload an image.

There’s no option to change this within the WordPress admin and not having the power to control the JPEG quality of your images can be frustrating.

Stop Compressing My Images Already!

As with most features in WordPress, there’s a filter or action in place that we can hook into which will allow us to modify and customize certain functions. For this mod, the filter we need to hook into is called jpeg_quality.


All the filter requires is a quality setting between 1 and 100, with 100 being no compression whatsoever.

You can read a bit about the jpeg_quality filter and see the original function by checking out the code reference page.

Needs More Compression

If you’re someone who believes in the full extent of optimizing your images, then compressing them even more might be the way to go. It’s an easy enough change since all you need to do is decrease the JPEG quality to a setting below the default of 90.


You can always play around with the number and test out the results. You might discover a perfect balance between smaller file size and optimal image quality.

Make it easier on yourself and install the Regenerate Thumbnails plugin so you don’t have to re-upload your images again and again while trying out different quality settings.

If you have any suggestions or comments, please feel free to use the form below to start a discussion.

Featured image provided by Death to the Stock Photo.

The post Increase JPEG Quality in WordPress appeared first on bavotasan.com.

Add More Details to the Previous Post Link

Add More Details to the Previous Post Link

Add More Details to the Previous Post Link

When you load up the latest post on a properly designed WordPress site, you should see a link for the previous post somewhere on the page. It usually appears right after the main content. On older posts, you’ll also find a link pointing to the next post.

These previous/next links are often referred to as the “post pagination”. No to be confused with “posts pagination” which appears on archive pages to links to the previous/next page to show a list of older/newer posts.

In most WordPress themes, the previous link is displayed using the following function:


If you take a look at the previous_post_link() page in the WordPress codex you can see the available parameters. If you use the code example above, the %title placeholder will be replaced with the previous post’s title.

Since we want to add more details to the previous post link, let’s take a look at get_previous_post() instead. That function retrieves all of the details for the previous post which will give us the ability to customize things however we want.

Gathering Previous Post Link Details

Here’s a small function that will load the extra details we’re going to use.

if ( $prev = get_previous_post() ) {
   $prev_title = $prev->post_title;
   $prev_ex_con = ( $prev->post_excerpt ) ? $prev->post_excerpt : strip_shortcodes( $prev->post_content );
   $prev_text = wp_trim_words( apply_filters( 'the_excerpt', $prev_ex_con ), 15 );
   $prev_time_author = sprintf( __( '%s ago - by %s', 'byline' ), human_time_diff( get_the_time( 'U', $prev->ID ), current_time( 'timestamp' ) ), get_the_author( $prev->ID ) )
}

In the above code, we set up a few variables with the previous post’s title, excerpt, time and author. There’s a word limit set for the excerpt using wp_trim_words(). If you want to increase/decrease this value, change 15 to whatever you want.

Adding the HTML

With those variables set, we can now use some HTML to display all the info for our previous post.


Styling It Up

Here are the CSS selectors and some basic CSS:

.previous {
   max-width: 50%;
   width: 100%;
   float: left;
   font-size: 14px;
   padding-left: 40px;
}

.previous .icon {
   -moz-transform: translateY(-50%);
   -ms-transform: translateY(-50%);
   -webkit-transform: translateY(-50%);
   transform: translateY(-50%);
   font-size: 24px;
   position: absolute;
   left: 0;
   top: 50%;
}

.previous strong {
   font-size: 18px;
}

.previous em {
   font-size: 12px; 
}

I’ve also added a black background and white text to the example image below to make it stand out form the page.

Add More Details to the Previous Post Link example

Even though the example above is for the previous post link, the next post link can be displayed and styled in a similar way using get_next_post().

If you have a suggestion or comment, please use the form below.

Featured image provided by Gratisography.

The post Add More Details to the Previous Post Link appeared first on bavotasan.com.

Add Word Count to Single Posts in WordPress

Add Word Count to Single Posts in WordPress

Add Word Count to Single Posts in WordPress

This is just a quick little snippet to display a word count on the single post page in WordPress. Since it requires being placed within the loop, you can actually add it to any template file that includes a loop, such as archive.php or index.php.

The example below is for my premium Destin theme, which also has a basic version available for free through WordPress.org.

Since we’re editing the theme’s core files, I suggest first creating a child theme. This ensures that the changes stay intact when you update the theme in the future.

Check out my tutorial Creating a Child Theme in WordPress for guidance.

The Basic Function

Once you’ve created your child theme, include this short block of code in its functions.php file:

function bavotasan_word_count() {
   return sprintf(
      __( '%s words', 'text-domain' ),
      str_word_count( strip_tags( get_post_field( 'post_content', get_the_ID() ) ) )
   );
}

str_word_count is a simple PHP function that counts the number of words inside string. All we’re doing is loading up the post’s content as the string after we’ve stripped out all HTML tags. Otherwise, those tags would be counted as words and mess up the total.

With that code in place, we can add bavotasan_word_count() to the theme’s content.php file.

Displaying the Word Count

We want the word count to appear on the left with the post’s meta data, so include the new function within this block of code:


Here’s the new function:

Add it all together:


Check out the image below to see what it’ll look like:

Destin WordPress Theme with Word Count

It’s an easy enough mod that allows you to include a bit more meta data for each of your posts.

If you have any thoughts or would like to add to this tutorial, please use the comment section below.

Featured image provided by Gratisography.

The post Add Word Count to Single Posts in WordPress appeared first on bavotasan.com.

Eliminate Thumbnails for Custom Post Types

Eliminate Thumbnails for Custom Post Types

Eliminate Thumbnails for Custom Post Types

For a recent project, a client required a front end uploader to allow their customers to submit a consent form. Once they completed the form they could upload it as a PDF or JPG. Each form would be linked to a custom post type that contained other information about the user.

The PDFs presented no problems, but because WordPress created thumbnails when processing images, the JPGs were automatically converted into multiple image sizes.

Every consent form uploaded as a JPG added at least three extra files. That meant one hundred uploads would become four hundred, with three hundred files that would never be used. That could add up quickly and use a lot of space on their server for no reason.

Instead of having to go in and delete the extra files, I needed to find a way to nip the process in the bud and eliminate thumbnails for those custom post types before they were created.

When you upload an image, WordPress passes the meta data through a filter which processes the default images sizes: thumbnail, medium and full. You control the sizes under the Settings → Media admin page. You could set all sizes to zero and no extra images would be created whatsoever, though that stopped working in WordPress 4.0. Plus it wouldn’t have worked for this client since they only needed to files eliminated for the custom post type.

No More Extra Files

In order to eliminate thumbnails and stop creating those extra image sizes, I hooked into the intermediate_image_sizes filter.

This is the code I added to functions.php:

add_filter( 'intermediate_image_sizes', bavotasan_custom_intermediate_image_sizes, 999 );
function bavotasan_custom_intermediate_image_sizes( $image_sizes ){
   // @NOTE Be sure to change 'custom_post_type_slug' to the actual slug of your custom post type
   if ( isset( $_REQUEST['post_id'] ) && 'custom_post_type_slug' === get_post_type( $_REQUEST['post_id'] ) )
      return array();

   return $image_sizes;
}

First I checked if they were uploading to the custom post type, then I returned an empty array instead of the default image sizes. Simple enough.

No Thumbnails Whatsoever

If you want to stop this for all uploaded images, you could simplify the code even more:

add_filter( 'intermediate_image_sizes', bavotasan_custom_intermediate_image_sizes, 999 );
function bavotasan_custom_intermediate_image_sizes( $image_sizes ){
   return array();
}

Now you only have to return an empty array. No need to check for a custom post type.

Either one of the functions above will end up saving you a lot of space. If you don’t needs those extra files, eliminate them before they’re created.

If you know of a better solution, feel free to add your thoughts in the comment section below.

Featured image provided by Death to the Stock Photo.

The post Eliminate Thumbnails for Custom Post Types appeared first on bavotasan.com.

Permanently Delete Default WordPress Themes

Permanently Delete Default WordPress Themes

Stop Default WordPress Themes from Reinstalling

If you build a custom WordPress theme for a client’s site, I’m sure you spend some time deleting the themes (and plugins) that come pre-installed with WordPress. There’s absolutely nothing wrong with them, but if you’re planning on customizing things, you really don’t need to leave them there.

I see it as a little security measure so that the client doesn’t mess everything up by accidentally switching themes. Plus, it’s better to remove themes (and plugins) if you’re not using them. No need to waste the storage space.

A Small Problem when Updating WordPress

One problem that will keep occurring, is that those default themes will be re-installed every single time you upgrade WordPress to the latest release. It’s an annoying tick that might present a potential issue now that things upgrade automatically. I like to play it safe and thankfully there’s an easy way to make sure this doesn’t keep happening.

All it takes is a single line added to your wp-config.php file:

define( 'CORE_UPGRADE_SKIP_NEW_BUNDLED', true );

With that in place, the default WordPress themes (and plugins) won’t come back after you delete them.

Play It Even Safer

Once in a while, you might encounter an issue if you delete all the default themes when WordPress tries to switch back to a theme that no longer exists. This will leave you with the white screen of death, which most client’s frown upon.

With another line of code added to wp-config.php, you can ensure that any time this happens the default theme will be one of your choosing. No more blank screens.

define( 'WP_DEFAULT_THEME', 'theme-folder-name' );

Just be sure to change theme-folder-name to your actual theme’s folder name. If you’re using Magazine Premium you would change it to magazine-premium. If you were using Arcade, it would be arcade. And so on.

Read more about customizing wp-config.php in the WordPress Codex.

Featured image provided by Gratisography.

The post Permanently Delete Default WordPress Themes appeared first on bavotasan.com.

Single Post as Home Page in WordPress

Single Post as Home Page in WordPress

Single Post as Home Page in WordPress

Over the past few months, I’ve been working on a new premium theme for WordPress that would feature a single post on the home page. The one issue I needed to overcome was that I wanted that post to appear the same as it would on the single post page, which meant also displaying the comments.

This wasn’t as straightforward as you might think, though I did find a few different ways to make it happen.

Change the WordPress query

The easiest is to just insert two lines of code into the theme’s index.php file right before the WordPress loop:

is_single = true;
?>

Now you can set the Blog pages show at most number to “1” in Settings → Reading and it’ll work.

Not too complicated, right?

The major issue with this is that you’re tricking WordPress into thinking that the home page is actually a single post page. It’s not the most efficient way to code and you will end up having two pages that display the same content with different URLs, which is a no-no for search engines.

A better way to do the same thing (which I still think is a no-no), is to hook into pre_get_post and change the query a little:

is_home() || ! $query->is_main_query() )
      return;

   global $withcomments;
   $withcomments = true;
   $query->set( 'posts_per_page', '1' );
   $query->set( 'ignore_sticky_posts', '1' );
}
?>

This is more efficient, though still presents us with the issue of double content.

Check out the WordPress Codex for more info on pre_get_post().

Redirect the template

The only other solution I could think of that would make a single post the home page and not cause double content is to redirect to the latest post automatically.

There are a few different ways to accomplish this.

Open up index.php and replace the code with this:


Or if you prefer to hook it all in functions.php, here the code your need:

add_action( 'template_redirect', 'bavotasan_custom_template_redirect' );
function bavotasan_custom_template_redirect() {
   if ( is_home() ) {
      $latest_post_ID = get_posts( 'posts_per_page=1&fields=ids' );
      wp_redirect( get_permalink( $latest_post_ID[0] ) );
      exit();
  }
}

You can even add in a little ternary operator to check for sticky posts:

add_action( 'template_redirect', 'bavotasan_custom_template_redirect' );
function bavotasan_custom_template_redirect() {
   if ( is_home() ) {
      $latest_post_ID = ( $sticky = get_option( 'sticky_posts' ) ) ? $sticky : get_posts( 'posts_per_page=1&fields=ids&ignore_sticky_posts=0' );
      wp_redirect( get_permalink( $latest_post_ID[0] ) );
      exit();
  }
}

Check out the WordPress Codex for more info on template_redirect().

Update

After @Kaspars made some valid points in the comments below, I thought about the redirect and found another approach that might be better. This requires both the pre_get_post() hook and the template redirect, but it eliminated the double content and keeps your home page URL constant.

add_action( 'pre_get_posts', 'bavotasan_custom_pre_get_posts' );
function bavotasan_custom_pre_get_posts( $query ) {
	if ( ! $query->is_home() || ! $query->is_main_query() )
		return;

	global $withcomments;
	$withcomments = true;
	$query->set( 'posts_per_page', '1' );
	$query->set( 'ignore_sticky_posts', '1' );
}

add_action( 'template_redirect', 'bavotasan_custom_template_redirect' );
function bavotasan_custom_template_redirect() {
   $latest_post_ID = get_posts( 'posts_per_page=1&fields=ids&ignore_sticky_posts=0' );
   if ( is_single( $latest_post_ID ) ) {
      wp_redirect( home_url() );
      exit();
  }
}

You lose the ability to feature a sticky post, though there is probably a workaround that could even make that work. For now, I suggest using this technique.

I’d like to hear what others have to say so feel free to add your thought in the comment section below.

Featured image provided by Gratisography.

The post Single Post as Home Page in WordPress appeared first on bavotasan.com.