Code Snippet on Speckyboy Design Magazine https://speckyboy.com/topic/code-snippet/ Resources & Inspiration for Creatives Sun, 16 Feb 2025 21:10:10 +0000 en-US hourly 1 https://speckyboy.com/wp-content/uploads/2024/03/cropped-sdm-favicon-32x32.png Code Snippet on Speckyboy Design Magazine https://speckyboy.com/topic/code-snippet/ 32 32 How to Use ChatGPT to Export Data from a WordPress Database https://speckyboy.com/use-chatgpt-to-export-data-from-a-wordpress-database/ Sun, 24 Nov 2024 17:48:41 +0000 https://speckyboy.com/?p=168853 Learn how ChatGPT can help extract data from multiple WordPress plugins for quicker and easier data handling.

The post How to Use ChatGPT to Export Data from a WordPress Database appeared first on Speckyboy Design Magazine.

]]>
Retrieving data from a WordPress site can be a nightmare. Site data could reside in several places. Pulling from these various sources isn’t easy.

Websites that feature eCommerce or memberships are prime examples. Each plugin may store data in a different spot. Some create separate database tables. Others use the default WordPress locales.

Export plugins exist that help in some – but not all – circumstances. For example, you might be able to export customer orders. However, grabbing additional data not directly related to those orders may not be possible.

Writing a custom query is another option. But you’ll need to know your way around PHP and MySQL. Not everyone has the expertise to do so.

Artificial intelligence (AI) can help. As I discovered, tools like ChatGPT can do the dirty work. It simplified the process and saved me loads of time. Perhaps it saved my sanity as well.

Here’s how to use AI to get what you need from the WordPress database.

Before We Get Started

There are a few items we should mention before starting:

  • Back up Your Site’s Database or Create a Local Copy of Your Site
    None of what we’re doing here should hurt your database. However, create a fresh backup – just in case.
  • You can also create a local copy of your site for experimenting. That enables you to work without the risk of harming your production website.
  • Have Access to a ChatGPT Account
    We’re using ChatGPT for this demo. Therefore, you’ll want to have access to a free account. You can follow along and experiment.

Other AI tools, such as Google Gemini, may also work. The point is to use an AI tool that will generate code.

Also, a warning: Use caution when generating code. AI tools can make mistakes! Review the code before using it.

What Are You Doing with the Data?
There are a couple of things you can do with the data you retrieve:

  • Display the data on the front end of your site;
  • Download a CSV file that contains the data;

You’ll want to determine this beforehand. The process is a bit different depending on your choice.

Oh, and you’ll also need access to your site’s database. Access to your theme is required for displaying data on the front end.

You'll need access to ChatGPT or another AI tool.

Retrieving User Data from Different Plugins

Now, onto our experiment. Let’s take a common sticking point and try to make sense of it.

Our fictional website has two purposes. We sell various products with WooCommerce. Customers come to our site, create accounts, and order from us.

On the other side of the coin, we also sell memberships. Our members pay for access to exclusive content. We use the Restrict Content Pro plugin to power this feature.

Both WooCommerce and Restrict Content Pro have reporting features. For example, we can find out how many members we have. Or the number of WooCommerce customers.

But what if we want to combine this data? There’s no straightforward way to do this. So, let’s see if AI can help.

Step 1: Find the Data You Want

The first step is to determine what data you want to retrieve. Then, you’ll need to find the data inside the WordPress database.

Our goal is to create a CSV export file that includes users who are:

  • A customer in our WooCommerce shop AND…
  • Have an active membership via Restrict Content Pro;

Data isn’t always easy to locate. In some cases, you may need to reference plugin documentation. Or contact their technical support. A thorough database search can help if all else fails.

In our case, WooCommerce and Restrict Content Pro create custom database tables. That will make our job a bit easier.

  • WooCommerce table names use the ‘wp_wc‘ prefix.
  • Restrict Content Pro table names use the ‘wp_rcp‘ prefix.

We’ll also want to bring in data from the ‘wp_users‘ and ‘wp_usermeta‘ tables. That allows us to tie customer and membership data to specific users.

With that in mind, we’ll look for the following information:

Data Type Database Table Column
User ID wp_users ID
First Name wp_usermeta Meta Key: first_name
Last Name wp_usermeta Meta Key: last_name
Customer ID wp_wc_customer_lookup customer_id
Membership Status wp_rcp_memberships status
Membership Level ID wp_rcp_memberships object_id

Step 2: Ask ChatGPT to Create a Database Query

Next, we’ll ask ChatGPT for some help. We’ll want to provide a clear explanation of the task.

Here’s the prompt I used:

I'd like to create a MySQL database query for a WordPress website. I only want to retrieve users who have both a WooCommerce Customer ID and a membership via Restrict Content Pro.

Here is the data I'd like to retrieve:

From the wp_users database table:
ID

From the wp_usermeta database table:
Meta Key: first_name
Meta Key: last_name

From the wp_wc_customer_lookup database table:
customer_id

From the wp_rcp_memberships database table:
status
object_id

Step 3: Get the Response

ChatGPT’s response included a code snippet and a detailed explanation of it (view the full response). The snippet joins multiple database tables together to produce a single report.

So, how do we see if it works? We can run the query in a tool that connects to the site’s database. I’m using a local website that includes AdminerEvo.

You could also use phpMyAdmin, MySQL Workbench, or similar apps. ChatGPT can even provide instructions for whatever app you’re using.

I’ve pasted the query into the SQL Command screen inside AdminerEvo.

Step 4: Study the Results

The results are in! Our fictional website has 198 users. 15 of them have a paid membership. There are also 200 product orders.

So, how many are WooCommerce customers and Restrict Content Pro members? A grand total of seven.

The query results returned the columns we requested. From here, we can tweak things further or export the data.

The results of the database query.

Going Further with AI

Our example query may seem simple. However, bringing together data from multiple plugins is challenging. A custom solution is often the only solution.

I’m no coding expert. Thus, figuring out how to get data became frustrating. Thankfully, AI has proven to be a terrific tool for the job.

It’s one of the areas where this technology shines. Many of us struggle to write this sort of code on our own. Writing a prompt describing what we want isn’t so bad, however.

There are also opportunities to take things further. We could change our prompt to display data on a WordPress page. Or return data relevant to the currently logged-in user.

A working knowledge of PHP and MySQL can take you a long way. So, experiment and see what you can accomplish. And be sure to add up all the time you save in the process!

The post How to Use ChatGPT to Export Data from a WordPress Database appeared first on Speckyboy Design Magazine.

]]>
How to Avoid Common WordPress Theme Development Mistakes https://speckyboy.com/avoid-common-wordpress-theme-development-mistakes/ https://speckyboy.com/avoid-common-wordpress-theme-development-mistakes/#respond Sat, 16 Nov 2024 00:12:03 +0000 https://speckyboy.com/?p=100338 We take a look at five of the most common mistakes found in WordPress theme development and offer alternatives solutions.

The post How to Avoid Common WordPress Theme Development Mistakes appeared first on Speckyboy Design Magazine.

]]>
WordPress is known for being incredibly flexible, especially when it comes to theme and plugin development. If you ever want to see proof, just ask a group of developers how they’d implement a specific feature. The chances are that you’ll receive several different methods for accomplishing the same result. Support forums are littered with these kinds of examples.

But with that flexibility also is the reality that it’s easy to do things the “wrong” way. Now, in this case, “wrong” means that something is either inefficient or a bit of a pain to maintain down the road. While it may work in the sense of being functional, there are usually better ways to get things done.

Let’s have a look at five of the more common mistakes found in theme development, along with alternatives that will save you future headaches.

1. Using Absolute URLs in Templates

If you’ve ever looked at the HTML code a WordPress page or post produces, you’ll notice that both images and internal links use absolute (full) URLs. But this isn’t the best way to get things done when adding code to your theme templates.

As an example, let’s say you are developing a website that is using a temporary URL. A hardcoded absolute URL in a template means that you’ll have to manually make code changes when you are ready to launch the site on its permanent domain. While this can be done, it’s too easy to forget all of the spots where this type of code could be lurking.

WordPress has built-in ways to determine the correct URL – pulled right from the Settings > General area of the Dashboard.

For a link, echoing esc_url( home_url() ) will provide a full path to the home page. So, instead of explicitly placing the URL in your code, you could add a simple link back to your home page like so:

<a href="<?php echo esc_url( home_url() ); ?>" />Home</a>

What’s more, you can also use this to point to secondary pages. For example, if we wanted to link to our site’s About Us page, we could use the following code:

<a href="<?php echo esc_url( home_url() ); ?>/about-us/" />About Us</a>

A similar snippet also works for images. This example pulls an image from our active theme’s /images/ subfolder:

<img src="<?php echo esc_url( get_stylesheet_directory_uri() ) ; ?>/images/hello.png" />

2. Adding Scripts and Styles Directly to a Template

Using third-party scripts and styles with WordPress is a world of its own. When you first start out in building themes, you may be tempted to simply place <script> or <style> tags, or even a Google Font embed code directly into your theme’s header. This is generally how things are done with static HTML sites, so it makes sense to do the same here.

