Move to the End and Beginning of a Word in PHPStorm

Another Macintosh keyboard shortcut that will be second nature to most Mac users is using ⌥← to move to the beginning of a word and ⌥→ to move to the end of a word. This moves the cursor to the left of the first character or the right of the last character. Try it in Mail. In TextEdit. In another editor you have installed like Sublime Text. It works the same across any Mac application I can think of except for PHPStorm. It feels so… wrong.

There is no existing Keymap setting in PHPStorm to move to the beginning and end of a word. Instead, there are command for moving to the next and previous words:

Move to Next Word

To fix this abomination, and affront to Clarus the Dogcow, you will need to install a PHPStorm plug-in called “Missing in Actions.” “Missing in Actions” actually will add quite a bit of functionality but, really, the thing that I was really looking for was the proper handling for ⌥← and ⌥→. Read more about Missing in Actions at the plug-in’s Github repository.

Go to PHPStorm > Preferences > Plugins. From there, choose “Browse Repositories.” Search for “Missing in Actions” and click the Install button. The plug-in will download and then you will be prompted to restart PHPStorm for the changes to take effect.

After restart is complete (you may have time to refresh your coffee), you will see new options available in the Keymap settings of PHPStorm:

  • Move Caret to Next End of Word
  • Move Caret to Previous Start of Word

Set these to ⌥→ and ⌥← and all will be well again.

Move Cursor to the Top of the Page in PHPStorm

I have started using JetBrain’s PHPStorm editor at work on a Macintosh and one of the things that has irked me is that some of the standard Macintosh keyboard shortcuts don’t work out of the box. For example, if you’re a seasoned Macintosh user, you are most likely used to using ⌘↑ to go to the top of the document. By default, in PHPStorm, this brings up the breadcrumb navigation. To get the default Macintosh behavior, you’ll want to edit the Keymap Preferences.

Go to PHPStorm > Preferences > Keymap to bring up the Preferences dialog. On the right-hand side of the dialog, you’ll be able to search for the command that you want to set the keyboard shortcut for. It wasn’t obvious to me what the command was for scrolling and moving the cursor to the top in PHPStorm, but I finally found that it is “Move Caret to Page Top.”

Move Caret to Top

Double-click this entry and set it to ⌘↑. Since PHPStorm assigns this by default to the “Show Breadcrumbs” command, you will be given an option to remove this existing mapping.

In addition to setting this keyboard shortcut, you can also set “Move Caret to Page Top with Selection” to Shift-⌘↑ and the corresponding commands for moving the caret to the bottom of the page. In my mind, this makes PHPStorm act much more like you’d expect an editor on the Mac to work.

Troubleshooting the White Screen of Death in WordPress

One question that I see asked a lot in the WordPress Support Forums is what to do when their website simply displays a white screen. This most likely represents a PHP fatal error that stops the server from generating the HTML for the browser to display.

How to Find the Problem

When PHP has a fatal error, it is usually logged to an error log file. The location and name of this file can change depending on the hosting server’s settings, but often the log file will be in the root of your website (maybe public_html) and called something like error_log or php_errorlog. If you don’t know, you should be able to search at your hosting company’s Support area for this information.

When you find out where the error log file is, open it up in a text editor or the File Manager in CPanel. The newest entries will be at the bottom of the file. If you see a PHP Fatal Error, this is most likely the culprit. Here is an example:

[19-Sep-2017 02:55:44 UTC] PHP Fatal error:  Call to undefined function load_theme_textdomain2() in htdocs/wordpress/public_html/wp-content/themes/twentyfifteen/functions.php on line 62

This tells me that there is a problem in the theme I am using, Twenty Fifteen, trying to call a function that does not exist. Now that I know this, I can look into fixing it.

Does the admin load?

If you go to your site’s home page and get the dreaded white screen, try to access your site’s administration panel at http://<your domain>/wp-admin/. It is possible that the error is only manifesting itself on the front-end and that you will still be able to get into your admin panel.

