Showing posts with label JQUERY. Show all posts
Showing posts with label JQUERY. Show all posts

Tuesday, October 27, 2020

Working With PHP Arrays in the Right Way

In this tutorial, I am going to make a list of common PHP array functions, with examples of usage and best practices. Every PHP developer must know how to use them and how to combine array functions to make code readable and short.

Also, there is a presentation with given code examples, so you can download it from the related links and show it to your colleagues to build a stronger team.

The Basics

There are two different ways of creating arrays. One is to use array() to specify the elements as key-value pairs. The other method is to put all elements inside []. There are two important points that you should remember when creating associate arrays with key pairs.

First, the key always has to be unique. If you try to use the same key multiple times in an array, PHP will ignore all other key-value pairs except the last one. Second, if a key is created as floats, bools, and valid string representations of integers, then it will be cast to integers.

Here are a few examples of creating arrays in PHP:

As you can see, using either array() or [] is equivalent when creating arrays. The shorthand notation has been available starting from PHP 5.4.

You also don't need to specify a key for every array value. When left out, PHP sets the key to one more than the largest specified integer key. All automatically assigned keys will be greater than or equal to 0.

Working With Keys and Values

Let's start with the basic functions that work with array keys and values. One of them is array_combine(), which creates an array using one array for keys and another for its values:

You should know that the array_values() function returns an indexed array of values, array_keys() returns an array of keys of a given array, and array_flip() exchanges keys with values:

You can check if an array contains a specific value and get its first corresponding key using the array_search() function. You can also use in_array() if you just want to know whether an array contains a specific element and are not interested in its position. Consider using the array_key_exists() function when you want to check if the array uses a given key.

As the example above shows, make sure you use strict type checking if you don't want any unexpected results.

If you want to look up multiple elements in an array, it's usually faster to check if it contains a particular value by first flipping the array with array_flip() and then using array_key_exists().

Make Your Code Shorter

The list() function, which is not really a function but a language construction, is designed to assign variables in a short way. For example, here's a basic example of using the list() function:

This construction works perfectly with functions like preg_slit() or explode() . Also, you can skip some parameters if you don't need them to be defined:

Also, list() can be used with foreach, which makes this construction even better:

With the extract() function, you can export an associative array to variables. For every element of an array, a variable will be created with the name of a key and value as a value of the element:

Be aware that extract() is not safe if you are working with user data (like results of requests), so it's better to use this function with the flags EXTR_IF_EXISTS and EXTR_PREFIX_ALL.

The opposite of the previous function is the compact() function, which makes an associative array from variables:

Filtering Functions

There is a great function for array filtering, and it is called array_filter(). Pass the array as the first param and an anonymous function as the second param. Return true in a callback function if you want to leave this element in the array, and false if you don't:

There is a way to filter not only by the values. You can use ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH as a third parameter to pass the key or both value and key to the callback function.

Also, you can call array_filter() without a callback to remove all empty values:

You can get only unique values from an array using the array_unique() function. Notice that the function will preserve the keys of the first unique elements:

With array_column(), you can get a list of column values from a multi-dimensional array, like an answer from a SQL database or an import from a CSV file. Just pass an array and column name:

Starting from PHP 7, array_column() becomes even more powerful, because it is now allowed to work with an array of objects. So working with an array of models just became easier:

Walking Through the Arrays

Using array_map(), you can apply a callback to every element of an array. You can pass a function name or anonymous function to get a new array based on the given array:

There is a myth that there is no way to pass values and keys of an array to a callback, but we can bust it:

But this looks dirty. It is better to use array_walk() instead. This function looks the same as array_map(), but it works differently. First of all, an array is passed using a reference, so array_walk() doesn't create a new array, but changes a given array. So as a source array, you can pass the array value using a reference in a callback. Array keys can also be passed easily:

Joining the Arrays

The best way to merge two or more arrays in PHP is to use the array_merge() function. Items of arrays will be merged together, and values with the same string keys will be overwritten with the last value:

To remove array values from another array (or arrays), use array_diff(). To get values which are present in given arrays, use array_intersect(). The next examples will show how it works:

Do the Math With Array Values

Use array_sum() to get a sum of array values, array_product() to multiply them, or create your own formula with array_reduce():

To count all the values of an array, use array_count_values(). It will give all unique values of a given array as keys and a count of these values as a value:

Generating Arrays

To generate an array with a given size and the same value, use array_fill():

To generate an array with a range of keys and values, like hours in the day or letters, use range():

To get a part of an array—for example, just the first three elements—use array_slice():

If you ever want to generate an associative array with different keys and the same value assigned to each key, you can simply use the array_fill_keys() function.

Sorting Arrays

It is good to remember that every sorting function in PHP works with arrays by a reference and returns true on success or false on failure. There's a basic sorting function called sort(), and it sorts values in ascending order without preserving keys. The sorting function can be prepended by the following letters:

  • a, sort preserving keys
  • k, sort by keys
  • r, sort in reverse/descending order
  • u, sort with a user function

You can see the combinations of these letters in the following table:


a k r u
a asort()
arsort() uasort()
k
ksort() krsort()
r arsort() krsort() rsort()
u uasort()

