Web & Graphic designer.

Specializing in custom WordPress site development and graphic design.

Default fallback featured image for posts and pages

Default fallback featured image for posts and pages

There are times when your theme is set up to show uploaded featured images in blog and page headers. There could be times, though, that a user might not be able or want to upload a featured image. In this case, it might be preferable to show a predefined fallback image to the viewer. Here is how to do it.

Install the Default featured image plugin and activate it. Then head to Settings -> Media, scroll down to the Default featured image area and upload a default image for your blogs and pages. After doing that, content that does not have an uploaded featured image attached but is set to show it on the page will use the default uploaded image instead.

You can customize the behavior of the plugin, as well. For example, to exclude the default image from pages, you would add the following code to your functions.php of a functionality plugin.

function dfi_skip_page ( $dfi_id, $post_id ) {
  if ( is_page() ) {
    return 0; // invalid id
  }
  return $dfi_id; // the original featured image id
}
add_filter( 'dfi_thumbnail_id', 'dfi_skip_page', 10 , 2 );

There are other customizations you can apply, head over to the FAQ area of the plugin to have a look!

How to resize the WordPress Customizer featured imageimage

How to resize the WordPress Customizer

I tend to write quite a lot of CSS to customize my websites. That’s why I almost always use an external text editor. A dedicated text editor or IDE (Integrated Development Environment) also gives you more control and helps writing CSS faster. The Customizer is no that bad for writing CSS, though, and if the amount of CSS you write is not enormous you could actually get away with it. Thing is, I’ve always found the WordPress Customizer’s width, quite narrow when editing CSS. There are two ways to solve this.

Method 1: Custom code

Add the following PHP code to your functions.php or use a functionality plugin. I would suggest using a child theme for this purpose.

add_action( 'admin_enqueue_scripts', 'the_dramatist_admin_styles' );
function the_dramatist_admin_styles() {
    wp_enqueue_style( 'admin-css-override', get_stylesheet_directory_uri() . '/admin.css', false );
} 

Then create a CSS file called admin.css inside your child theme directory and add the following:

.wp-full-overlay.expanded {
    margin-left: 500px;
}
#customize-controls.wp-full-overlay-sidebar {
    width: 500px;
}

Adjust the width value according to your liking.

Method 2: Using a plugin

Install and activate the Admin CSS MU plugin, then go to Appearance -> Admin CSS MU and write the previous CSS code in the Admin CSS text area at the top. Then hit Save CSS.

Admin CSS MU - Custom admin CSS
Admin CSS MU – Custom admin CSS

Again, adjust the width value according to your liking and enjoy your new customized width!

GeneratePress Elementor image

How to hook Elementor headers and footers in GeneratePress

GeneratePress and Elementor is a great combo for fast website building by combining the power, flexibility and speed of both tools.

Even though it’s perfectly possible to have great looking headers and footers in GP, some users, specially non-coders might get intimidated by the fact they might need to write some CSS to be able to have their headers and footers exactly as they have envisioned.

With the advent of GenerateBlocks, which is coming along very nicely and it’s currently on beta, GP will gradually give the user the ability to design headers and footers more visually.

For existing Elementor users that want to stay in the GeneratePress ecosystem and take advantage of the speed and lightweight nature of the theme, there are a few solution.

GeneratePress Premium and Elementor Premium

This method assumes you have GP Premium and Elementor Pro. Create a header and footer template in Elementor by going to Templates -> Add New. Select, either Header or Footer, name your template and click the CREATE TEMPLATE button to start editing the template.

Elementor template creation popup image
Elementor template creation popup

You can then assign logo and menu elements to your header, add a hero image, etc. For the footer, you are free to create columns as widgets and also create a footer bar. After creating your templates in Elementor and saving them, do not assign them anywhere in the PUBLISH SETTINGS. Basically, don’t add any conditions. Just hit SAVE & CLOSE.

Elementor template creation - Publish Settings image
Elementor template Pubish Settings

Exit back to the WordPress admin and go view your Elementor templates by selecting Templates -> Theme Builder. You will see a shortcode entry at the right of the template entry. Take note of that.

Now the magic of GeneratePress happens!