If you were able to get useful information from the error log, you should be able to disable either the problem theme or plug-in and be back in business. If you were not able to get information from the error log, you can try changing the theme to one of the included WordPress themes to see if there is an issue with the active theme. Or, if that doesn’t work, you can disable plug-ins one at a time, loading the home page of your site in a different tab, between plug-in disables to try to track down the errant plug-in.

Does the admin not load?

If the administration does not load there are a couple of things you can do to disable plug-ins. You can rename the folder of your plug-ins. If WordPress cannot find the plug-in file, it will disable it:

Plug-in was disabled

Another option, if you have access to the database through a tool like phpMyAdmin.phpMyAdmin is often available in CPanel and other hosting control panels. Go to the wp_options table and look for the record with the option_name of “active_plugins.” The option_value of this record will contain a serialized list of active plug-ins for your site. Here is an example of a site with Akismet and Contact Form 7 active:

a:2:{i:0;s:19:"akismet/akismet.php";i:1;s:36:"contact-form-7/wp-contact-form-7.php";}

Delete the option_value completely and this should disable all plug-ins for your site.

Need to change your active theme? There are two rows for this, also in wp_options. You can look for the option_name values of “template” and “stylesheet.” Change these values to a different theme available on your site.

Why did my site break all of a sudden?

It is impossible to give one answer for all the possibilities, of course, but I have found that one of the common causes of this issue would be an upgrade to the version of PHP running on your site. If a plug-in is using a deprecated function from PHP 5, and the host switches your account to use PHP 7, this could cause a problem. Do a Google search for the error you found in your error log to try to find out more. If you suspect the issue is a PHP upgrade and you have access to CPanel, there is often a way to change the version of PHP for your site. Look for an icon like this in CPanel:

PHP Version Manager

If you have that, try reverting to an older version of PHP.

This article just scratches the surface of troubleshooting problems with a WordPress site being down but hopefully it will help get you started on the right track for figuring out your issue.

Tab Modifier Plus Chrome Extension

As a web developer, I often find myself with local, staging, and live versions of the same website. Obviously, one can tell which environment one they are on by viewing the address in the browser bar. I find it handy to have an additional visual cue, though, to make it even clearer. I have found a neat little extension for Chrome or Opera called Tab Modifier Plus that allows you to set custom favicons for tabs based on the URL.

When adding a new tab rule, you can match the URL by text matching or with regular expressions.

Add New Rule

In my case, my local sites all begin with “http://stirrell.” so I can use that with a “Starts with” rule. Once you have set up the URL match, you can then choose a number of options for the tab:

  1. Choose a favicon.
  2. Pin the tab.
  3. Prevent the tab from being duplicated.
  4. Ask for confirmation before closing the tab.
  5. Mute sounds on the tab.

In my case, I will choose an included favicon available in Tab Modifier Plus, a green circle, to let me know I am on a “safe” site:

Custom favicon

Then, of course, I can use a red circle for live web sites.

Although I use Tab Modifier Plus as a visual clue for “safe” and “dangerous” sites, I can see many other uses for this nicely-made extension. I appreciate that the options page uses Google’s Material look-and-feel. I have also tested in Opera and it seems to work just fine. I definitely recommend this extension.

Dynamically Overriding a Page’s Template

It is easy to override the template for a post or page in WordPress in a few ways. For example, the naming of page template files can be used to override a single page’s template:

  • page-{id}.php
  • page-{slug}.php

Or, a page template can be chosen in the Page Attributes section when editing a page:

Choose a Template

This works great when you always want a page template to be used for a particular page. But what if you need to change a page’s template based on something that might change? Like the current user’s role, for example? Well, you can use the template_include filter in WordPress to override the normally-used template in a function.

Start out by attaching a function to the filter:

add_filter( 'template_include', 'dynamic_page_template' );