usort()

Combining Array Functions Like a Boss

The real magic begins when you start to combine array functions. Here is how you can trim and remove empty values in just a single line of code with array_filter() and array_map():

To create an id to a title map from an array of models, we can use a combination of array_combine() and array_column():

To get the top three values of an array, we can use array_count_values()arsort(), and array_slice():

It's easy to use array_sum() and array_map() to calculate the sum of order in a few rows:

Conclusion

As you can see, knowledge of the main array functions can make your code much shorter and more readable. Of course, PHP has many more array functions, and even the given functions have many variations to use with extra parameters and flags, but I think that in this tutorial we've covered the basics that every PHP developer should know.

Learn PHP With a Free Online Course

If you want to learn PHP, check out our free online course on PHP fundamentals!

 

In this course, you'll learn the fundamentals of PHP programming. You'll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you'll build up to coding classes for simple object-oriented programming (OOP). Along the way, you'll learn all the most important skills for writing apps for the web: you'll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.



by Anton Bagaiev via Envato Tuts+ Code

Service Box 167

The post Service Box 167 appeared first on Best jQuery.


by Admin via Best jQuery

Preloader Style 280

The post Preloader Style 280 appeared first on Best jQuery.


by Admin via Best jQuery

Monday, October 26, 2020

Range Slider Style 81

The post Range Slider Style 81 appeared first on Best jQuery.


by Admin via Best jQuery

CSS Timeline Style 117

The post CSS Timeline Style 117 appeared first on Best jQuery.


by Admin via Best jQuery

PHP Control Structures and Loops: if, else, for, foreach, while, and More

Today, we're going to discuss control structures and loops in PHP. I'll show you how to use all the main control structures that are supported in PHP, like if, else, for, foreach, while, and more.

What Is a Control Structure?

In simple terms, a control structure allows you to control the flow of code execution in your application. Generally, a program is executed sequentially, line by line, and a control structure allows you to alter that flow, usually depending on certain conditions.

Control structures are core features of the PHP language that allow your script to respond differently to different inputs or situations. This could allow your script to give different responses based on user input, file contents, or some other data.

The following flowchart explains how a control structure works in PHP.

PHP Control Structures and Loops if Condition Flow

As you can see in the above diagram, first a condition is checked. If the condition is true, the conditional code will be executed. The important thing to note here is that code execution continues normally after conditional code execution.

Let's consider the following example.

PHP Control Structures and Loops elseif Condition Flow

In the above example, the program checks whether or not the user is logged in. Based on the user's login status, they will be redirected to either the Login page or the My Account page. In this case, a control structure ends code execution by redirecting users to a different page. This is a crucial ability of the PHP language.

PHP supports a number of different control structures:

  • if
  • else
  • elseif
  • switch
  • while
  • do-while
  • for
  • foreach
  • and more

Let's take a look at a few of these control structures with examples.

Learning PHP Control Structures

In the previous section, we learned the basics of control structures in PHP and their usefulness in application development. In this section, we'll go through a couple of important control structures that you'll end up using frequently in your day-to-day application development.

PHP If Statement

The if construct allows you to execute a piece of code if the expression provided along with it evaluates to true.

Let's have a look at the following example to understand how it actually works.

The above example should output the Your age is greater than 30! message since the expression evaluates to true. In fact, if you want to execute only a single statement, the above example can be rewritten as shown in the following snippet without brackets.

On the other hand, if you have more than one statements to execute, you must use brackets, as shown in the following snippet.

PHP Else Statement

In the previous section, we discussed the if construct, which allows you to execute a piece of code if the expression evaluates to true. On the other hand, if the expression evaluates to false, it won't do anything. More often than not, you also want to execute a different code snippet if the expression evaluates to false. That's where the else statement comes into the picture.

You always use the else statement in conjunction with an if statement. Basically, you can define it as shown in the following pseudo code.

Let's revise the previous example to understand how it works.

So when you have two choices, and one of them must be executed, you can use the if-else construct.

PHP Else If Statement

We can consider the elseif statement as an extension to the if-else construct. If you've got more than two choices to choose from, you can use the elseif statement.

Let's study the basic structure of the elseif statement, as shown in the following pseudo code.

Again, let's try to understand it using a real-world example.

As you can see in the above example, we have multiple conditions, so we've used a series of elseif statements. In the event that all if conditions evaluate to false, it executes the code provided in the last else statement.

PHP Switch Statement

The switch statement is somewhat similar to the elseif statement which we've just discussed in the previous section. The only difference is the expression which is being checked.

In the case of the elseif statement, you have a set of different conditions, and an appropriate action will be executed based on a condition. On the other hand, if you want to compare a variable with different values, you can use the switch statement.

As usual, an example is the best way to understand the switch statement.

As you can see in the above example, we want to check the value of the $favourite_site variable, and based on the value of the $favourite_site variable we want to print a message.

For each value you want to check with the $favourite_site variable, you have to define the case block. If the value is matched with a case, the code associated with that case block will be executed. After that, you need to use the break statement to end code execution. If you don't use the break statement, script execution will be continued up to the last block in the switch statement.