Create a layout element by going to Appearance -> Elements. Click Add New and select a Layout element. Name your element and go to the Disable Elements tab. Put a checkmark on Site Header, Primary Navigation and Footer. Now, go to the Display Rules tab and select Entire Site from the Location section’s dropdown. Click Save to save your layout element. We are effectively creating a custom layout where the checked GeneratePress items are going to be disabled on the theme for the entire site. That will allow us to hook the Elementor templates through a Hook element!

GeneratePress Layout element - Disable Element image
GeneratePress Layout element – Disable Element
GeneratePress Layout element - Display Rules
GeneratePress Layout element – Display Rules

Go to Appearance -> Elements. Click Add New and select a Hook element. Give it a descriptive name, copy the shortcode from the Elementor theme builder template list next to your header template and paste it inside the content area. In the Settings underneath, select header from the Hook dropdown and put a checkmark on Execute Shortcodes. On the Display Rules tab select Entire Site from the Location section’s dropdown, then save the element.

GeneratePress Header hook element
GeneratePress header hook element

If you view your site now, you will see that the Elementor header template has been inserted in place of the normal GP header. Great!

Similarly for the footer, create a layout element by going to Appearance -> Elements. Click Add New and select a Hook element. Give it a descriptive name, copy the shortcode from the Elementor theme builder template list next to your footer template and paste it inside the content area. In the Settings underneath, select footer from the Hook dropdown and put a checkmark on Execute Shortcodes. On the Display Rules tab select Entire Site from the Location section’s dropdown, then save the element.

GeneratePress footer hook element
GeneratePress footer hook element

Your Elementor footer template will automagically appear at the bottom of your site!

This method completely replaces the theme’s header and footer sections. This means that any header and footer schema markup added by the theme will also be removed. The absence of schema won’t stop the page from being indexed. You just won’t have the additional information or influence over your SERP output, and would not have a good SEO impact. For me personally, it’s one of the main reasons I keep my headers and footer “in-house” using theme functionality apart from the whole performance gain of only using GeneratePress.

There is a way to counteract the issue, though. Read on!

GeneratePress Free and Elementor Free

The following method will also work with GeneratePress Premium and Elementor Pro. Also, the plugin supports a wide range of themes that are written according to WordPress standards. You must have no doubt in your mind that GeneratePress is such a theme!

Install the Elementor – Header, Footer & Blocks plugin and activate it. Go to Appearance -> Header Footer Builder and adjust Elementor Header Footer options accordingly. In the screenshot below, I selected Header as a template type and set it to display on the entire site. You can also select Before Footer and Footer as template types. The Custom Block type allows you to insert the template anywhere on your site through the use of a shortcode.

Elementor header footer and blocks template image
Elementor header footer and blocks template

Hit Publish (or Save Draft) and click the Edit with Elementor button. Go crazy with your design and Publish when you are done.

Check your site to see your custom Elementor template appear on you theme’s header! That was too easy!

This method requires no additional GP elements to be created and as mentioned above, it can work with both the free and premium GP version as well as the free and Pro version of Elementor.

The added benefit of this method is that your header and footer schema markup from the theme IS being retained and that’s a big plus on my book!

That will be all for today, let me know if you have any questions/comments in the form below!

I am an experienced web and graphic designer and expert in the GeneratePress theme. Get in touch if you want to discuss how I can help you with your next project!

Elementor FREE - Replace icon with a custom one

Elementor FREE – Replace icon with a custom one

Elementor Pro makes it easy to add icons in various places on your website. But on the free version of Elementor, there is no way to upload a custom icon unless you upload your own and make some CSS changes. In this tutorial, I am going to show you how a simple way of doing just that. It’s very easy!

Getting the icon

First of all, go and find an icon that you like or design your own. There are tons of icon font sites including IcoMoon and FLATICON. Some font icon services allow you to change the background icon color. For instance, FLATICON allows you to do that once you register an account. Just click on the FLATICON edit icon icon at the top right of the screen and change the color. You would, then, need to save the icon as SVG format. Size is not important as we are going to set that up in our CSS. SVG is a vector-based image file format so the overall size will not affect the file size like in the case of a PNG image.

Uploading the icon

To be able to load the SVG file to our Media library, we would have to install a very useful plugin called SAFE SVG. Once installed, we can head to our media library and upload our custom icon. Once the icon upload, take note of the image URL that you see at the right side once you click on the image in the Copy Link read-only text field. It will be in the following format.