This can be added to your theme’s functions.php file or to a custom plug-in. In this example, the function called dynamic_page_template will be invoked. This function will accept the parameter, $page_template, which is the $page_template that is to be used. If you want the page template defined in a way above (by the template name or the selected template in the Page Attribute area) to work as normal, simply returning $page_template will accomplish this. However, we can also set $page_template to something different and return that instead. Here is a simple example:

function dynamic_page_template( $page_template ){
  global $post;
  if (100 == $post->ID) :
    $page_template = get_template_directory() . "/page-test.php";
  endif;

  return $page_template;
}

In this example, we are pulling in the $post (or page) information by calling it globally. Then, we can check for the post ID value. If the ID is 100, we are setting the page template dynamically to the page-test.php file in our theme. The get_template_directory call gets us the directory for our theme. Now, even if we have a file named page-100.php, our function will take precedence.

Hiding the WordPress admin bar on certain pages

There may be times when you would like to hide the WordPress admin bar on certain pages. Maybe the admin bar interferes with the design, for example. This can be especially true for things like pages opening up in a lightbox. Fortunately, it is not too difficult to hide the admin bar on certain pages with a filter in WordPress.

There is actually a filter in WordPress named, logically enough, show_admin_bar. This filter will show the admin bar if true is returned but not show the admin bar if the returned value is false. You pass the $bool value in which is WordPress’s own determination if the admin bar should be shown or not. So, in your theme’s functions.php file, you can add the following code:

function my_theme_hide_admin_bar($bool) {
  if ( is_page_template( 'page-pop-up.php' ) ) :
    return false;
  else :
    return $bool;
  endif;
}
add_filter('show_admin_bar', 'my_theme_hide_admin_bar');

In the code above, we are simply checking to see if the page we’re on is using the template file, page-pop-up.php. This is a theme file that I used to display pages opening up in a lightbox. If the page is using that template, we return false to suppress the showing of the admin bar. If not, we return the usual $bool value set in WordPress and it will act as normal. Of course, the template conditional is just one example. You could also use other WordPress conditionals to turn the admin bar off for a myriad of other circumstances.

Conditional Required Contact Form 7 Fields

Sometimes you may want to have a required field in Contact Form 7 only when another form field has a certain value. For example, if someone has an option to choose their preferred method of contact between email and telephone, you’d want to make the email address field or the phone call field required accordingly. This isn’t too difficult to accomplish in Contact Form 7. You can look at how Contact Form 7 validates text and email fields by viewing its code in:

contact-form-7/modules/text.php

Around line 91, you will see the validation filters defined by Contact Form 7:

add_filter( 'wpcf7_validate_text', 'wpcf7_text_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_text*', 'wpcf7_text_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_email', 'wpcf7_text_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_email*', 'wpcf7_text_validation_filter', 10, 2 );

Then, you can look at the function that handles the validation, wpcf7_text_validation_filter. The function accepts two parameters – $result and $tag. The $tag is the field being validated and the $result is, well, the result of the validation. In other words, did something go wrong?

The user-entered text of the field being checked is assigned to $value. Then, the function checks the current tag type. Is it text? Email? And it will process it accordingly. If a value is empty but the field is required, for example, the result will be invalid:

$result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );

In this case the Contact Form 7 error message for required fields is given as an error (wpcf7_get_message( ‘invalid_required’ )). If $result-invalidate() is called, that field will fail validation and you will get a form error.

We’re not, of course, going to modify the plug-in’s files directly. We want to make our plug-in modifications safe from future plug-in updates so we will tie into the same filters that the plug-in uses. I can put this code in my theme’s functions.php file or put it into a my own plug-in. In my example, I am setting two conditional required fields – email and phone number. So, I will need to set my own custom validations for both text and email fields:

add_filter( 'wpcf7_validate_text', 'my_site_conditional_required', 10, 2 );
add_filter( 'wpcf7_validate_text*', 'my_site_conditional_required', 10, 2 );
add_filter( 'wpcf7_validate_email', 'my_site_conditional_required', 10, 2 );
add_filter( 'wpcf7_validate_email*', 'my_site_conditional_required', 10, 2 );