Finally, if you want to execute a piece of code if the variable's value doesn't match any case, you can define it under the default block. Of course, it's not mandatory—it's just a way to provide a default case.

So that's the story of conditional control structures. We'll discuss loops in PHP in the next section.

Loops in PHP

Loops in PHP are useful when you want to execute a piece of code repeatedly until a condition evaluates to false. So code is executed repeatedly as long as a condition evaluates to true, and as soon as the condition evaluates to false, the script continues executing the code after the loop.

The following flowchart explains how loops work in PHP.

Loop Flow

As you can see in the above screenshot, a loop contains a condition. If the condition evaluates to true, the conditional code is executed. After execution of the conditional code, control goes back to the loop condition, and the flow continues until the condition evaluates to false.

In this section, we'll go through the different types of loops supported in PHP.

While Loop in PHP

The while loop is used when you want to execute a piece of code repeatedly until the while condition evaluates to false.

You can define it as shown in the following pseudo code.

Let's have a look at a real-world example to understand how the while loop works in PHP.

If you're familiar with the Fibonacci series, you might recognize what the above program does—it outputs the Fibonacci series for the first ten numbers. The while loop is generally used when you don't know the number of iterations that are going to take place in a loop.

Do-While Loop in PHP

The do-while loop is very similar to the while loop, with the only difference being that the while condition is checked at the end of the first iteration. Thus, we can guarantee that the loop code is executed at least once, irrespective of the result of the while expression.

Let's have a look at the syntax of the do-while loop.

Let's go through a real-world to understand possible use-cases where you can use the do-while loop.

In the above example, we're trying to read a file line by line. Firstly, we've opened a file for reading. In our case, we're not sure if the file contains any content at all. Thus, we need to execute the fgets function at least once to check if a file contains any content. So we can use the do-while loop here. do-while evaluates the condition after the first iteration of the loop.

For Loop in PHP

Generally, the for loop is used to execute a piece of code for a specific number of times. In other words, if you already know the number of times you want to execute a block of code, it's the for loop which is the best choice.

Let's have a look at the syntax of the for loop.

The expr1 expression is used to initialize variables, and it's always executed. The expr2 expression is also executed in the beginning of a loop, and if it evaluates to true, the loop code is executed. After execution of the loop code, the expr3 is executed. Generally, the expr3 is used to alter the value of a variable which is used in the expr2 expression.

Let's go through the following example to see how it works.

The above program outputs the square of the first ten numbers. It initializes $i to 1, repeats as long as $i is less than or equal to 10, and adds 1 to $i at each iteration.

For Each in PHP

The foreach loop is used to iterate over array variables. If you have an array variable, and you want to go through each element of that array, the foreach loop is the best choice.

Let's have a look at a couple of examples.

If you want to access array values, you can use the first version of the foreach loop as shown in the above example. On the other hand, if you want to access both a key and a value, you can do it as shown in the $employee example above.

Breaking Out of the Loop

There are times when you might want to break out of a loop before it runs it course. This can be achieved easily using the break keyword. It will get you out of the current forforeachwhiledo-while or switch structure.

You can also use break to get out of multiple nested loops by supplying a numeric argument. For example, using break 3 will break you out of 3 nested loops. However, you cannot pass a variable as the numeric argument if you are using a PHP version greater than or equal to 5.4.

Another keyword that can interrupt loops in PHP is continue. However this only skips the rest of the current loop iteration instead of breaking out of the loop altogether. Just like break, you can also use a numerical value with continue to specify how many nested loops should it skip for current iteration.

Conclusion

In this article, we discussed different control structures and loops in PHP. They are an essential part of PHP—or any programming language for that matter.

Learn PHP With a Free Online Course

If you want to learn PHP, check out our free online course on PHP fundamentals!

 

In this course, you'll learn the fundamentals of PHP programming. You'll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you'll build up to coding classes for simple object-oriented programming (OOP). Along the way, you'll learn all the most important skills for writing apps for the web: you'll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.


by Sajal Soni via Envato Tuts+ Code

A Guide to Overriding Parent Theme Functions in Your Child Theme

If you've had any experience working with parent and child themes in WordPress, you'll know that the template files in your child theme override those in your parent theme. So for example if your parent theme has a page.php file and you create a new one in your child theme, WordPress will use the one in the child theme when displaying pages.

You might think that functions would work in the same way: create a new function in your child theme's functions.php file with the same name as one in the parent theme, and it'll take precedence. Unfortunately it isn't as simple as this.

In this tutorial I'll show you three methods you can use to override functions from the parent theme in your child theme:

  • pluggable functions
  • function priority
  • removing functions from the hook they're attached to

How Functions in Parent and Child Themes Work

Before examining the methods for overriding functions in your child themes, it helps to understand how functions work in parent and child themes.

Firstly, you need to know that all of the functions in your parent theme will be run when you're using a child theme. You don't have to add anything to your child theme's functions file to make this happen. This is different from CSS, where you have to manually include the parent theme's stylesheet in the child theme's stylesheet.