https://www.siteurl.com/wp-content/uploads/2020/02/telephone-icon.svg

The bit of code we are interested in is the text after the main site URL. We will use that in our CSS when we add our custom icon as a background image.

Adding an icon list widget in Elementor

Once you are done you make use of one of the icon widgets in Elementor. In my case, I inserted an, with the  Icon List and selected a phone icon from the icons provides. At this point, it doesn’t matter what icon you select because, as mentioned earlier, we are going to replace it anyway.

Call us now - Elementor icon
Icon list with Elementor icon

Finally, with the icon list selected, go to the Advanced tab and in the Advanced section add a CSS Class, like this:

Elementor icon list CSS class

Adding the CSS

Adding this CSS to your child theme or in the Customizer will create all the magic:

/* Header telephone icon */
.call-us span.elementor-icon-list-icon i {
  display: none;
}
.call-us span.elementor-icon-list-icon {
  background: url("/wp-content/uploads/2020/02/telephone-icon.svg") no-repeat center center;
  width: 50px;
  height: 50px;
  margin-right: 1rem;
}

In the above CSS, we first hide the original icon that we added in Elementor. Then we assign our custom icon as a background image to the parent container, set it to not repeat and center it horizontally and vertically. Next, we set the width and height of that container and finally, we add a bit of right margin to create some indentation to our text.

Call us now - Custom icon
Icon list with custom icon

What about other Elementor icon widgets?

If you would like to use an Elementor icon widget instead, the CSS selectors would be slightly different:

.call-us .elementor-icon i {
  display: none;
}
.call-us .elementor-icon {
  background: url("/wp-content/uploads/2020/02/telephone-icon.svg") no-repeat center center;
  width: 50px;
  height: 50px;
  margin-right: 1rem;
}

Inspecting the CSS with your browser’s developer tools should be fairly simple to detect the right selectors.

That’s it! I hope you found the tutorial useful. If you are thinking about upgrading to Elementor PRO, you can use my affiliate link below:

GET ELEMENTOR PRO

Server backup on Cloudways - Header image

Server backup on Cloudways

Cloudways allows you to set up a backup schedule for your server. The server backup will back up your application files and databases. In this small article, I am going to explain how the system works in case you had any doubts or concerns.

Scheduling your server backup

Click on the Servers tab from the top of the Cloudways Panel. Then, select your server and head over to the Backups tab in the Server Management area.

Cloudways server backup panel
Cloudways server backup panel

There, you will find various options for finetuning and set up the schedule:

Backup frequency

Here you can schedule a backup by selecting the exact time. You can select intervals from 1 Hour up to 7 Days.

Schedule time

Here you set the actual time in which the backup is to be taken. You can set the time in hours and minutes from the dropdown fields.

Backup Retention

Here you can select how long the backups are going to be kept in storage and be available to you for restore.  You can select in multiple of one week intervals from 1 week up to 4 weeks.

Local Backups

Usually, a backup will be kept in a remote Amazon bucket storage. If you activate local backups, the backups will also be saved in your local server disk. Please, bear in mind that if you activate that option, the backups WILL count towards your server storage quota.

On-demand backup

On the right side of the panel, you can select to perform an on-demand backup of your server. This type of backup will be available on your server as a downloadable file ready for you to be downloaded through SFTP. The location of that backup would be inside a folder called local_backup at your server’s root folder once you connect to it through SFTP. Note that in order for the on-demand backup to work and for a copy to be stored on your server, you will need to have Local Backups activated from the previous step. If you don’t have the option activated, then the backup will only be taken remotely on the Amazon bucket.

Deleting local backups

In case you have any local backups saved in your server, you can delete them all by enabling the local backup functionality if it is not enabled, hit the SAVE button and then click the trash icon on the right. You can then disable local backups if you wish and hot the SAVE button again.

Cloudways - Local backup deletion
Local backup deletion

Restoring from backup

Once backups have been performed they can be restored individually for each application you host on your server. Select your application by clicking Applications from the top, select your Application and click the Restore tab under Application Management.

Cloudways - Restoring an application
Restoring an application