But, like just about everything else in WordPress, there is a better way to go about it. Instead, take advantage of wp_enqueue_script() and wp_enqueue_style() – which add scripts and stylesheets to the correct spots for you. It also makes managing assets that much easier, as everything is called from your theme’s functions.php file.

Rather than reinvent the wheel here, the WordPress Theme Handbook has a fantastic guide on how properly add scripts and styles to your theme.

Make smart development decisions

3. Calling Outside Instances of jQuery

In a related note, one of the hidden secrets of WordPress is that it already includes a copy of jQuery, along with several popular UI features. So, you don’t need to install jQuery or call it remotely. This makes it easy to take advantage of the popular JavaScript library and implement elements such as tabs, datepickers, dialogs and a whole lot more.

The only catch is that you have to specifically enable the items you want to use through your theme’s functions.php file. While that creates a bit of a learning curve, it also cuts down on bloat.

And, truth be told, it’s not overly difficult to implement a desired jQuery UI element. For example, to enable the use of jQuery UI Tabs, just add the following snippet to your functions.php:

function my_jquery_elements() {
   wp_enqueue_script( 'jquery-ui-tabs', array('jquery'));
add_action( 'template_redirect', my_jquery_elements ', 10 );

This tells WordPress to load in the element from its already-existing library. From there, design your tabs and define them as specified in the jQuery UI documentation.

4. Taking Customization Too Far

The ability to add custom fields and custom post types can make life for both developers and site content editors much easier. They offer convenience, better content organization and a more intuitive UX. But sometimes we take it too far.

I’m a huge fan of custom fields, for example. But even I admit that there have been times when I’ve customized a theme to the point of inflexibility. Fields are great for setups where we know exactly what content will need to be input – like the fields of a staff member profile.

However, it can get messy when there are inconsistencies in the types of content someone wants to add. Clients are notorious for having “minor” exceptions in content that can make using customizations more difficult. Conditional logic can account for some of this, but you can only take it so far before the UI gets out of hand.

There are no hard and fast rules for this type of customization. The only thing we can really do is use our best judgment about what should be customized and what can be better left to either the WordPress content editor or even a niche plugin. When we do add fields or post types, just know that things could change down the road and try to build with that in mind.

5. Failing to Comment Code

I’m going to make another admission here: Commenting code is not one of my strong points. It’s not that I don’t use comments at all, but it’s more that they aren’t very articulate. Usually, I’ll point out the start and end of particular items with not a ton of insight in-between. Should I be doing more? Probably so.

Commenting is important because it at least provides some reference points within the code. When digging through PHP or JS files that contain more than one thing, you’ll want to know where to find a particular item.

Even if you’re the only one who will ever edit that code, comments are highly recommended. If, for instance, you need to change something six months from now, it’s unlikely that you’re going to remember the exact spot you placed a snippet of code.

So, I’m not going to be a huge hypocrite and implore you to comment everything with great depth. But I will say that even a minimal effort here makes future maintenance easier for you or another developer that has to comb through your work.

Minimally commented code

Better Techniques Over Time

Building your own WordPress theme can be a great experience. But it does take a good bit of practice to pick up on the finer details of creating a well-coded theme and easy to maintain. The more experience you gain, the more your techniques will evolve.

I can honestly say that the first few themes I put together were nowhere near as efficient as they are now. And I’m also certain that they still might not be up-to-snuff when viewed by a truly expert developer. In that sense, our evolution is a constant one.

Finally, I’d like to note that I have personally made every one of the mistakes mentioned above. It’s only through trial and error, along with several visits to the Codex, that I found out how to start doing things the “WordPress Way.”

The lesson is that we’re all going to make mistakes. But each one provides us with a chance to learn and improve.

The post How to Avoid Common WordPress Theme Development Mistakes appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/avoid-common-wordpress-theme-development-mistakes/feed/ 0
Simple Ways to Customize & Add Functionality to WordPress Plugins https://speckyboy.com/customize-wordpress-plugins/ https://speckyboy.com/customize-wordpress-plugins/#respond Wed, 06 Nov 2024 20:12:47 +0000 https://speckyboy.com/?p=108062 Extending a WordPress plugin doesn’t require expert knowledge. Mostly all you need is an understanding of PHP & HTML is all you need.

The post Simple Ways to Customize & Add Functionality to WordPress Plugins appeared first on Speckyboy Design Magazine.

]]>
There are times when a WordPress plugin’s functionality gets you close to what you need – but not quite the whole way. In addition, there are also situations where you’ve committed to using a particular plugin and would like to build additional features around it.

These are prime examples of why you’d want to customize or extend an existing WordPress plugin. It’s one of the really cool aspects of how the CMS allows us to build highly custom websites. We can take a plugin we’re already using on our site and integrate extra functionality or usability items that help us to do more.

And, while it may sound like something reserved for seasoned developers, extending a plugin doesn’t require a PhD. Depending on what you’re looking to achieve, a basic understanding of PHP, HTML, and CSS may be all you need to add some powerful features.

Today, we’ll review the process of choosing a plugin worth extending and some basics regarding what you can achieve.

Finding the Right Plugin

The first part of this process is also the most important: choosing a plugin. Sure, you can pick any one of the tens of thousands of available choices out there. And you may already have one in mind. But if you’re going to go to the trouble of adding extra capabilities, your ultimate pick is worth some serious consideration.

In many cases, a plugin you would consider customizing is playing a key role in what your website does. For example, an eCommerce plugin such as WooCommerce is going to be a major part of an online store. Just as an organization that holds a lot of events might heavily rely on a calendar plugin.

Regardless of what the plugin does, it’s vital to choose one that you can commit to for the long term. Therefore, you’ll want to look for software that:

  • Is being actively maintained by its author;
  • Has an adequate userbase, relevant to its niche;
  • Has a track record of fixing bugs and responding to support requests;
  • Offers, at the very least, a majority of the features and functions you need;

While these aren’t the only characteristics of a good plugin, they make for a solid place to start. Another great feature, for instance, would be a library of plugin-specific hooks that allow you to more easily tap into its various functions. It’s not required, but certainly a great help in the customization process.

Once you’ve taken the plunge, it’s time to start thinking about what type of extras you want to add!

Exploring Potential Add-Ons

The types of features you can build to customize a plugin are limited only by your skill and imagination. Just think of some of the amazing add-ons that developers have built for plugins such as Gravity Forms or Advanced Custom Fields. They prove that you can take an already great piece of software and make it even more useful.

However, our focus here is more on site-specific functionality rather than pie-in-the-sky endeavors. These items are narrower in scope and help facilitate what you want to do with your website. You might also want them to make a certain aspect of your site easier for you or a client to maintain.

Here are a few basic ideas that can help you brainstorm:

Adding More Types of Data

A default installation of your favorite plugin might not include all of the relevant data that your website has to offer. But through using WordPress custom fields (which can be created with plugins like the aforementioned Advanced Custom Fields), enables you to add just about any type of data you like.

Take, for example, a calendar plugin. Let’s say that your website uses one to post meeting information. Out of the box, that plugin may not allow you to easily add links to an agenda or other documents you’d like to share with users.

While you could manually add links to these items within the content of each event, that may not necessarily be the easiest thing in terms of maintenance. Instead, you could create a simpler process that is more user-friendly.

In this case, integrating a few custom fields into event posts can make a huge impact with regard to ease of use. It also adds a layer of consistency to both the front and back ends of your website. The back end is now easier to maintain, and the fields can be styled in your theme to help users find this important information.

Custom fields added to an event calendar plugin.

Changing Plugin Output

Going beyond adding different types of data to go along with a plugin, you might also find a need to change its default output. There are a couple of situations where this could be of use:

It’s Not Relevant to Your Site

Sometimes, the language or terminology a plugin uses may not fit the subject matter of your website. For instance, if your site uses WooCommerce to take online donations – but doesn’t sell products – the cart’s terminology could seem confusing to users.

By default, WooCommerce calls everything you sell a “Product.” This is fine for a typical online store, but here it seems out of place. Thankfully, there are ways to change it.

Through the use of the gettext WordPress filter, it’s possible to change all instances of the word “Product” to “Donation”, along with any similar terms you deem appropriate.

A donation product in WooCommerce

Changing or Adding Data in Special Situations

There are often little bits of information that could really enhance the user experience of your site. Yet, they may only be relevant at specific times.

Sticking with WooCommerce, let’s say that you need to display important information to all products within a specific category. The goal, once again, is to streamline things so that you don’t have to manually add this message to each product.

A fairly simple conditional statement in your theme or a custom plugin can do the job. By combining the is_product() WooCommerce function and the has_term() WordPress function, you can target just the products in a specific category and add in the important information.

// Add important information to products within the "Jackets" category.
add_action( 'woocommerce_single_product_summary', 'jacket_information', 10);
// Check to see if it's a WooCommerce product and in the "Jackets" category.
 if ( is_product() && has_term( 'Jackets', 'product_cat' ) ) {
 
 // Now, provide the important information.
 function jacket_information() {
 echo 'Wear a jacket - it is very cold outside!';
 }
 }