Another thing to know is that if your parent and child themes have functions with the same name, this will break your site—unless the function in the parent theme is a pluggable function (more on this shortly). This is why it’s important to use prefixes for all your functions, and to use a different prefix in parent and child themes—just in case.

However you can change the order in which functions are fired, and you can prevent functions from being fired altogether, as we'll see shortly.

Pluggable Functions

Pluggable functions are something you code into your parent theme, so they won't be any use to you if you're working with an existing parent theme that doesn't have them.

But if you're writing your own parent theme, maybe as a starting point for future projects, or if you're creating your own theme framework, it's good practice to make your functions pluggable so that you can easily override them in child themes. It's also a good idea to look through the functions that are written into the parent theme you're using, as many of them, including the WordPress default theme, will have pluggable functions.

To write a pluggable function, you simply enclose it in a conditional tag to check if a function with that name has already been run:

So if you enclose the functions in your parent theme in a conditional tag like this, WordPress will check if there is a function with the same name in your child theme that's already been run, and if that's the case it won't run the function from the parent theme.

Then when you come to write a function in your child theme which you want to override the one in the parent theme, you just give it the same name as the one in the parent theme:

WordPress will run the function in the child theme first, and when it comes to the one in the parent theme, it'll check if it already exists and because it does, it won't run it.

Function Priority

If you're not using your own parent theme, or you're using a third party one without pluggable functions, you'll need another method.

When you write functions you can assign them a priority, which tells WordPress when to run them. You do this when adding your function to an action or filter hook. WordPress will then run the functions attached to a given hook in ascending order of priority, so those with higher numbers will run last.

Let's imagine the function in the parent theme isn't pluggable, and looks like this:

This function is attached to the init hook and hasn't been given a priority. By default WordPress assigns a priority of 10 to functions which haven't had a priority added, so to fire your function after it you use a number larger than 10. I tend to use 15 so I've got some breathing room in case I want to add another function between the two later on.

This means the function in your child theme would look like this:

Alternatively, the function in your parent theme may have had a priority assigned to it:

So you just need to make sure the priority you give the function in your child theme is higher:

Removing Functions From Hooks

Sometimes running another function after the first one isn't enough to override it—you need to make sure the function in the parent theme doesn't run at all. In this case, you can remove the parent theme function from the hook it's attached to, using the remove_action() or remove_filter() functions. The one you use will depend on whether the function is attached to an action hook or filter hook in the parent theme.

So let's return to our previous function in the parent theme:

To remove this function from its action hook and therefore prevent it from firing, you create a function in your child theme to remove it using remove_action():

However, this won't work on its own—you need to attach this function to a hook which will fire after the hook which the parent theme function is attached to. This is because you can't remove the action before it's been fired. You can find details of the order in which actions are fired in the Codex.

Once you've done this, you can simply write an alternative function to replace the parent theme function in your child theme's functions file, or you can do nothing if all you wanted to do was remove the functionality from the parent theme.

A Note on Priorities

Note that if you're trying to remove a function using remove_action() or remove_filter() and the function has had a priority assigned to it, you must include the priority when removing it, or it won't work.

So if the function in the parent theme looks like this:

... you'll need to include the same priority value when removing it:

Advanced Parent and Child Theme Functions: Plugable Functions and Extending Functions

As well as the above, there are some specific scenarios in which you might want to take things further. The following tips are in response to questions that have been asked in the comments below.

How to Partially Override a Function in the Parent Theme

Strictly speaking, you can’t partially override a function. You can only let it run, or disable it. But there are workarounds.

The first is if the function you want to partially override itself contains functions that are pluggable. You might find that the function includes a call to another pluggable function from within the parent theme.

If this is the case, you can override any functions within the main function, if that’s the code you want to change. Do it by writing a new version of the pluggable function that either contains just a return statement or contains alternative code. Note that this will only work if the function is pluggable—if it isn’t, your site will break. 

However this method only works if you’re lucky enough to need to override functionality within a function that’s provided by another contained and pluggable function.

In the vast majority of cases, this won't be an option. In which case, you'll need to deactivate the function and replace it with a function of your own, with a different name. To create your new function, you can copy and paste the function from the parent theme into the child themes functions.php file, and then edit it to remove the code you don’t want.

You’d use two of your own functions: one to remove the original one, and the second to provide new code, like this example overriding a parent theme called on the init hook:

How to Override Non-Pluggable Functions

Functions in the parent theme that aren’t pluggable can’t be overridden in any special way. So you’d have to use the method above, removing the function from its action hook and then writing a new function on the same action hook that provides the new code.

Don’t give the function in your child theme the same name as the function from the parent theme as this will break your site!

How to Extend Parent Theme Functions

Functions are generally not designed to be extendable. However there may be an exception if your function includes calls to other pluggable functions.

If this is the case, you can extend the function by overriding the functions within the main function, without having to replace the whole of the main function.

In most cases, you can only extend a parent theme function in one of three ways:

  • If the function you want to extend is pluggable, copy it into your child theme and add extra code to extend it.
  • If the function isn't pluggable, remove it from its hook using remove_action() and write a new function (with a different name) on the same hook with extra code. You might want to copy code from the original function into your new function and edit that.
  • Write a second function which is called on the same hook as the first function and adds extra code that will run before or after the first function. Use the priority parameter in add_action() to specify whether your second function will run before or after the original function.