Just select a backup from the dropdown list and click the RESTORE APPLICATION NOW button underneath.

Conclusion

Backing up and restoring a server is a great practice for peace of mind knowing that your precious files are backed up and ready for recall in case of loss of data. What I like about the Cloudways backup is that it can backup remotely to an Amazon bucket storage and that could be a great thing if you lose access to the backend of your site for some reason. As always, I would suggest that you try the backup and restore process and see if it actually works for you and everything is restored correctly.

Take care and good luck!

If you liked the article and thinking of signing up with Cloudways managed hosting, you can click on my affiliate link and signup.

How to deal with the "Error 503 Backend fetch failed" Varnish error on Cloudways

How to deal with the “503 Backend fetch failed” Varnish error on Cloudways

Varnish Cache is a web application accelerator also known as a caching HTTP reverse proxy. It can be installed in front of any server that speaks HTTP and can be configured to cache the contents. Varnish Cache is really, really fast. It typically speeds up delivery with a factor of 300 – 1000x, depending on your architecture.

Cloudways implement Varnish to their web technology stack along with other caching layers.

Varnish can be activated on your Cloudways server by clicking on the Servers link on top then click on your server name, select Manage Services form the Server Management menu on the left and activate Varnish from the MANAGE SERVICES panel on the right.

Cloudways - Manage Services
Cloudways – Manage Services panel

As you can see, from there you can also purge your server’s cache or disable the cache altogether.

Apart from that, though, you can also enable/disable the Varnish cache for each of your applications. Just select the Applications link from the top of your Cloudways panel then select your application from the list that appears, click the Application Settings on the left from the Application Management panel and enable/disable accordingly.

Cloudways - Applications Settings
Cloudways – Applications Settings panel

Instead of having to go to your Cloudways panel Application Settings, Cloudways has developed a plugin called Breeze that can be installed on your WordPress installation so that cache can be cleared from there in a convenient way. The plugin can also be used to minify your HTML, CSS and JavaScript and adjust other settings related to Gzip compression and Browser Cache. There are also settings to optimize your database tables and use your CDN to offload your cache.

I have been using Cloudways Managed WordPress hosting for some time now and I am more than happy. One of the few issues that bug me sometimes is an error I get usually after I clear my application Varnish cache and visit a page on the frontend. It doesn’t happen very often but when it does, I would get this page on the browser:

503 backend error image
Varnish 503 Backend error

A couple of page refreshes usually fix the issue but I wasn’t happy that this was happening in the first place and I wanted a resolution on this. Searching for a solution, I discovered that there were quite a few cases of users having the exact same problem but solution was vage at best and no official post was published by Cloudways, probably  due to the fact that each user case was unique.

I decided to initiate a ticket through the Cloudayws chat support. After a few moments, an agent asked me to confirm my server IP and I was given a few things to try out that could potentially fix the issue. I decided to write this blog post while I was implementing a few of those changes so other users could potentially benefit from what I had done.

Excessive number of applications

The good thing about Cloudways is that you could install a number of applications on the same server. Of course, the higher the number of applications you install, the more strain you put on your server. You could potentially alleviate the Varnish error on your server by having a small number of applications.

Server Execution Limit and Memory Limit

From your Server Management panel, under the Settings & Packages on the BASIC tab, there are a couple of settings that could help. I was told that the Execution Limit setting could be set to 1200 and the Memory Limit setting to 512.

Cloudways - Server Management
Cloudways – Server Management panel

Execution Limit is the amount of time a request is allowed to run across the stack. Web servers set a time limit on how long a script can run. This is done to prevent the webserver from abuse. Since WordPress is made up of PHP scripts, each script has to run completely within the set time limit. On Cloudways this time limit is usually 60 seconds, and in most cases, this is more than enough time for a script to run. However, if a PHP script runs for longer than the set time limit, PHP cuts short the execution. It then returns the fatal error: maximum execution time exceeded message.

Memory Limit is the maximum amount of Memory in (MB) that a PHP request is allowed to allocate. That means that if multiple requests were to use more than your server’s memory, you could potentially run out of memory so it depends on your server’s resources and the number of applications currently running on your server. So if you were to modify this settings, remember to monitor performance if your server resources are minimal.

Disable WP-CRON on on all applications