Combining Features with Other Plugins

On occasion, you might want to combine all or parts of what one plugin does into another. This one may sound like it’s well beyond the scope of the word “simple” – which is a fair point. But, depending on what you want to do, it may be easier than you imagine. Here are just a few ideas:

  • Use a slider plugin to dynamically display the best-selling products from your WooCommerce store.
  • Provide access to purchase a product after a user completes a specific lesson on an online course.
  • Include a survey form on a user’s account page – but only after they have been a part of your membership site for a month.

These types of combinations are often possible through plugin-specific hooks or ones that have been built into WordPress itself. The possibilities here are endless. All it takes is a little imagination and a willingness to experiment with code. Reading through documentation can provide you with some clues on how to put it all together.

A More Customized WordPress Website

Building a great website isn’t just a matter of implementing large, sweeping functionality. It’s often the smaller details that help to separate a great site from an average one.

WordPress plugins tend to help us with the big stuff. They provide the framework for us to get up and running. But with a little elbow grease, we have the ability to further customize things to match the needs and goals of our projects.

The post Simple Ways to Customize & Add Functionality to WordPress Plugins appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/customize-wordpress-plugins/feed/ 0
30+ Free Icon Fonts for UI Design https://speckyboy.com/free-icon-fonts/ https://speckyboy.com/free-icon-fonts/#respond Mon, 04 Nov 2024 12:10:43 +0000 http://speckyboy.com/?p=48816 We have a collection of the best @font-face icon fonts that you can freely download and use in your next mobile app or web design projects.

The post 30+ Free Icon Fonts for UI Design appeared first on Speckyboy Design Magazine.

]]>
Instead of letters and numbers, an icon font contains glyphs, symbols, or pictograms. They are the simplest way for a UI designer to add icons to a UI design project.

One of the great things about using an icon font is its scalability. They can be resized without losing quality, making them perfect for responsive web design. With CSS media queries, they can be scaled up for desktop or down for mobile. Icon fonts are also fully customizable, allowing you to adjust the size and edit colors to fit the aesthetic of a UI design.

Adding icon fonts to any web design or mobile app project is easy using CSS. You load the font file using @font-face, and using standard CSS rules, you can set the font-size, color, padding, margin, or other properties.

Although very popular, icon fonts do also have their pitfalls. Ian Feather has discussed his reasons for switching from an icon font to SVG, and CSS Tricks have outlined some considerations when choosing between icon fonts or SVG icons. Both favor SVG.

As a counter-argument, Pictonic has said that icon fonts are 10% faster than SVG. These are just things you should consider before using icon fonts.

To ensure that your icons always load correctly and have reliable fallbacks for browsers that don’t support @fontface, you should take a look at the guidelines set out by the Filament Group, here.

The Pros & Cons of Icon Fonts

Icon fonts provide consistency, accessibility, and customization options while maintaining cross-browser compatibility. However, it’s essential to consider their pros and cons and choose the best icon format based on your specific design needs.

Here’s what you need to know about using icon fonts for UI design:

  1. Scalability: Icon fonts are vector-based, meaning they can be scaled up or down with no quality loss.
  2. Lightweight: Icon fonts are typically smaller in file size compared to image-based icons, reducing page load times and improving website performance.
  3. Ease of Use: Incorporating icon fonts into your UI design is straightforward. You can include them in your HTML and CSS, then style and size them.
  4. Consistency: Icon fonts provide a consistent look and feel across various devices and browsers.
  5. Customization: You can easily customize icon fonts by adjusting their size, color, and other CSS properties. This flexibility allows you to match icons to your project’s design.
  6. Accessibility: Icon fonts can be made accessible by adding appropriate aria-labels and roles, ensuring that screen readers can interpret their meanings to users with disabilities.
  7. Responsive Icons: Some icon fonts offer responsive features, allowing icons to adapt automatically to different contexts and orientations.
  8. Cross-Browser Compatibility: Icon fonts are widely supported by modern web browsers, making them a reliable choice for web design.

However, there are some limitations to consider:

  1. Limited Complexity: Icon fonts may not be suitable for complex or intricate icons that need multiple colors or fine details. In such cases, SVG icons might be a better choice.
  2. Icon Diversity: While icon fonts offer a wide variety of symbols, they might not cover every unique design requirement. You may need to create custom icons or combine them with other icon formats.
  3. Unicode Conflicts: Icon fonts use Unicode characters, which could conflict with actual text content if not managed correctly.

The Top Free Icon Fonts for UI Designers

Eva Icons Open Source UI Icon Set

480 Icons

These open-source icons include actions and items, from arrows and attachments to color palettes. With over 480 icons, it’s the whole package!

Eva Icons Open Source UI Icon Set @fontface webfont free

Ionicons Icon Pack for Ionic Framework

1,100+ Icons

Ionicons is a well-rounded icon pack for the Ionic framework. It includes numerous app icons (notifications, arrows, food, and more) and icons featuring renowned brands’ logos (e.g., Pinterest, Facebook, and others). You can download the outline, filled, or sharp icon renders as SVG or web font files.

Ionicons Icon Pack for Ionic Framework @fontface webfont free

Font Awesome

2,000+ Icons

Font Awesome is a hugely popular icon set with over 1,600 free icons. The FA gallery includes everything from brand logos to business and lifestyle icons.

Font Awesome Icon Set @fontface webfont free

Cryptofonts

1,250+ Free Icons, Icon Font

Free Icon Set UI Web Design Cryptofonts

Line Awesome Icon Font

1,380 Icons

Add modern line icons to your projects with Line Awesome in just one line of code. It builds on Font Awesome, offering 1,000s of icons, from accessibility and buildings to arrows and brands. You can easily add them to your website (via CDN).

Line Awesome Icon Font @fontface webfont free

Dashicons, the WordPress Admin Icon Font

300+ Icons

Dashicons is an icon font for WordPress. It’s technical in style but gets the point across and is easy to use. From brand logos to TinyMCE, run wild!

Dashicons WordPress Admin Icon Font @fontface webfont free

Remix Icon Open Source Library

2,000+ Icons

Remix Icon is an open-source icon library with over 2,200 icons. All of the icons are free for personal and commercial use. You’ll get a wide variety of icons, from thin outline icons to filled symbols for extra emphasis. Download them as PNG, SVG, or code.

Remix Icon Open Source Library @fontface webfont free

Themify Icon Font

320+ Icons

Inspired by Apple iOS, Themify icons offer over 300 beautiful minimalist icons. From arrows to app icons, you’ll get everything you need, such as an icon font for easier workflow integration (SVG included) or a plugin for WordPress. Themify icons are perfect for modern UI design!

Themify Icon Font @fontface webfont free

Dripicons Line-Icon Font v.2

200 Icons

If you don’t want garden-variety line icons, check out Dripicons. This free icon font is incredibly easy to use, but the best part is that they’re beautiful! You’ll get a set of versatile bold line icons, from arrows and tech to education and music.

Dripicons Line Icon Font v.2 @fontface webfont free

GitHub’s Octicons Icons

180 Icons

If you like GitHub’s aesthetic, you’ll love Octicons. These icons are available in two sizes (16px and 24px) and include some special-case icons, like pull requests. You can toggle between outline and filled icons, and they work well with different programming languages.

GitHub Octicons Icons @fontface webfont free

Foundation Icon Fonts

280 Icons

Get going with just a few lines of code and Foundation icons. This collection includes different sets, from general to accessibility icons, so there’s something for every project. Foundation icons work as a web font, so you don’t have to jump through hoops.

Foundation Icon Fonts @fontface webfont free

The Elegant Icon Font

360 Icons

Beautiful, elegant, and engaging – this icon font has over 300 icons. They’re simple to use, especially if you’ve used Elegant Themes or the Divi builder in the past. You will find everything you need, from file icons to arrows, in this set.

The Elegant Icon Font @fontface webfont free

Feather Open Source Icon Set

282 Icons

Keep it simple with Feather, a collection of minimalist open-source icons. From arrows and chevrons to app UI icons, Feather is an excellent addition to your standard design toolbox. You can customize every icon’s size, stroke width, and color.

Feather Open Source Icon Set @fontface webfont free

Typicons Icon Font

500+ Icons

Simple, friendly, and perfect for a wide range of projects, Typicons are a great choice. They are embedded in a web font, so they’re easy to use. You’ll get 336 icons, from cogs and arrows to brand logos. You can pick between filled icons or outlines.

Typicons Icon Font @fontface webfont free

Genericons Neue Icon Font

100 Icons

Simplify your design with Genericons, a set of simple and minimalist web and app design icons. They work well for blogs or simple websites where you want to keep the focus on your messaging. You’ll get plenty of icons for key features, from sitemaps to RSS feeds.

Genericons Neue Icon Font @fontface webfont free

Microns Icon Font

164 Icons