Summary

Overriding functions in a parent theme is more complicated than overriding template files or styling, but it can be done. Here I've shown you three methods for doing this:

  • If you're writing your own parent theme, or using one which has them, use pluggable functions so that a function in the child theme with the same name as one in the parent theme will replace it.
  • Assign higher priorities to functions in your child themes to ensure they're run after those in your parent theme.
  • Use remove_action() or remove_filter() to remove functions in the parent theme altogether.

Which method you use will depend on the way your parent theme is coded and whether you need to remove the parent theme function altogether or just run another function after it to override it.


by Rachel McCollin via Envato Tuts+ Code

Sunday, October 25, 2020

WP_Query Arguments: Categories and Tags

In the earlier parts of this series, you've learned how WP_Query is structured and what its properties and methods are. The next stage is to understand the various arguments you can use with it and how best to do so.

WP_Query has a large number of possible arguments, which makes it extremely flexible. As you can use it to query just about anything held in your wp_posts table, it has arguments for every permutation of query you might want to run on your content.

In this tutorial I'll look at two types of argument for categories and tags:

The arguments for these two taxonomies are similar but do have some differences you need to know about if you're going to use them effectively.

A Recap on How Arguments Work in WP_Query

Before we start, let's have a quick recap on how arguments work in WP_Query. When you code WP_Query in your themes or plugins, you need to include four main elements:

  • the arguments for the query, using parameters which will be covered in this tutorial
  • the query itself
  • the loop
  • finishing off: resetting post data

In practice this will look something like the following:

The arguments are what tells WordPress what data to fetch from the database and it's those that I'll cover here. So all we're focusing on here is the first part of the code:

As you can see, the arguments are contained in an array. You'll learn how to code them as you work through this tutorial.

Coding Your Arguments

There is a specific way to code the arguments in the array, which is as follows:

You must enclose the parameters and their values in single quotation marks, use => between them, and separate them with a comma. If you get this wrong, WordPress may not add all of your arguments to the query or you may get a white screen.

Category Parameters

Let's start with category parameters. The options you have here are as follows:

  • cat (int): use category id.
  • category_name (string): use category slug (NOT name).
  • category__and (array): use category id.
  • category__in (array): use category id.
  • category__not_in (array): use category id.

Note that for none of these do you use the name of your category. Even the category_name parameter takes the slug as its value, not its name. I tend to use this one rather than the ID as when I come back to my code at a later date, slugs are easier to identify than IDs. However if you think your site users might change the slug for one or more categories, I recommend using the ID to avoid any problems.

Let's take a look at how you use each of these.

The cat Parameter

The cat parameter is straightforward: just use a single category ID or a string of category IDs.

Querying for one category looks like this:

Querying for multiple categories looks like this:

The above will tell WordPress to fetch posts that are in any of the categories listed. If you want to find posts in every one of an array of categories, you use the category_and parameter, of which more shortly.

You can also use the cat parameter to find posts that are in one category but not another, by using a minus sign before the category ID as follows:

The above would query posts in category 12 but not in category 13.

The category_name Parameter

The category_name parameter uses the category slug, not the name (confusing, I know!). Again you can use it with a single category or with a string of categories to find posts that are in any of the categories.

To query posts in a single category you add:

And to find posts in one or more of a number of categories, use this:

As with the cat parameter, this won't find posts that are in all of the categories, but it will find posts in any of the categories.

The category__and Parameter

If you want to find posts that are in all of an array of categories, this is the parameter you use. It takes the category IDs for its value. So to find posts in all of three categories, you would use:

Note that this uses an array not a string, so you code it differently. The parameter has two underscores in its name: use just one and it won't work.

The category__in Parameter

The next parameter looks for posts in one or more of an array of categories. It actually works in the same way as the cat parameter, and also takes the category ID as its value.

So to query posts in one or more of an array of categories, you would use:

The above would fetch posts from one or more of these categories.

The category__not_in Parameter

The category__not_in parameter does as you would expect: it queries posts which are not in a category or an array of categories.

To exclude posts from one category, you would use the following:

And to exclude posts from an array of categories:

This would exclude posts from any of these categories.

Tag Parameters

Tags have slightly different parameters from categories: you can't work out what they might be based on your knowledge of category parameters, I'm afraid!

The tag parameters are:

  • tag (string): use tag slug.
  • tag_id (int): use tag id.
  • tag__and (array): use tag ids.
  • tag__in (array): use tag ids.
  • tag__not_in (array): use tag ids.
  • tag_slug__and (array): use tag slugs.
  • tag_slug__in (array): use tag slugs.

Let's look at each of these.

The tag Parameter

The tag parameter takes the tag slug for its value and can be used to find posts with one tag or with any of a string of tags.

So to find posts with one tag you use:

And to find posts with tags from an array of tags:

Note that the above queries posts with any of the tags in the array, not all of them.

The tag_id Parameter

The tag_id parameter works in a similar way to the cat parameter: it takes the tag ID and can be used with a single tag or multiple tags.