A suggestion was made to disable WP-CRON on all applications to optimize memory consumption on the server. This is easy to do. Just open the wp-config.php file located on your WordPress installation root folder and add the following just before the /* That's all, stop editing! Happy blogging. */ line:

define('DISABLE_WP_CRON', 'true');

Then, save the file and reupload it on the server. You can then easily add a manual CRON job to your application by following this article. Alternatively, you can create your own CRON job on an external website such as this one that allows you to create CRON jobs from minute-by-minute to once a year, for free.

Checking your cache plugin settings

In case you have another caching plugin install, there might be some settings that need to be tweaked. You can experiment with some settings so that there are no conflicting issues. For example, I use Autoptimize to minify my scripts so I have minification deactivated in the Breeze plugin.

Disable Varnish on php stack applications

It is not recommended from Cloudways to have Varnish activated on custom PHP applications. You can easily disable it from your Application Settings console (see screenshot above).

Attacks on your login page

Usually malicious users or bots might be targeting your login pages and as a result, your server resources would be consumed and produce the 503 error. You could make use of your security plugin to apply a reCAPTCHA for all your login and registration page and also change your default login URL. For example, Wordfence has a function to enable reCAPTCHA on the login and user registration pages by going to Wordfence->Login Security, select the Settings tab and activate the Enable reCAPTCHA on the login and user registration pages checkbox. Various other security plugins can also do the job.

Attacks from WordPress XML-RPC

XML-RPC is a method that WordPress uses to communicate with external services and transmit data. With the introduction of the upcoming WordPress API we can expect XML-RPC to be eliminated entirely. Attackers could use brute force attacks through xmlrpc.php to gain access to your site. Hackers could also use the pingback feature in WordPress to send pingbacks to thousands of sites instantaneously. This feature in xmlrpc.php gives hackers a nearly endless supply of IP addresses to distribute a DDoS attack over. Those attacks could be easily overloading your server thus causing the 503 error.

You can use the XML-RPC Validator to examine if your site has XML-RPC running. If the test fails that means that XML-RPC is deactivated. To deactivate it you can make use of the Disable XML-RPC plugin or manually by adding the following to your .htaccess file:

# Block WordPress xmlrpc.php requests
<Files xmlrpc.php>
order deny,allow
deny from all
allow from 127.0.0.1
</Files>

Some security plugins like Wordfence also have the functionality to deactivate XML-RPC, built-in. Just head to WordFence->Login Security, select the Settings tab and enable the Disable XML-RPC authentication checkbox.

Analytics monitoring

The application motoring tool on the Cloudways console can be used to monitor incoming traffic to your website. From there, you can check which IP requests and URLs accessing your site. You can find them by going to Applications->Application management -> Monitoring -> Analytics -> Traffic.

Cloudways traffic monitoring
Cloudways traffic monitoring

And there you have it!

Please, bear in mind that the above settings are not guaranteed to fix the issue and I suggest you try any changes on a cloned server beforehand. There is some useful info here for sure, though, and it would be interesting to see if any of these work for you.

You can visit the Cloudways Managed Cloud Hosting Platform and see if they have any plans that interest you. If you liked the article and thinking of signing up with Cloudways managed hosting, you can click on my affiliate link and signup.

GeneratePress theme tutorial: Blog thumbnail image fixed height fix

GeneratePress theme tutorial: Blog thumbnail image fixed height fix

Today I would like to address an issue that seemed quite tricky in the beginning but I was able to find a solution though some thorough googling! GeneratePress Premium has a nice blog layout addon that allows blog archives to be displayed as a grid. On top of that Tom Osborne the creator of GeneratePress has created a WordPress plugin called WP Show Posts which allows you to display posts anywhere on your website using an easy to use shortcode. I have recently used both of those mentioned functionalities on my latest creation, a support community forum and resource repository for the WordPress Brizy page builder. You can view the community page at https://brizycommunity.com.

While building the website I run into an issue regarding the height of the blog thumbnail images on the blog archive. Depended on the size of the feature image uploaded for every single post, some thumbnails would appear with varied heights making the blog layout appearing a bit off.

Blog grid layout thumbnail variable height
Default blog grid layout – Not all images have the same height