Microns take pride in their simplicity. The collection includes icons for the most common use cases, from charts and arrows to navigation. They’re easy to encode, and the file is only 5kb, so they’re perfect for use across your project portfolio.

Microns Icon Font @fontface webfont free

Stroke 7 Icon Font

200+ Icons

Straight out of the Pixeden workshop, Stroke 7 is a collection of thin-line icons. The set offers 200+ icons that can be customized with CSS. The icons are minimalist, so they won’t distract from your main message.

Stroke 7 Icon Font @fontface webfont free

Stroke Icon Font Vol.1

80 Icons

Petras Nargela designed this set of 80 free icons. These beautiful, fresh, clean icons can be downloaded as PSD, AI, or web font files. If you need something different, you’ve found it!

Stroke Icon Font Vol.1 @fontface webfont free

Material Design Iconic Font

Created by Google, the Material Design icon set contains plenty of icons you can use across your projects. You just have to add one line of code to your website, and you’re good to go! Since community members constantly add icons, there’s plenty of variety.

Material Design Iconic Font @fontface webfont free

CSSans Pro CSS Font

CSSans is a colorful and dynamic CSS font. It’s composed of multiple colorful geometric elements that add vibrancy to your designs. CSSans is all about personality! It’s infinitely customizable.

CSSans Pro CSS Font @fontface webfont free

MFG Labs Icon Set

120 Icons

The MFG Labs icon set was originally designed for an internal project, but the team couldn’t resist sharing this icon set. They’re easily embeddable and customizable with CSS. You’ll find all the icons necessary to create the right atmosphere for your next design.

MFG Labs Icon Set @fontface webfont free

Ligature Symbols Icon Font

240 Icons

Ligature Symbols is an icon font with fun and minimalist icons. Individual icons can be combined to create ligatures (e.g., combine table and cell icons to create grids), improving this collection’s usability. You’ll find everything you need here.

Ligature Symbols Icon Font @fontface webfont free

Devicon 2.0 Programming & Development Icon Font

180+ Icons

Devicons are friendly, developer-friendly icons created to represent programming and tools. From Chrome and Confluence to Django and Illustrator, you’ll find the icon you’ve been looking for. You can easily copy-paste them into your projects using either the font or SVG versions.

Devicon 2.0 Programming Development Icon Font @fontface webfont free

Mini Icon Font Set

80 Icons

Simple and clean, these mini icons are perfect for a wide variety of projects, particularly those more formal in tone. The icon collection contains 80 icons in Photoshop PSD and font formats. From download/upload symbols to location and weather icons, this set offers every icon you need!

Mini Icon Set @fontface webfont free

Helium Icon Set & Font

100 Icons

Taras Shypka’s Helium icon set offers plenty of icons. Not only do they come in every format imaginable, but you can also use them as an icon font. You’ll get 112 icons with fine-shaded lines.

Helium Icon Set Font @fontface webfont free

Gonzocons 2.0 Line Icons

100 Icons

Gonzocons, designed by Jan Rajtoral, includes 100 line-style icons that perfectly replicate modern icon design trends. From simplistic arrows to buoyant hearts and hourglasses, Gonzocons icons definitely have a personality. You can get them as SVG files or as a web font for easier integration with your app or site.

Gonzocons 2.0 Line Icons @fontface webfont free

Map Icon Marker Font

180 Icons

Map Icons is an icon font made for Google Maps and Places. You can customize them with CSS, and pick from over 180 icons. From general icons for hair salons to icons for activities, this set gives you plenty to choose from to make your next project amazing.

Map Icon Marker Font @fontface webfont free

Top Free Weather Icon Fonts

Weather Themed Icon Font

222 Icons

If accurate forecasts are important to your next project, you’ll love this set of weather-themed icons. With over 200 icons (including specialty icons like 28 lunar phases), you’ll be ready to create something amazing! You can easily customize them with CSS to fit your needs.

Weather Themed Icon Font @fontface webfont free

Meteocons Weather Icon Font

40 Icons

Get 40+ minimalist and friendly weather icons with Meteocons. This set offers every format imaginable, from SVG to desktop and web fonts. They’re free to use personally and commercially, and you can even create a custom font with the icons you frequently use.

Meteocons Weather Icon Font @fontface webfont free

Top Free Social Media Icon Fonts

Socialicious Social Media Icon Library

74 Icons

If you’re looking for incredible social icons, check out Socialicious. It gives you social media icons in font form, so they’re incredibly easy to use and even easier to customize. Integrate them with a single line of code and customize them with CSS.

Socialicious Social Media Icon Library @fontface webfont free

Mono Social Icons Font

100 Icons

Engaging and dynamic, Mono Social are social media icons with a fun personality. You can use them for free and pick one of the three options (rounded, circle, regular) to fit your style. Use them with CSS, HTML, and SCSS. They’re free for personal and commercial use.

Mono Social Icons Font @fontface webfont free

How to Use Icon Fonts

Adding icon fonts to a project typically involves a few simple steps. Here’s a general guide on how you can add icon fonts to your own web or UI project:

  1. Choose an Icon Font Library: Select an icon font library from above that suits your project’s needs.
  2. Download or Link to the Icon Font: You can download the icon font files and host them on your server or link to them via a CDN. Many icon font libraries offer both options.
  3. Include the CSS Stylesheet: Link to the icon font’s CSS stylesheet in your HTML document’s head section. This stylesheet contains the necessary CSS rules to display the icons correctly.
    <link rel="stylesheet" href="path/to/icon-font.css">
  4. Add Icon Elements to Your HTML: In your HTML markup, create elements (e.g., i, span, or div) with appropriate class names to represent the icons you want to use. Assign the class names provided by the icon font library.
    <i class="fas fa-heart"></i> <!-- Font Awesome Heart Icon 
    <i class="material-icons">star</i> <!-- Material Icons Star Icon 
  5. Style & Customize Icons: You can customize the icons by applying CSS styles to the elements. Adjust size, color, and other properties.
  6. Accessibility Considerations: Make sure your icons are accessible by providing alternative text or labels when necessary. This is important for users who rely on screen readers.
    <i class="fas fa-envelope" aria-label="Email"></i>
  7. Testing & Optimization: Test your icon fonts across different browsers and devices to ensure consistent rendering. Optimize your project for performance by minimizing the number of icon requests and reducing file sizes.
  8. Documentation & Maintenance: Document the icon classes you're using and keep track of any customizations for future reference and maintenance.

Refer to the documentation of each icon font for more detailed instructions.

Icon Font FAQs

  • What are Icon Fonts?
    Icon fonts consist of symbols and glyphs, offering a visual alternative to standard letters and numbers. In UI design, they're used to add scalable, styleable icons.
  • Why Use Icon Fonts in UI Design?
    Icon fonts are popular in UI design because they're lightweight, scalable, and easy to style with CSS. They ensure icons look sharp on all screen sizes.
  • Can I Customize These Icon Fonts?
    While you can't directly edit the icons in the font, you can use CSS to customize their appearance, like changing colors and size or adding effects like shadows.
  • Are Icon Fonts Compatible with All Browsers?
    Most modern browsers support icon fonts. However, testing your design in different browsers is always good to ensure compatibility and consistent appearance.
  • Can I Use Icon Fonts for Both Web and Mobile UI Design?
    Icon fonts are suitable for both web and mobile UIs. Their scalability and customization options make them a versatile choice for any platform.
  • How Do Icon Fonts Differ from SVG Icons?
    Icon fonts are a collection of icons as font characters, which makes them easy to scale and style with CSS. SVG icons are individual vector images with more complex designs and colors. Both are scalable, but SVGs offer more design details.
  • How Do I Ensure Accessibility with Icon Fonts?
    For accessibility, always provide proper text alternatives (like "alt" text) for screen readers.
  • Will Icon Fonts Slow Down My Website?
    Generally, icon fonts are lightweight and shouldn't significantly impact your website's loading speed. They are often more efficient than using many individual image files.

More Free Icon Sets

The post 30+ Free Icon Fonts for UI Design appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/free-icon-fonts/feed/ 0
How to Speed up Google Fonts in WordPress https://speckyboy.com/speed-google-fonts-wordpress/ https://speckyboy.com/speed-google-fonts-wordpress/#comments Sat, 02 Nov 2024 11:49:04 +0000 https://speckyboy.com/?p=86422 In this quick tutorial, we show you a couple of methods for optimizing and drastically speeding up Google Fonts in WordPress.

The post How to Speed up Google Fonts in WordPress appeared first on Speckyboy Design Magazine.

]]>
Today, I’m going to cover a few methods for optimizing and speeding up Google Fonts in WordPress. Images, of course, are and always will be the heaviest part of a web page, but according to HTTP Archive, as of October 2016, web fonts are just over 3% of an average page’s overall weight.

Even though the weight of web fonts makes up only a small portion of the overall web page, every optimization you make helps contribute to faster load times. Check out some ways below to speed up those fonts!

What are Google Fonts?