To find posts with a single tag you use this:

To find posts with one or more tags from a string of tag IDs:

You can also use tag_id to exclude tags, either when using it for single tags or multiple tags.

So to query posts except those with a given tag, you'd use:

While to find posts with one of two tags but without another tag, you'd use this:

So the above will query posts with either or both of tags 21 or 23 but not tag 22.

The tag__in Parameter

This parameter lets you find posts with one or more of an array of tags. It works in the same way as tag when used with an array:

This will query posts with any or all of the tags listed. If you want to find posts with all of the tags, you use tag__and, which I'll cover in a moment.

The tag__not_in Parameter

The tag__not_in parameter lets you query posts which don't have a given tag or array of tags.

Use it like this to exclude one tag:

Note that you still need to use an array even though you're only using one tag. For more tags, use:

This will query posts that don't have any of the above tags.

The tag_slug__and and tag_slug__in Parameters

These two parameters behave in exactly the same way as the tag__and and tag__in parameters, except that you use that tag slug in your arrays instead of the tag ID.

So for example to find posts which have both of a pair of tags, you use tag__slug_in:

This finds posts with any of these tags. You could also use the tag parameter with a string of tag slugs to achieve the same result.

To include posts with all of a set of tags, use tag_slug__and:

Instead of querying posts with any of the tags, this only queries posts that have all of the tags.

Advanced Use of Categories and Tags with WP_Query

Let’s take a look at some advanced uses of category and tag arguments with WP_Query, based on questions raised in the comments to this article.

List Subcategories of a Category

To list the subcategories of a given category (with a link to the subcategory archives for each), you wouldn’t use WP_Query. Instead you’d use wp_list_categories(), which outputs a list of categories with links to their archives. To output the subcategories of a specific category, use the ‘child_of' argument.

Here’s the code:

Substitute the 5 in the code above for the ID of the category whose subcategories you want to list.

Display The First Post from a Category in One Element Then More Posts in Another Element

This is a useful technique if you want to highlight the most recent post from a category, maybe including the excerpt and featured image for that post, and then show a list of the next few posts from the category.

You do this by using the 'posts_per_page' and 'offset' arguments.

The simplest way to do this is to write two separate queries. The first uses 'posts_per_page' => 1 to just fetch the first post. The second query uses'offset' => 1 to fetch posts after the first post, and also uses 'posts_per_page' to define how many posts to output.

Here’s the code:

An alternative method, which involves fewer calls to the database, is to write one query and then loop back through that query a second time, rewinding the query and using a variable to make sure the post output by the first loop isn’t repeated. 

You can find more about using one query for multiple loops in our tutorial on the subject.

Display Posts From Multiple Categories

If you want to display posts that are in a given category and also in one or more of your other categories, you use the cat and category__in arguments. For each of these you use the category ID.

Imagine you want your posts to be category 1 and also in one or more of categories 2, 3 and 5.

Here are the arguments you would use for this:

Summary

Querying your posts by category and/or tag is something there's a good chance you'll have occasion to do with WP_Query. By using the arguments above, and combining them where necessary, you can create powerful arguments to extract exactly the data you need from the database.

If you want to learn more about WP_Query, check out some of my other posts in the Mastering WP_Query series.


by Rachel McCollin via Envato Tuts+ Code

20 Essential WordPress Utilities to Manage Your Site

WordPress utility plugins let you make enhancements to all aspects of your WordPress website: performance, design, and security. 

With thousands of options available, however, it can be quite difficult sorting the good from the not so good.

In addition, you need to be very selective when deciding on what kinds of plugins you want to use because each plugin added to your site can decrease the load speed of your pages. More plugins also increase the likelihood of scripting conflicts.

With all these issues in mind, I’ve compiled a list of 20 essential WordPress utility plugins available at CodeCanyon to help take your site from good to great. 

There is still a lot of room to improve basic and critical functionality of your WordPress website, and the best way to do so is with utility plugins. Grab some of these best selling WordPress utility plugins and take your website to the next level!

Best selling WordPress Utilities

The Best-Selling WordPress Utilities of 2020

Let's look at the WordPress utility plugins available at CodeCanyon that will help take your site to the next level. 

1. WPBakery Page Builder for WordPress

WPBakery Page Builder for WordPress

WPBakery Page Builder for WordPress, formerly Visual Composer, is an easy-to-use page builder that will help you create any layout you desire quickly and easily. 

This visual page builder allows you to use simple drag-and-drop widgets or building blocks that allow you to create eye-catching websites without having to understand any coding. This allows you to build out your ideas visually and build out your website quickly and easily.  

This page builder not only allows you to visually construct any page on your website in the WordPress admin back-end, but it allows you to construct any page in the front-end as well.   

2. Yellow Pencil

Yellow Pencil

Yellow Pencil is a WordPress CSS editor plugin which allows you to customise any theme quickly and easily by editing it in real time. All you need to do is click on an element you want to modify, start changing its features visually, and Yellow Pencil will create the required CSS style codes in the background for you. The plugin provides over 50 style properties, 500 fonts, 300 background colors, and a live color picker to help you modify your site. 