I could set a fixed width and height by going to Layout->Blog and set width and height pixel values for the Archive featured image dimensions but then I would lose all responsive design functionality for various desktop and mobile device screen sizes since due to the fixed size nature of the thumbnails.

Blog grid layout thumbnail variable height - Mobile View
Default blog grid layout – Mobile View

A better way I found out was to actually utilize some sweet CSS. I wanted that CSS to be applied only at a minimum size of 769px, my mobile breakpoint.

@media( min-width: 769px ) {
  
  .inside-article .post-image a img {
    height: 174px;
    object-fit: cover;
    object-position: center;
  }
  
}

In the above code, I set the thumbnail archive feature image to a set height of 174px. I also set the object-fit CSS property cover and the object-position property to center. That way the thumbnail dimensions would not stretch out of proportions but instead zoom into the image slightly to keep their aspect ratio intact.

Blog grid layout thumbnail equal heights

Also that way, I would still retain equal heights on a 2 column layout but switch to the default behaviour on a one column layout.

Blog Grid layout - 2 columns
Blog Grid layout – 2 columns
Blog Grid layout - 1 column
Blog Grid layout – 1 column

The same issue was also present on the WP Show Posts shortcode on the homepage:

WP Show Posts - Latest News - Varied thumbnail heights
Thumbnails with unequal heights

Adding some CSS to the existing code fixed the variable thumbnail image height issue:

@media( min-width: 769px ) {
  
  .inside-article .post-image a img {
    height: 174px;
    object-fit: cover;
    object-position: center;
  }
  
  section.wp-show-posts article .wp-show-posts-image a img {
    height: 232px !important;
    object-fit: cover !important;
    object-position: center !important;
  }
  
}
WP Show Posts - Latest News - Fixed thumbnail heights
Thumbnails with fixed heights

I provide advanced customization work for GeneratePress, so please get in touch if you need any work done.

Hope you find that useful. Till next time, then!

UPDATE

GP Premium 1.10.0 update brought a new Featured Image Resizer feature and it works quite well. To adjust settings according to our previous examples, we would first remove the CSS provided in the article, then head over to Appearance -> Customize -> Blog and scroll down to the Feature Images section. Set Width to 100% and adjust Height accordingly.

GP Premium 1.10.0 update - Featured image resizer
GP Premium 1.10.0 update – Featured image resizer
Set custom category post type archive as homepage - image

Set a custom category post type archive as your homepage

Sometimes you might have a custom category post type archive that you want to display as your homepage. Your blog page might already be “occupied” by a link that lists all your blog items possibly including the custom post type items as well. Surely, you can add a category menu item to your main navigation menu but you would have to add a redirect from that link to your homepage and that’s not a good idea for performance and SEO purposes. Just a clarification, by homepage, I mean the page that gets loaded when users first visit you website URL and can be set at Settings->Reading->Homepage, not to be mistaken by the blog page that can also be set on the same screen.

Reading settings
WordPress Reading settings

So the process to achieve the above would be to create a page that would act as your home page and then setting that page as your homepage like the screenshot above. In my case, I have created a Videos page for a video custom post type. Then you would add the following code inside your functions.php file or though a code snippet.

function prefix_downloads_front_page( $query ) {
    // Only filter the main query on the front-end
    if ( is_admin() || ! $query->is_main_query() ) {
        return;
    }
    global $wp;
    $front = false;
  // If the latest posts are showing on the home page
    if ( ( is_home() && empty( $wp->query_string ) ) ) {
        $front = true;
    }
  // If a static page is set as the home page
  
    if ( ( $query->get( 'page_id' ) == get_option( 'page_on_front' ) && get_option( 'page_on_front' ) ) || empty( $wp->query_string ) ) {
        $front = true;  
    }
    if ( $front ) :
  
        $query->set( 'post_type', 'video' );
        $query->set( 'page_id', '' );
        // Set properties to match an archive
        $query->is_page = 0;
        $query->is_singular = 0;
        $query->is_post_type_archive = 1;
        $query->is_archive = 1;
    endif;
  
  //Fix pagination
  if ( get_query_var('paged') ) {
        $paged = get_query_var('paged');
  } elseif ( get_query_var('page') ) {
        $paged = get_query_var('page');
  } else {
        $paged = 1;
  }
  $query->set( 'paged', $paged );
}
add_action( 'pre_get_posts', 'prefix_downloads_front_page' );