First off, for those of you who might not know, Google Fonts is an open-source (free) directory of over 800 web font families which you can use on your website. They are also available to download locally for print and other uses. Millions of WordPress websites utilize Google Fonts as it is a great free way to enhance the look and usability of your site.

If you are going for pure performance, system fonts will always win, but there is nothing like the professionalism and aesthetic of a good web font. And in fact, typography has been shown to affect conversions in a positive way. But everything has its cost. And so, it is important to understand how adding Google Fonts to your WordPress site affects speed and performance.

How to Use Google Fonts in WordPress

There are a couple of ways to add Google Fonts to your WordPress site. The first and default way is to grab them directly from Google. This method uses their global CDN to deliver the fonts quickly from different servers from around the globe.

When you add them to your site there will be an external request to fonts.googleapis.com.

googleapis

The are also external requests to fonts.gstatic.com for the WOFF or WOFF2 versions depending upon browser support.

gstatic

WordPress Plugin

If you are a WordPress beginner, the easiest way to add Google Fonts to your website is probably with a free plugin. The Easy Google Fonts plugin is a good popular example. As of writing, it currently has over 300,000 active installs with a 4.9 out of 5-star rating.

easy google fonts wordpress

Add Embed Code From Google Fonts

It is important to note that most WordPress plugins add slight overhead, and so I prefer to add Google Fonts with their much simpler to use embed code. So, head over to Google Fonts and choose the font you want. For this example, I’m using Roboto.

Click on the “Customize” option. This is an important step as each font family has different font weights. Typically you will want regular, medium, and bold.

Note: Every font-weight you include adds to the overall load time of your fonts, so don’t just select all of them. The less, the better.

4 roboto google fonts

Then click on the “Embed” option. This is where you will want to copy the embed code it provides.

google fonts embed

Take that code and put it into the <head> section of your WordPress site. There are different ways you can do this, some might prefer to enqueue the fonts, but for this example I simply added the code to the header.php file. Note: This might vary slightly depending on the theme you are using.

header font embed

Then, to actually make your WordPress theme use the Google Fonts, you have to add some CSS styles. Below is an example of what I’m using. If your theme admin panel doesn’t have a custom CSS editor you can always use a free plugin like Custom CSS and JS.

body {font-family:roboto; font-size:18px;}
h1,h2,h3,h4,h5,h6 {font-family:roboto; font-weight:700; text-transform:none !important;}
h1 {font-size:28px;}
h2 {font-size:26px;}
h3 {font-size:24px;}
h4 {font-size:20px;}
h5 {font-size:18px;}
h6 {font-size:16px;}

Now that you know some quick methods for adding Google Fonts to your WordPress site, I’m now going to do a few quick tests to see alternative ways of speeding them up. I ran some tests first with the setup above and the average speed came out at 418ms. Note: Each test was run five times, and the average result was taken.

google fonts cdn speed test

Host Google Fonts Locally

Another way to deliver Google Fonts on your WordPress site is to host them locally on your web server. If your audience is in a certain geographical location and close to your server, it can actually be faster to host them locally than it is to use Google Fonts. Google Fonts CDN is great, but adding those additional external requests and DNS lookups can cause delays.

This method will typically only work if you are using fast hosting. In the example, I’m using managed WordPress hosting from Kinsta, which is ironically powered by the Google Cloud Platform.

To host locally I actually utilized a free tool called the google-webfonts-helper. This allows you to download the Google fonts locally more easily and gives you all of the CSS. Below is an example of what we will end up with. You will need to upload the fonts you downloaded to your web server. In this case, I put them in a folder called “fonts.”

/* roboto-regular - latin */