3. Hide My WP

Hide My WP

Hide My WP is a security plugin that hides the fact you’re using WordPress on your site, which allows you to fly under the radar of attackers that target WordPress sites. 

In addition, their Intrusion Detection system automatically monitors the site and finds potentially dangerous requests. It then provides you with all details of the attacker like who they are, where they’re located, and how they’re trying to hack your site, and suggests whether they should be blocked or not.

Other great features include:

  • easily replace any words in your HTML output file
  • easily change or hide any URL 
  • notify you when someone is poking around your WordPress site
  • change default WordPress email sender

4. Interactive World Maps

Interactive World Maps

Using maps on your website is a great way to integrate content with location, and the Interactive World Maps plugin is an ideal utility plugin for doing so. The plugin allows you to include maps in posts, pages, and even in the sidebar of your site. 

You can choose to use a map of the entire world, a continent, a country, a region, or a city. You can also add active colour regions to the map and display them in two different ways, as regions and as markers.

Other great features include:

  • ability to add interactivity
  • change background colour
  • change the width and height of the map
  • and much more

5. Advanced Google Maps Plugin for WordPress

Advanced Google Maps Plugin for WordPress

If the Interactive World Maps above isn’t quite what you were looking for, then Advanced Google Maps Plugin for WordPress offers another viable option. This is a great plugin for displaying multiple posts, pages or custom posts on a single Google map. You can assign a location to your post easily using the meta box or your own custom fields.

Other great features include:

  • display posts information like title, content, featured image, categories, etc.
  • display post listing below the map and show post information in the listing 
  • possible to customise HTML easily to integrate your own design
  • display posts or locations below the map in grid or list format

6. Video Gallery Plugin

Video Gallery Plugin

Video galleries are a great way to keep your visitors engaged. Here is where Video Gallery plugin comes in, to help you create a compelling WordPress video gallery. This plugin allows you to feature single videos, or mix-and-match video sources, streams, galleries, and playlists to curate the exact content you desire. 

It's fully responsive, with subtitle support and AdSense compatibility, making it a solid choice for a dedicated WordPress video gallery. You can completely customize the look and function of your player with a user-friendly, drag-and-drop admin panel. You can also use the Design Centre to generate a brand-compatible skin for your video gallery. 

7. Essential Grid Gallery

Essential Grid Gallery

And if you want a plugin that builds video galleries and more, then the Essential WordPress gallery plugin allows you to build grid-style galleries using images, video, and audio files from a wide variety of sources, both self-hosted and social. Use the template library to create a fully-responsive and mobile-optimized gallery, or connect with Instagram, YouTube, Twitter, and more to stream social media content. Dozens of fully customizable skins and animation options give you total control of the look and feel of your gallery.

8. White Label Branding for WordPress

White Label Branding for WordPress

White Label Branding for WordPress allows developers more latitude in customising WordPress menus. The plugin allows you to customise the WordPress admin and the login screen and add a Role and Capability Manager, which allows you to create new user roles and assign capabilities and decide who has access to what features of the site.

Other great features include:

  • ability to add your own favicon easily
  • hide certain screen options
  • add a private dashboard metabox for editors or administrators eyes only
  • and much more

9. Reviewer WordPress Plugin

Reviewer WordPress Plugin

Reviewer WordPress Plugin offers you a great way for visitors, customers and clients to leave reviews on your site. What’s more, the plugin also allows you to add comparison tables inside your WordPress blog posts, pages, and custom posts. 

Reviewer WordPress plugin offers a good range of customisable themes so that you can adapt your reviews and comparison tables to fit your site, and each theme has a responsive layout to adapt to any devices.

Other great features include:

  • review box and user review widgets
  • three different rating modes
  • ability to collect visitor name and email
  • Google ReCaptcha for preventing spamming
  • and much more

10. Ajax Search Pro

Ajax Search Pro

If you’re looking for a better search function than the native one WordPress provides, check out Ajax Search Pro. It's a live search engine plugin for WordPress that provides users with customisable front-end settings. 

For example, by checking different boxes, the user can change the behaviour of the plugin to look for exact matches, include or exclude certain post types, categories, etc.

Other great features include:

  • four built-in layouts
  • image support
  • custom field filters
  • keyword highlighting
  • and much more

11. Blog Designer PRO for WordPress

Blog Designer Pro for WordPress

If you’ve ever dreamed of designing your own blog but don’t have the necessary coding skills, Blog Designer PRO for WordPress may be the answer. Unlike the average blog template, the plugin comes with 36 templates, all of which you can customise extensively to suit your own design aesthetic.

Other great features include:

  • fully responsive blog templates
  • support of custom post type
  • preview of blog layout
  • and much more 

12. Super Store Finder for WordPress

SuperStore Finder for WordPress

Super Store Finder for WordPress is a great plugin for businesses who want to help their website visitors and potential customers find their stores easily and quickly. The plugin is integrated with Google Maps API v3 and has a fully responsive design for smartphones, tablets, and touch-screen devices.