Just replace video with your custom post type slug at line 24. The archive is then going to be available as your homepage or from clicking your homepage website logo (if you have one).

TIP: To change the homepage archive layout to something else, let’s say a column layout style layout, you would use the below code inserted with the same method as previously:

add_filter( 'generate_blog_columns','gm_portfolio_columns' );
function gm_portfolio_columns( $columns ) {
    if ( is_category( 'videos' )  || is_archive('video') ) {
        return true;
    }
    return $columns;
}
add_filter( 'generate_blog_get_column_count','gm_search_column_count' );
function gm_search_column_count( $count ) {
    if ( is_category( 'videos' ) || is_archive('video') ) {
        return 20;
    }
    return $count;
}

In this case, I already had a column layout but with 4 columns. Inserting the code above would make my layout span 5 columns. I have In this case, I already had a column layout but with 4 columns. Inserting the code above would make my layout span 5 columns. I have assigned my video custom post type to a category of videos. The code above would look for a page where the category of videos is present, in this case if the video category was displayed is_category( 'videos' ). At the same time though, we are also looking for the custom post type archive which is loaded as our homepage is_archive('video'). Those two conditions would make sure that the correct layout would be loaded on both places. This solution works well for all kinds of paginated archives as well!

Have a look at this website here in which I have implemented the solution. I would also like to thank Tom Usborne from GeneratePress for corrections on the code!

I provide advanced customization work for GeneratePress, so please get in touch if you need any work done.

That’s all for now, hope you find that useful!

GeneratePress theme tutorial: Convert the top widget bar into a notification window

GeneratePress theme tutorial: Convert the top widget bar into a notification window

A notification bar is useful if you want to show a site-wide message to your audience about certain news or a promotion that you offer in your online shop. There is a plethora of notification bars that can be found in the WordPress plugin repository or you can embed one yourself. GeneratePress has a top bar widget that can be activated from the Customizer so why not take advantage of what’s already available to us and save a few resources and HTTP requests? By going to Appearance->Customize->Widgets->Top Bar a custom widgets can be added including custom menus, social icons, login information, etc. But what if you wanted to add a notification bar that always needs to load at the top of the page but give the user the option to be able to close it with the use of a close () button?

GeneratePress top bar widget area in the Customizer
GeneratePress top bar widget area in the Customizer

I recently asked that question in the GP Premium support forum and Tom Usborne (creator of GeneratePress) along with David gave me some great tips and code snippets (as always!) which I then applied to a test website with great results! The first thing to do is to actually add a custom HTML widget to the top bar widget area. Just go to Appearance->Customize->Widgets->Top Bar and then click the Add a Widget button to add a Custom HTML widget. I used the following HTML code to add a paragraph and a Font Awesome icon inside the content custom HTML widget area:

<p>USE CODE: TE20 AND GET 10% DISCOUNT</p>
<i class="top-close-button fas fa-times-circle"></i>

Tip: Since GeneratePress 2.1 the Font Awesome library is not included by default anymore. Please, read this article to add the Font Awesome library to the theme.

In Appearance->Customize->Layout->Top Bar, I set the “Top Bar Width” to Full and “Top Bar Alignment” to Center. In Appearance->Customize->Colors->Top Bar, I chose a dark background color with white text.

Top bar layout options
Top bar layout options
Top bar color options
Top bar color options

Next we need to add some CSS and JavaScript code. CSS code can be added from the Customizer (Appearance->Customize->Additional CSS). JavaScript code is to be added to the wp_footer hook area (Appearance->GP Hooks, then select the wp_footer hook and paste the code). Alternatively, if you are not a GP Premium owner you should be able to enqueue the script yourselves. Make sure not to include the <script></script>tags if you are to create your own JavaScript file, though.

CSS

/** Top bar **/
.top-bar {
    left: 0;
    right: 0;
    position: fixed;
    z-index: 1;
}
.top-bar p {s
  margin-bottom: 0;
}
.top-close-button {
  float: right; 
  clear:right; 
  margin-top: -20px;
  cursor: pointer;
}
body, div#wpadminbar, .top-bar {
    transition: transform 500ms ease;
}