For both the text (phone) and email fields, I am using the function, my_site_conditional_required, for my own custom validations. Here is my complete function:

function my_site_conditional_required($result, $tag) {
    $tag = new WPCF7_Shortcode( $tag );

    $name = $tag->name;

    $value = isset( $_POST[$name] )
        ? trim( wp_unslash( strtr( (string) $_POST[$name], "\n", " " ) ) )
        : '';

    if ( "phone" == $name && 'Phone' == $_POST['contact-method'] ) :
        if ( '' == $value  ) :
            $result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );
        endif;
    endif;

    if ( "email" == $name && 'Email' == $_POST['contact-method'] ) :
        if ( '' == $value ) :
            $result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );
        elseif ( ! wpcf7_is_email( $value ) ) :
            $result->invalidate( $tag, wpcf7_get_message( 'invalid_email' ) );
        endif;
    endif;

    return $result;
}

Here is how it works. I am doing the same thing that Contact Form 7 does with setting the $value. Then, instead of checking the tag type, I want to check the tag name. I specifically want to look for the fields named “phone” or “email.” I also have a dropdown named “contact-form” so I can check the $_POST value of contact-form and use that to see if the field being checked should be required. If $_POST[‘contact-form’] is equal to “Phone,” I want the phone field to be required:

if ( "phone" == $name && 'Phone' == $_POST['contact-method'] ) :
        if ( '' == $value  ) :
            $result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );
        endif;
endif;

I have an extra check for the email. I don’t just want to require the email address, I want to make sure it is a valid email address as well. Contact Form 7 provides a function to check an email, wpcf7_is_email:

elseif ( ! wpcf7_is_email( $value ) ) :

As you can see, my custom function works very similarly to the code in the plug-in. Finally, you probably want to show the user the field that is required based on their downdown selection. I added empty spans after the field labels that I can use to add and remove informational asterisks from:

<label class="email-label">Email</label>

Then, I can use jQuery to add and remove the asterisks:

jQuery(function() {
  add_required_asterisks();
  jQuery("select[name='contact-method']").on('change', function() {
    add_required_asterisks();
  });
});

function add_required_asterisks() {
  if ( jQuery("select[name='contact-method']").val() == "Phone" ) {
    jQuery(".phone-label .asterisk").html("*");
    jQuery(".email-label .asterisk").html("");
  }
  else {
    jQuery(".phone-label .asterisk").html("");
    jQuery(".email-label .asterisk").html("*");
  }
}

I created a JavaScript function that will see what my dropdown menu (named “contact-method”) is set to and then, based on that, turn the asterisks on or off. Then, I call that function on page load and, whenever the dropdown changes:

jQuery("select[name='contact-method']").on('change', function() {
add_required_asterisks();
});

Quick WordPress Tip – Upload to a Post Without Switching Tabs

Here is a quick tip for WordPress users out there. When you are adding, say, a Featured Image to a post, you are brought to the Media Library window that includes an “Upload Files” tab. This might lead you to believe that you need to switch to that tab in order to upload a new image file. Actually, though, you can save yourself some clicks by simply dragging a photo onto the Media Library. No need to switch tabs.

Drop to Upload

Saving changes made in Chrome’s Web Inspector

It is wonderful to be able to use Chrome’s Web Inspector development tools to tweak the CSS of a web page to get elements just right. However, what is the best way to apply these changes to the actual stylesheet? One could, of course, just move these changes by recreating the tweaks to the CSS document manually. There is a way, though, to actually save out the modified CSS file right from the Web Inspector. To do this, simply click on the CSS link at the right-hand side of the Styles palette:

CSS link

 

Clicking on the link will open up the modified CSS file in the Web Inspector’s Sources tab:

sources

 

Right-clicking on the opened CSS file will allow you to view the changes made to the CSS file via the Elements tool (Local Modifications) as well as save out the changed CSS file which you can use to replace the old CSS.

Right click