Other great features include:

  • multiple store locator layouts to choose from
  • manages unlimited store locations
  • full-screen street view feature
  • extensive map settings to show all stores, specific location, or geo location
  • and much more

13. Ajax Translator Revolution WordPress Plugin

Ajax Translator Revolution WordPress Plugin

Ajax Translator Revolution WordPress Plugin is quite simply an automatic WordPress translation plugin that allows your visitors to view your website in their preferred language in a matter of seconds. 

The translation bar sits at the top of the website by default, but you can use the custom positioning settings to place it wherever you want. The plugin can translate as many as 91 languages and remembers a visitor’s selected language.

Other great features include:

  • over 80 settings for customisation available
  • display languages, flags with names, just names, or just flags
  • translate everything or selected sections of a web page
  • can exclude entire pages, posts, and categories
  • and much more

14. Cornerstone

Cornerstone

Cornerstone is a front-end WordPress page builder that allows you to see the changes you make to your site in real time as you build it. One of the great features of this plugin is Skeleton Mode, which allows you to see the underlying structure of your entire page without leaving the front-end interface.

Other great features include:

  • huge library of ready-made and customisable elements
  • text editing on the fly
  • compatible with any WordPress theme
  • and much more

15. Filetrip

FileTrip

The Filetrip plugin makes it easy to distribute files directly from your WordPress site as it allows your website visitors and clients to easily download any digital file from your website to Dropbox, Google Drive, or another cloud service. 

You can also program the plugin to automatically send copies of files uploaded by users to multiple destinations.

Other great features include:

  • automatic email notification for uploads and backups
  • ability to schedule full backup for your website
  • convert media files into transferable files
  • and much more

16. Ultimate Author Box

Ultimate Author Box

The Ultimate Author Box plugin is a great way to celebrate the authors who write for your blog. The plugin allows you to add an author box to each post to identify the author and provide additional information about them. 

You can add extra tabs to highlight the author’s other posts, social feeds, or other custom content like a contact form. The plugin comes with over 19 predesigned author box templates.

Other great features include:

  • ability to set role restrictions for author boxes
  • over 20 social media profiles
  • author summary in pop-up display
  • unlimited custom colour scheme customisation options
  • and much more

17. WP Contacts 

WP Contacts

Use WP Contacts to manage, log, track and share your contacts on any page of your site you choose. This responsive drag-and-drop plugin facilitates front-end login, and the contact database is highly customisable.

18. Custom Page Templates

Custom Page Templates

Custom Page Templates allows you to override your theme design and create a unique page template for your WordPress website. The plugin has an enormous amount of flexibility and gives you complete freedom to control precisely where and when your changes will be applied.

Other great features include:

  • over 30 shortcodes
  • ability to work with any plugin
  • support for popular plugins like Visual Composer, WooCommerce, etc.
  • and much more

19. Out-of-the-Box

Out-of-the-Box - Dropbox plugin for WordPress

Want to share photos, videos, or other files with your customers, clients, friends, and fans directly from your website without eating up your bandwidth? Say hello to Out-of-the-Box, a Dropbox integration plugin for WordPress that allows you to display your Dropbox files on your website. This responsive plugin is also multilingual ready.

Other great features include:

  • audio and video players
  • smart loading to save time and bandwidth
  • ability to search files by name or contents
  • and much more

20. Diamond Flipbook

Diamond Flipbook Plugin

The Diamond WordPress flipbook plugin allows you to create flipbooks from a variety of source files. Automatically convert PDFs, or upload multiple JPGs at the same time to create a flipbook. You can also manually add pages, or simply enter text directly into the WYSIWYG editor. Then, either add a shortcode for the generated flipbook to your website or post an image link that will launch a lightbox with one click. 

This WordPress gallery plugin also offers YouTube support. Fully responsive and with no Flash needed, this plugin works reliably on both mobile and desktop.

Add a Premium WordPress Plugin to Your Website Now!

Check out these thousands of premium WordPress plugins , as well as the best-selling, trending WordPress plugins, available on CodeCanyon that will vastly improve how your WordPress website functions and offer visitors an excellent user-experience. 

Best selling WordPress Utilities

Discover More Awesome WordPress Plugins

In the following articles and tutorials you will find more useful plugins for your WordPress website:

Learn More About WordPress Plugins

What makes WordPress an awesome platform is the wealth of unlimited resources available to help you succeed with your WordPress website. We are some selections from Envato Tuts+! 

Discover the best WordPress plugins to use for backup, security, caching, and SEO. Learn how to install and configure key WordPress plugins in this free course.

One of the great things about using WordPress is the vibrant plugin ecosystem. There are many thousands of WordPress plugins that promise to improve every aspect of your site. With the right plugins, your WordPress site will run more smoothly, get more visitors, and be less likely to face problems.

In this free course, Envato Tuts+ instructor Rachel McCollin will teach you how to install and configure free WordPress plugins for backup, security, caching, and SEO. You'll see how WordPress can be made far more powerful and secure by the addition of a few key plugins.

Learn How to Use WordPress

If you're just getting started, learn how to use WordPress in our complete guide or check out our free Beginner's Guide to WordPress course.



by Franc Lucas via Envato Tuts+ Code