JS

<script>
jQuery( document ).ready( function( $ ) {
    $( '.top-close-button' ).on( 'click', function( e ) {
        e.preventDefault();
$( '.top-bar' ).css( 'transform', 'translate(0%, -100%)' );
if ($('div#wpadminbar')[0]) {
    $( 'body' ).css( 'transform', 'translate(0, -52px)' );
    $( 'div#wpadminbar' ).css( 'transform', 'translate(0%, 20px)' );
} else {
  $( 'body' ).css( 'transform', 'translate(0, -52px)' );
}
    } );
} );
</script>

If you are on the latest versions of GP Premium and make use of the Elements instead, you can also create a hook element type by heading to Appearance->Elements->Add New and choosing Hook from the dropdown selection box. Name the element, paste the javascript code, select wp_footer as a hook type then click on the Display Rules tab and for Location choose Entire Site. Then, publish the element and you should be good to go!

Hook element
GeneratePress footer hook element

There might be times where jQuery isn’t properly enqueued so you would have to force jQuery to load by adding the following code snippet to your functions.php file or a functionality plugin like Code Snippets:

add_action( 'wp_enqueue_scripts', 'tu_load_jquery' );
function tu_load_jquery() {
    wp_enqueue_script( 'jquery' );
}

If you have any problems with the “close” button not working the previous code should be able to resolve it.

As you can see the styling repositions the bar at the center top, adjusts the spacing, relocates the close button at the top right of the bar and sets a few CSS transition effects that will be used when the bar is dismissed by the user. Also, the bar stays visible and fixed on top of the page while scrolling. The JavaScript code dynamically adds a few classes when the top bar close button is pressed and sets different Y-axis transformations to cater for the admin bar being present. Meaning that when the WordPress admin bar is present at the top of the user’s browser, the notification bar would need to be moved up and out of the browser screen and at the same time the whole page would need to move up without pushing the admin bar out of the way! You might also need to tinker with the values according to the height of your own bar.

Top bar without the admin bar
Top bar without the admin bar
Top bar with the admin bar visible
Top bar with the admin bar visible

Possible Improvements

You might notice that once the X mark is clicked to dismiss the top bar area, the footer at the bottom also moves up. To solve the issue, you can modify the CSS and Javascript accordingly:

CSS

/** Top bar **/
.top-bar {
    left: 0;
    right: 0;
    position: fixed;
    z-index: 1;
}
.top-bar p {
  margin-bottom: 0;
}
.top-close-button {
  float: right; 
  clear:right; 
  margin-top: -20px;
  cursor: pointer;
}
div#wpadminbar, .top-bar, .site-header, .main-navigation, .site {
    transition: transform 500ms ease;
}

JS

<script>
jQuery( document ).ready( function( $ ) {
    $( '.top-close-button' ).on( 'click', function( e ) {
        e.preventDefault();
$( '.top-bar' ).css( 'transform', 'translate(0%, -100%)' );
if ($('div#wpadminbar')[0]) {
    $( '.site-header, .main-navigation, .site' ).css( 'transform', 'translate(0, -52px)' );
    $( 'div#wpadminbar' ).css( 'transform', 'translate(0%, 20px)' );
} else {
  $( '.site-header, .main-navigation, .site' ).css( 'transform', 'translate(0, -52px)' );
}
    } );
} );
</script>

What we are doing here essentially is we target all the direct descendant elements of the body class except the .site-footer class. This trick will leave a margin above the footer though, so pick your poison and see what you like best or experiment with different selectors.

As a final note, the bar would appear on every page refresh but you could set up a JavaScript Cookie and set up a conditional to show/hide the bar depended on whether this Cookie was set or not. A great alternative method though, as Dave Smith suggested in the post comments, is to use the Widget Options plugin or similar to set the HTML widget to only show on certain pages. Finally, if you are a GP Premium member you can disable the top bar individually for a particular page or post by using the Disable Elements add-on module. The disable functionality can thus be activated and deactivated from the bottom of each page or post.

GeneratePress is a very powerful theme! Grab your copy here.

I provide advanced customization work for GeneratePress, so please get in touch if you need any work done.

Hope you found the tutorial useful. Till next time, keep Generating!

Do NOT follow this link or you will be banned from the site!