@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 400;
  src: local('Roboto'), local('Roboto-Regular'),
       url('https:/perfmatters.io/fonts/roboto-v15-latin-regular.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */
       url('https://perfmatters.io/fonts/roboto-v15-latin-regular.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
}

/* roboto-500 - latin */
@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 500;
  src: local('Roboto Medium'), local('Roboto-Medium'),
       url('https://perfmatters.io/fonts/roboto-v15-latin-500.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */
       url('https://perfmatters.io/fonts/roboto-v15-latin-500.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
}

/* roboto-700 - latin */
@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 700;
  src: local('Roboto Bold'), local('Roboto-Bold'),
       url('https:/perfmatters.io/fonts/roboto-v15-latin-700.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */
       url('https://perfmatters.io/fonts/roboto-v15-latin-700.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
}

We then need to make sure to remove the embed code from Google Fonts in the header so that you no longer have those external calls. I then again ran some tests with the setup above and the average speed came out to 386ms.

local google fonts speed test

Note: The web server is located in Iowa, and the speed test from Pingdom was run from Dallas, TX. So as you can see, even though the server is located elsewhere in the United States, it is still slightly faster to load Google Fonts locally on the server. Of course, you will want to test various locations yourself based on your own audience.

Host Google Fonts on Your Own CDN

Now for a third scenario. On the site above, I’m using a third-party CDN provider already (KeyCDN) to host all of the other assets(images, CSS, Javascript, etc.). What happens if we now throw our fonts on the same CDN, instead of Google’s CDN?

I’m using the free CDN Enabler WordPress plugin. This actually copies the fonts from the “fonts” folder on the web server to KeyCDN automatically. We then have to tweak the code slightly so that the path to the fonts is now pointing to the CDN (such as cdn.domain.com).

/* roboto-regular - latin */

@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 400;
  src: local('Roboto'), local('Roboto-Regular'),
       url('https://cdn.perfmatters.io/fonts/roboto-v15-latin-regular.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */
       url('https://cdn.perfmatters.io/fonts/roboto-v15-latin-regular.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
}

/* roboto-500 - latin */
@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 500;
  src: local('Roboto Medium'), local('Roboto-Medium'),
       url('https://cdn.perfmatters.io/fonts/roboto-v15-latin-500.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */
       url('https://cdn.perfmatters.io/fonts/roboto-v15-latin-500.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
}

/* roboto-700 - latin */
@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 700;
  src: local('Roboto Bold'), local('Roboto-Bold'),
       url('https://cdn.perfmatters.io/fonts/roboto-v15-latin-700.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */
       url('https://cdn.perfmatters.io/fonts/roboto-v15-latin-700.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
}

I then again ran some tests with the setup above and the average speed came out to 384ms.

As you can see, using a CDN is yet again just slightly faster. Not by much, but if you compare it to Google’s CDN, test it, it definitely is faster. Part of this is because it can utilize the same HTTP/2 connection, and it still reduces the external call and DNS lookup, just as hosting locally does. And of course, one advantage to this method is that it will be globally faster.

Summary

As you can see from the tests above, the Google Fonts CDN is great, but it might not always be the fastest. Of course, it will always depend on your own environment and where you are serving up traffic, whether it be to a local audience or global.

I recommend testing each method above for yourself and see which one is the fastest and works the best for your WordPress site. And remember, only load the font weights you actually need!

The post How to Speed up Google Fonts in WordPress appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/speed-google-fonts-wordpress/feed/ 11
How to Create Next & Previous Links in WordPress Posts https://speckyboy.com/next-and-previous-links-on-wordpress-posts/ https://speckyboy.com/next-and-previous-links-on-wordpress-posts/#respond Fri, 01 Nov 2024 07:51:59 +0000 http://speckyboy.com/?p=28148 On many WordPress themes you see links at the bottom of single posts which direct you to the previous and next posts of the blog. So, in this tutorial, I...

The post How to Create Next & Previous Links in WordPress Posts appeared first on Speckyboy Design Magazine.

]]>
On many WordPress themes you see links at the bottom of single posts which direct you to the previous and next posts of the blog.

So, in this tutorial, I will show you how to use the built-in WordPress functions to create those links.

There is a function for both the previous link and the next link. Both of these functions should be used on a single post within the loop. Both functions will echo the links on the screen and allow you to change the format of the links on the page.

The Previous Post Link

WordPress has the function previous_post_link which should be used in the loop of the single posts. This function will create a link to the previous post by date. If there are no posts, then a link will not be displayed.

To use the previous post link just use the below snippet:

<?php previous_post_link($format, $link, $in_same_cat = false, $excluded_categories = ''); ?>

This function accepts four parameters:

  • $format – This will allow you to change the format of the outputted link. To define just the link, use the token %link.
  • $link – This defines the text that is used on the link. The default is %title of the post.
  • $in_same_cat – This is a boolean which defines if the linked post is in the same category or not. The default is false.
  • $excluded_categories – This allows you to define which categories are excluded from being linked to.

Examples of Using Previous Post Link

All of the parameters in the previous_post_link are optional, so the simplest use of this function is to use no parameters:

<?php previous_post_link(); ?>

Change Link Format

To change the format of the link, you can wrap it in an h1 tag by using the first parameter:

<?php previous_post_link('<h1>%link</h1>'); ?>

Change Link Text

To change the text of the link, you need to change the second parameter:

<?php previous_post_link('%link', 'Link To Previous Post'); ?>

Link to Posts in the Same Category

To only link to previous posts in the same category, use the following snippet:

<?php previous_post_link('&laquo; %link', '%title', TRUE); ?>

Exclude Links in Category

To exclude any categories from being linked to from this link, you need to use the 4th parameter. To exclude all posts with a category ID of 17, use the following snippet:

<?php previous_post_link('&laquo; %link', '%title', FALSE, '17'); ?>

Next Post Link

The next_post_link function works the same way as the previous link but will return the next post. This takes the same parameters as the previous post link function and will work the same way.

If there is no next post, then the link will not be displayed.

<?php next_post_link('format', 'link', 'in_same_cat', 'excluded_categories'); ?>

Examples of Using Previous Post Link

All of the parameters in the next_post_link are optional, so the simplest use of this function is to use no parameters.

<?php next_post_link(); ?>

This adds a link on the page to the next post using the default values.

Change Link Format

To change the format of the link, you can wrap it in an h1 tag by using the first parameter:

<?php next_post_link('<h1>%link</h1>'); ?>

Change Link Text

To change the text of the link, you need to change the second parameter:

<?php next_post_link('%link', 'Link To Next Post'); ?>

Link to Posts in Same Category

To only link to the next posts in the same category, use the following snippet:

<?php next_post_link('&laquo; %link', '%title', TRUE); ?>

Exclude Links In Category

To exclude any categories from being linked to from this link, you need to use the 4th parameter. To exclude all posts with a category ID of 17, use the following snippet:

<?php next_post_link('&laquo; %link', '%title', FALSE, '17'); ?>

Use in a Theme

When you use these in your WordPress theme, you would want the previous link to float to the left and the next post link to float to the right.

Here is a real-world example of using these functions.

<?php
    previous_post_link('<span class="left">&laquo; %link</span>');
    next_post_link('<span class="right">%link &raquo;</span>');
?>                           
<div class="clearfix"></div>

This adds a span around both of the links adding a CSS class of left or right, so you can float the link. We then use the clearfix example to clear the floats on the page.

The post How to Create Next & Previous Links in WordPress Posts appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/next-and-previous-links-on-wordpress-posts/feed/ 0
How to Use the WordPress Custom Fields Plugin https://speckyboy.com/wordpress-custom-fields/ https://speckyboy.com/wordpress-custom-fields/#respond Mon, 28 Oct 2024 11:41:54 +0000 http://speckyboy.com/?p=50723 We explore some ideas of how you can use WordPress custom fields to create powerful enhancements to the appearance of your site.

The post How to Use the WordPress Custom Fields Plugin appeared first on Speckyboy Design Magazine.

]]>
Custom Fields are one of those features inside WordPress that not everyone is fully aware of. While they’ve been around for a while, they aren’t really screaming “use me” out of a standard install of WordPress. That said, they can really help you achieve some powerful and unique features in your projects.

Let’s explore one simple idea of how you can use WordPress custom fields to create an enhancement to the appearance of your site.

What You’ll Need

Before we start, make sure you install a copy of the Advanced Custom Fields plugin. While those proficient with PHP can create their own custom fields (or even use the more basic implementation that comes with WordPress), Advanced Custom Fields makes things a bit easier. It adds a familiar WYSIWYG interface and will even export the PHP for you under a separate Export entry in the plugin’s menu. If desired, you can then paste that code into your theme’s functions.php file. However, that isn’t completely necessary, as the custom fields you create will stay functional for as long as you keep the plugin active.

Let’s Create Some Fancy Page Titles

While there’s something to be said for simple text page titles, sometimes you might want something a little more interesting. For example, what if you wanted each page of your site to have its own page title background image, like this:

This has been designed to be a background image with a blue, semi-transparent box to hold the page’s title text. Here’s how to make it work:

Within Advanced Custom Fields

Within Advanced WordPress Custom Fields settings

  1. Create a new custom field set and give it a name such as Page Header. Take note of the field name that Advanced Custom Fields creates – page_header in this case.
  2. Select Image as your Field Type.
  3. Set the Return Value to Image URL. This will make it easier to display the image we upload on the front end of the site.
  4. Set Rules in the Location box to Post Type is equal to Page. You may also set this to a specific page, post type or category if you wish (adjust your code accordingly).
  5. In the Options box, set the position of your field to High (after title). This will ensure the custom field will be placed just below the title of your page inside WordPress.
  6. Save your field.

Of course, there are a lot of other options and field types you could explore. Take a look at the Advanced Custom Fields documentation for more information.

Inside the WordPress Editor

  1. After you have created your custom field, visit the page you wish to edit in the WordPress Dashboard.
  2. You’ll notice that the custom field we created is now towards the top of your page, just under the title:
    You'll notice that the custom field we created is now towards the top of your page
  3. From there, click on the Add Image button to upload your custom image. This will be familiar to you as it’s exactly the same process as using the Add Media feature in your pages and posts.
  4. Once your image is uploaded, you’ll see a preview of it. Make sure to save your page.
  5. You can repeat these steps for each page on your site that you would like to use a custom page title image.

In Your WordPress Template

  1. Find the page template you wish to edit in your theme/child theme. Since I’m going to add this field to every page in the site, I’m using page.php.
  2. Add code similar to this in place of your current page title area (you may need to do some digging if using a pre-built theme):

In Your Theme’s Stylesheet

  1. Paste the below CSS into your theme’s stylesheet:

 .custom-page-title {
 font-size:34px;
 line-height:40px;
 font-weight:normal;
 color:#FFF;
 height:150px;
 margin-top:10px;
 -moz-border-radius-topright: 75px;
 -webkit-border-top-right-radius: 75px;
 border-top-right-radius: 75px;
 -moz-border-radius-bottomright: 75px;
 -webkit-border-bottom-right-radius: 75px;
 border-bottom-right-radius: 75px;
}

 h1.custom-page-title span {
 position:absolute;
 background-image:url(images/page-title-background.png);
 width:240px;
 height:110px;
 padding:20px;
 }

Notice the use of in the style attribute of the H1 tag. This allows the custom page title images we uploaded to our pages to be used as a background image. Then, we created a box using a semi-transparent .png file which will hold the title’s text.

Of course, you can style this in any number of ways. Depending upon how you want to implement this custom field, you may also use conditional statements to create a default page title (fallback) image or even hide the field on specific pages.

So Many Possibilities

As with Custom Post Types, Custom Fields can help add some cool features to your site and even make it easier for your clients to update. Because there are so many different types of fields to use, you can customize virtually any type of content you want.

Take some time and play around with Advanced Custom Fields and see what you can create!

The post How to Use the WordPress Custom Fields Plugin appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/wordpress-custom-fields/feed/ 0
How to Add Conditional Logic to Your WordPress Theme https://speckyboy.com/conditional-logic-wordpress/ https://speckyboy.com/conditional-logic-wordpress/#comments Thu, 24 Oct 2024 22:14:28 +0000 https://speckyboy.com/?p=98274 We take a look at a few of the more commonly used Conditional Tags and how you might implement them into your own WordPress site.

The post How to Add Conditional Logic to Your WordPress Theme appeared first on Speckyboy Design Magazine.

]]>
Building a website with WordPress provides great flexibility with what you can do in terms of both design and functionality. And, as you get deeper into theme development, you’ll find that there are times when you need to target a specific page, category, or post type for something special. That’s where conditional logic can make your job much easier.

Conditional logic is a powerful feature of programming languages (PHP, in our case). In essence, we can use code to check if a certain condition exists and then do something specific if that condition is met. A simple example of this would be checking to see if a user is currently on our site’s home page. Using conditional logic, we might choose to load a slider or other special content in that situation.

With regards to WordPress, there are a number of useful Conditional Tags built into the software that let us test for all sorts of scenarios. They’re well-documented and allow you to bring a higher level of functionality to your site.

Today, we’ll take a look at a few of the more commonly used Conditional Tags and how you might implement them into your own site.

A Note on Using Condtional Tags

Conditional Tags are bits of PHP code and should go into your site’s active theme. There are a number of places you can use conditional logic within a theme.

If you haven’t already done so, it’s a good idea to familiarize yourself with the WordPress Template Hierarchy for an explanation of how theme files work.

And, before you try to implement new code on a live site, it’s best to set up a development (staging) environment to test things out first. Remember that one false move with PHP can give your site the dreaded “White Screen of Death”. So take great care in testing before you work on a live site.

is_home()

This one causes great confusion amongst developers. By looking at the tag, you’d assume that is_home() would be used for checking your site’s home page. That’s not the case.

It actually looks for the page assigned as your Posts page, which is set in Settings > Reading inside the WordPress dashboard. By default, WordPress uses your home page to list posts – but most sites tend to use a static home page instead.

So, for example, if you had assigned a page named “Blog” as your Posts page, that’s what is_home() will look for.

<?php

// If this the Posts page, display a message.
if ( is_home() ): 

echo '<h2>Thanks for visiting our blog!</h2>';

endif;

?>

is_front_page()

Conversely, is_front_page() looks for whichever page is set as your site’s home – regardless of whether it is static or not. Admittedly, this isn’t the most obvious thing in the world when you’re learning to create your own themes. But knowing which tag to use is vital.

What’s nice about this particular tag is that, even if you were to assign a different page as your home page later on, you’ll still target the right place. There are more explicit ways to target pages, but this one keeps you covered in the event of a change.

<?php
// If this is the home page, show a special message.
if ( is_front_page() ) { ?>

<h1>Welcome</h1>

<?php 
// Otherwise, show the page title.
} else { ?>

<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>

<?php } ?>

is_single() and is_page()

Each of these tags performs a dual function. is_single() looks to see if the current URL is a post. It could be a standard blog post, attachment or belong to a custom post type.

Similarly, is_page() will return true if the current URL is a page. By default, both tags target any content falling under the umbrella of a page or post. This is a common thread amongst many Conditional Tags.

<?php

// Target all posts.
if ( is_single() ):

echo 'You are on a single post.';

endif;

// Target all pages.
if ( is_page() ): 

echo 'This is a page';

endif; ?>

But you can also leverage these tags to target a specific post or page by adding an ID or slug.

<?php

// Target About Us
if ( is_page( 'about-us' ) ): ?>

<a href="#"></a>

<?php endif; ?>

Using an array will allow you to target multiple pieces of content.

<?php

// Target About Us and Contact Us pages.
if ( is_page( array('about-us', 'contact-us') ) ): ?>

<a href="#"></a>

<?php endif; ?>

is_tax() and has_term()

Taxonomies play a big role in how content is organized on a site. Two of the most common are categories and tags – which have their own Conditional Tags. But WordPress also enables us to create our own taxonomies.

For instance, if your site contains music reviews, you might have a taxonomy called “Genre”. From there, you could have listed specific genres of music within that taxonomy such as, “Rock”, “Hip-Hop” and “Jazz”.

is_tax() targets a taxonomy archive page. Staying with our music review example, this tag would fire (go into effect) when we are on the archive page for each of the specific genres.

<?php

// Display a message on our Genre archive pages.
if (is_tax('genre','rock','hip-hop','jazz') ):

echo '<h2>This is a genre archive. Enjoy!</h2>';

endif; ?>

has_term() is used to target the current post based on which taxonomy it belongs to. This is useful if, for example, we want to add a special graphic for posts in each genre of music on our site.

<?php

// Show an image for the Rock genre.
if (has_term('rock','genre') ): ?>

<?php endif; ?>

is_page_template()

Once you’re familiar with the template hierarchy of a theme, you may want to create your own custom page templates. is_page_template() lets you target the current page template being used (regardless of whether or not it’s custom). You can either check to see if any page template is being used at all, or look for a specific one.

You do have to be careful when looking for a specific page template, however. Since this tag checks for the existence of a filename, the conditional could stop working should that template’s name be changed. You’ll have to update your code to reflect any filename changes.

<?php

// Add a search form to the Services page template.
if (is_page_template('services.php') ):

?>

<?php get_search_form(); ?>

<?php endif; ?>

All Conditions Met

While this was just a brief introduction of how conditional logic can be used, it hopefully whets your appetite for learning more.

Once you master conditionals, you’ll be able to customize your site in ways that would be near impossible otherwise.

They can give you fine-grain control over the look and layout of your theme while still benefitting from all the advantages of utilizing a CMS.

The post How to Add Conditional Logic to Your WordPress Theme appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/conditional-logic-wordpress/feed/ 5
20 Time-Saving WordPress SQL Query Snippets https://speckyboy.com/wordpress-sql-query-snippets/ https://speckyboy.com/wordpress-sql-query-snippets/#comments Tue, 22 Oct 2024 11:02:03 +0000 http://speckyboy.com/?p=72089 WordPress stores every single scrap of information within a MySQL database. Posts, pages, comments, shortcodes, plugin settings… absolutely everything. The WordPress backend is fantastic and does allow you to manage...

The post 20 Time-Saving WordPress SQL Query Snippets appeared first on Speckyboy Design Magazine.

]]>
WordPress stores every single scrap of information within a MySQL database. Posts, pages, comments, shortcodes, plugin settings… absolutely everything. The WordPress backend is fantastic and does allow you to manage and edit everything with ease, but only up to a certain point.

Say you have hundreds or even thousands of posts within your database, and you need to make site-wide global changes. Making each edit via the WordPress Dashboard can be time-consuming and does open up the possibility of mistakes occurring. If you do need to make site-wide edits, then it’s time to roll up your sleeves and delve directly into the WordPress MySQL database.

Always Backup WordPress First!

Your WordPress database stores every single one of your carefully written posts, every comment from your loyal readers, and every setting you have used to personalize your site. No matter how confident you are in your ability to use SQL queries, always remember to backup your WordPress database first!

Here are some resources to help you backup WordPress:

  • WordPress Backups – Here you will find detailed instructions to backup your WordPress Site and your WordPress database as well as resources for automatic WordPress backups (plugins).
  • Free WordPress Backup Solutions – These free WordPress backup plugins cater to every need and website.

You might also like these useful .htaccess snippets or these snippets that make WordPress user-friendly for your clients.

Add a Custom Field to All WordPress Posts & Pages

This snippet will add a custom field to every post and page found in your WP database. All you have to do is replace the UniversalCutomField to whatever Custom Field name you like to create, and then change MyCustomFieldValue to the value of your choice.

INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT ID AS post_id, 'UniversalCustomField'
AS meta_key 'MyCustomFieldValue AS meta_value FROM wp_posts
WHERE ID NOT IN (SELECT post_id FROM wp_postmeta WHERE meta_key = 'UniversalCustomField');

For posts only, use this snippet…

INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT ID AS post_id, 'UniversalCustomField'
AS meta_key 'MyCustomFieldValue AS meta_value
FROM wp_posts WHERE ID NOT IN
(SELECT post_id FROM wp_postmeta WHERE meta_key = 'UniversalCustomField')
'' AND post_type = 'post';

…and for pages only, use this code…

INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT ID AS post_id, 'UniversalCustomField'
AS meta_key 'MyCustomFieldValue AS meta_value
FROM wp_posts WHERE ID NOT IN
(SELECT post_id FROM wp_postmeta WHERE meta_key = 'UniversalCustomField')
AND 'post_type' = 'page';

Delete WordPress Post Meta

When you install or remove plugins, they use the post meta to store data. After you have removed a plugin, the data will remain in the post_meta table, which of course, is no longer needed. Remember and change YourMetaKey to your own value before running this query.

DELETE FROM wp_postmeta WHERE meta_key = 'YourMetaKey';

Identify Unused WordPress Tags

In a WordPress database, if you run a query to delete old posts, like the one above, the old tags will remain. This query allows you to identify all of the unused tags.

SELECT * From wp_terms wt
INNER JOIN wp_term_taxonomy wtt ON wt.term_id=wtt.term_id WHERE wtt.taxonomy='post_tag' AND wtt.count=0;

Batch Delete WordPress Spam Comments

This little snippet is a life-saver. All you have to do to delete them all is run this SQL command:

DELETE FROM wp_comments WHERE wp_comments.comment_approved = 'spam';

Batch Delete All Unapproved WordPress Comments

This SQL query will remove all unapproved comments and not touch the approved comments.

DELETE FROM wp_comments WHERE comment_approved = 0

Disable WordPress Comments on Older Posts

For this query, specify the comment_status as either open, closed, or registered_only. Also, specify the date by editing the 2016-01-01 to suit your needs.

UPDATE wp_posts SET comment_status = 'closed' WHERE post_date < '2016-01-01' AND post_status = 'publish';

Disabling & Enabling WordPress Trackbacks & Pingbacks

For this query, specify the comment_status as either open, closed, or registered_only.

Globally enable pingbacks/trackbacks for all users:

UPDATE wp_posts SET ping_status = 'open';

Globally disable pingbacks/trackbacks for all users:

UPDATE wp_posts SET ping_status = 'closed';

For this query, specify the ping_status as either open or closed. Also, specify the date by editing the 2016-01-01 to suit your needs.

UPDATE wp_posts SET ping_status = 'closed' WHERE post_date < '2016-01-01' AND post_status = 'publish';

Delete WordPress Comments With a Specific URL

If you have spam comments that all contain the same URL, then this query allows you to remove them in one go. The following query will delete all comments with a particular URL. The '%' means that any URL containing the string within the '%' signs will be deleted.

DELETE from wp_comments WHERE comment_author_url LIKE "%nastyspamurl%" ;

Identify & Delete WordPress Posts that are over 'X' Days Old

If you ever need to identify and delete posts over a certain number of days old, this snippet will help.

To identify any posts that are over 'X' amount of days, run this query, remembering to replace the 'X' with the number of days you are looking for:

SELECT * FROM 'wp_posts'
WHERE 'post_type' = 'post'
AND DATEDIFF(NOW(), 'post_date') > X

To delete any posts that are over 'X' amount of days, run this query:

DELETE FROM 'wp_posts'
WHERE 'post_type' = 'post'
AND DATEDIFF(NOW(), 'post_date') > X

Removing Unwanted WordPress Shortcodes

WordPress shortcodes are great, but if you decide to stop using them, their code will stay within your post content. Here is a simple SQL query to run on your database to get rid of any unwanted shortcodes. Replace unusedshortcodes with your own shortcode name.

UPDATE wp_post SET post_content = replace(post_content, '[unusedshortcodes]', '' ) ;

Change Your WordPress Posts Into Pages and Vice-Versa

Changing posts to pages is very easy. All you have to do is run this short SQL query:

UPDATE wp_posts SET post_type = 'page' WHERE post_type = 'post'

… and if you want to change pages to posts use this snippet:

UPDATE wp_posts SET post_type = 'post' WHERE post_type = 'page'

Change Author Attribution On All WordPress Posts

The first thing you will need to do for this snippet is retrieve the IDs of the WordPress author. You can find this out by using the following SQL command:

SELECT ID, display_name FROM wp_users;

Once you have the old and new IDs, insert the command below, remembering to replace NEW_AUTHOR_ID with the new author ID and OLD_AUTHOR_ID with the old.

UPDATE wp_posts SET post_author=NEW_AUTHOR_ID WHERE post_author=OLD_AUTHOR_ID;

Batch Deleting WordPress Post Revisions

Post revisions can be very useful, but they also considerably increase the size of your MySQL database. You could manually delete post revisions, but a much quicker method would be to use this SQL query.

DELETE FROM wp_posts WHERE post_type ="revision";

Disable or Enable All WordPress Plugins

If you have ever encountered the white screen of death and found yourself unable to login to the WordPress Admin after activating a new plugin, then this snippet will certainly help you. It will disable all plugins instantly, allowing you to log back in.

UPDATE wp_options SET option_value = 'a:0:{}' WHERE option_name = 'active_plugins';

Changing the Destination URL of a WordPress Site

Once you've moved your blog (template files, uploads & database) from one server to another, the next thing you will then need to do is to tell WordPress your new address.

Remember and change https://www.old-site.com to your old URL, and the https://www.new-site.com to your new URL.

The first command to use is:

UPDATE wp_options SET option_value = replace(option_value, 'https://www.old-site.com', 'https://www.new-site.com') WHERE option_name = 'home' OR option_name = 'siteurl';

Then you will have to change the url from the table wp_posts with this snippet:

UPDATE wp_posts SET guid = replace(guid, 'https://www.old-site.com','https://www.new-site.com);

And finally, you'll need to search the content of your posts to be sure that your new URL link is not messing with the old URL:

UPDATE wp_posts SET post_content = replace(post_content, ' https://www.ancien-site.com ', ' https://www.nouveau-site.com ');

Change the Default 'Admin' WordPress Username

Every WordPress installation will create an account with the default Admin username. Being able to change this default username will give your WordPress admin panel additional security.

Change YourNewUsername to your new name:

UPDATE wp_users SET user_login = 'YourNewUsername' WHERE user_login = 'Admin';

Manually Reset your WordPress Password

If you have only a single user on your WordPress installation, and the login name is 'admin,' you can reset your password with this simple SQL query. Once executed, it will replace PASSWORD with your new password.

UPDATE 'wordpress'.'wp_users' SET 'user_pass' = MD5('PASSWORD') WHERE 'wp_users'.'user_login' ='admin' LIMIT 1;

Search & Replace WordPress Post Content

To search and replace post content, use the following code. Replace OriginalText with the current text and replace NewText with your new text.

UPDATE wp_posts SET 'post_content'
= REPLACE ('post_content',
'OriginalText',
'NewText');

Changing the URL of WordPress Images

If you need to change the paths of your images, you can use this SQL command:

UPDATE wp_posts
SET post_content = REPLACE (post_content, 'src=”https://www.myoldurl.com', 'src=”https://www.mynewurl.com');

The post 20 Time-Saving WordPress SQL Query Snippets appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/wordpress-sql-query-snippets/feed/ 4
Useful PHP Snippets for Improving WordPress Search https://speckyboy.com/10-useful-wordpress-search-code-snippets/ https://speckyboy.com/10-useful-wordpress-search-code-snippets/#comments Sat, 19 Oct 2024 22:32:24 +0000 http://speckyboy.com/?p=7581 We share ten really useful PHP code snippets that will help improve the result accuracy and functionality of search in WordPress.

The post Useful PHP Snippets for Improving WordPress Search appeared first on Speckyboy Design Magazine.

]]>
It is no secret that the standard search within WordPress is not the greatest. The problem is that WordPress takes your search term far too literally.

In this post, we have ten useful WordPress search code snippets that will help improve the search accuracy for your readers. Just copy and paste.

You might also like these useful .htaccess snippets & hacks, these WordPress SQL Query Snippets, or these snippets that make WordPress user-friendly for your clients.

How To Exclude Posts or Pages from WordPress Search Results

If you would like to be able to control which posts or pages should be excluded from WordPress search results, all you have to do is copy and paste the code below into your functions.php file.

In this snippet, posts with the IDs 0 and 1 will be excluded. Edit accordingly to suit your needs.

function SearchFilter($query) {
    if ($query->is_search) {
        $query->set('cat','0,1');
    }
    return $query;
}
add_filter('pre_get_posts','SearchFilter');

WordPress Drop-Down Category Search Form

A useful function you could give to your WordPress search would be to allow your readers to filter the search results by targeting a specific category. This can be achieved by using a simple drop-down containing all of the category titles.

All you have to do is replace the standard WordPress search form (found within the searchform.php) with the snippet below:

<form role="search" method="get" id="searchform" action="<?php bloginfo('siteurl'); ?>">
  <div>
    <label class="screen-reader-text" for="s">Search for:</label>
    <input type="text" value="" name="s" id="s" /> 
    in <?php wp_dropdown_categories( 'show_option_all=All Categories' ); ?> 
    <input type="submit" id="searchsubmit" value="Search" />
  </div>
</form>

Search Within a Specific WordPress Post Type

WordPress gives you the ability to search specific post types by using this small snippet.

All you have to do is copy and paste the code below into your functions.php file.

function SearchFilter($query) {
  if ($query->is_search) {
    // Insert the specific post type you want to search
    $query->set('post_type', 'feeds');
  }
  return $query;
}
// This filter will jump into the loop and arrange our results before they're returned
add_filter('pre_get_posts','SearchFilter');

Display the Number of Search Results Returned

If you would like to show your readers how many results have been found per search term, you could use this helpful snippet.

Open search.php and locate the following:

<h2 class="pagetitle">Search Results</h2>

And replace it with this code:

<h2 class="pagetitle">Search Result for post_count; _e(''); _e(''); echo $key; _e(''); _e(' &mdash; '); echo $count . ' '; _e('articles'); wp_reset_query(); ?>

Highlight WordPress Search Terms with jQuery

To help make your search results that little bit clearer to your readers, you could use this snippet which will highlight the searched term within the results.

Copy and paste the following code into your theme’s functions.php file:

function hls_set_query() {
  $query  = attribute_escape(get_search_query());
  if(strlen($query) > 0){
    echo '
      <script type="text/javascript">var hls_query  = "'.$query.'";</script>
    ';
  }
}
function hls_init_jquery() {
  wp_enqueue_script('jquery');
}
add_action('init', 'hls_init_jquery');
add_action('wp_print_scripts', 'hls_set_query');

And then add this code into your header.php file, just before the /head tag:

<style type="text/css" media="screen">
    .hls { background: #D3E18A; }
  </style>
  <script type="text/javascript">
  jQuery.fn.extend({
    highlight: function(search, insensitive, hls_class){
      var regex = new RegExp("(<[^>]*>)|(\\b"+ search.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1") +")", insensitive ? "ig" : "g");
      return this.html(this.html().replace(regex, function(a, b, c){
        return (a.charAt(0) == "<") ? a : "<strong class=\""+ hls_class +"\">" + c + "";
      }));
    }
  });
  jQuery(document).ready(function($){
    if(typeof(hls_query) != 'undefined'){
      $("#post-area").highlight(hls_query, 1, "hls");
    }
  });
  </script>

Disable WordPress Search

If you are looking for a way to disable all of WordPress’s search functionality, you could use this small snippet.

All you have to do is copy and paste the code below into your functions.php file.

function fb_filter_query( $query, $error = true ) {
  if ( is_search() ) {
    $query->is_search = false;
    $query->query_vars[s] = false;
    $query->query[s] = false;

    // to error
    if ( $error == true )
      $query->is_404 = true;
  }
}
add_action( 'parse_query', 'fb_filter_query' );
add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

Make your WordPress Search Results Unlimited

Sometimes you may not want your search results to be limited by the confines of the standard WordPress Loop. This snippet allows your search to return unlimited results.

In search.php you can add the following code above the loop for this functionality.

First of all find this code within search.php:

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

And then add this code:

<?php $posts=query_posts($query_string . '&posts_per_page=-1'); ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

The post Useful PHP Snippets for Improving WordPress Search appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/10-useful-wordpress-search-code-snippets/feed/ 12