4elements, Amsterdam, Holland

  1. Programming With Yii2: Validations

    Final product image
    What You'll Be Creating

    If you're asking, "what's Yii?" check out my earlier tutorial: Introduction to the Yii Framework, which reviews the benefits of Yii and includes an overview of what's new in Yii 2.0, released in October 2014.

    In this Programming With Yii2 series, I'm guiding readers in use of the newly upgraded Yii2 Framework for PHP. In this tutorial, I'm going to introduce you to Yii2's validators. Validators simplify the code needed to validate input, i.e. verify conformance or non-conformance of data input, typically from users via web forms.

    For these examples, we'll continue to leverage the Hello application codebase we've used in past tutorials. Use the GitHub links on this page to get the code.

    Just a reminder, I do participate in the comment threads below. I'm especially interested if you have additional ideas or want to suggest topics for future tutorials. You can also reach me @reifman on Twitter. 

    What Is a Validator?

    If you're a web developer, you likely know that user input can't be trusted. For example, users can use SQL injection techniques to try to run queries that change or expose passwords. Someone once leveraged SQL injection against my open source PHPList installation and managed to discover one of my passwords (PHPList stored these in plain text). More commonly, you just want to ensure that the data that users provide conforms to the types, forms and ranges of your application.

    Building validators in PHP by hand takes time. The Yii Framework provides a ton of baseline validation features so there's no need to build them from scratch. But, if you need some custom extensions, that's straightforward as well.

    Validations are yet another reason why I think it always makes sense to build applications on a web framework such as Yii rather than vanilla PHP.

    In earlier episodes, we've also talked a lot about Yii's code generator, Gii. One of the benefits of Gii is that it will write the appropriate validation rules for your models based on the SQL type definitions in the schema. This is a big time saver.

    What Validations Does Yii Support?

    Here's a list of the built in Yii validators and links to documentation:

    How Yii Validation Works

    Here's how Yii describes the flow of validation. Typically, you can use the default scenario and don't need to build your own. You'll generally need to rely on Gii to generate rules or write your own.

    When the validate() method is called, it goes through the following steps to perform validation:

    1. Determine which attributes should be validated by getting the attribute list from yii\base\Model::scenarios() using the current scenario. These attributes are called active attributes.
    2. Determine which validation rules should be used by getting the rule list from yii\base\Model::rules() using the current scenario. These rules are called active rules
    3. Use each active rule to validate each active attribute which is associated with the rule. The validation rules are evaluated in the order they are listed.

    According to the above validation steps, an attribute will be validated if and only if it is an active attribute declared in scenarios() and is associated with one or multiple active rules declared in rules().

    Example of Model Validation Rules

    Here's what a set of model validation rules may look like. I've taken these from the Meeting Planner application Place model:

    As we implement our own validation examples further below, you'll learn what each of the definitions above represent.

    Example of Displaying Errors

    There are a couple of ways to access the errors returned by validation. 

    Here's an example of getting the array of errors in the controller:

    And here's an example of leveraging Yii's errorSummary function within ActiveForms:

    Here's what it looks like:

    Using Yii errorSummary to display form errors

    Advanced Validation

    In later episodes, I'll also give examples of making use of advanced validation features:

    For now, let's begin walking through examples of the various kinds of built-in validators.

    Basic Field Validators

    Let's look at some of the basic field validators which are helpful to everyday form implementation.

    Preparing a Model Using Migrations and Gii

    As we've done in early episodes of this series, I'm going to create a migration:

    I'll create a Sample model to create some example schema and validations using Gii. Here's the migration code:

    Then, we'll run the migration:

    Then, we'll use Yii's code generator to build a model:

    Validation Yiis Gii Model Generator

    And then CRUD files:

    Validation Yiis Gii CRUD Generator

    Gii generates these sample validation rules:

    Now, let's use these to work with and walk through some of the basic validators.

    Required Validator

    The RequiredValidator ensures a value is present. You can see it in place above for rank, censorship and occurred.

    Visit the Sample Create form generated by Gii, e.g. http://localhost:8888/hello/sample/create. Yii's ActiveForm JavaScript client-validation will present an error message even when you tab away from one of these fields.

    Validators Required With JavaScript Client Side Validation

    Safe Validator

    The SafeValidator is not a true validator. It allows massive assignment of a posted web form to include an attribute. e.g. $model->attributes = $_POST['Comment']. Or, in the Gii created SampleController, you can see this code:

    Without the safe rule in the Sample model (or another rule), the occurred value would not be assigned to the model attributes. This reduces the likelihood of an additional attack vector without deliberate code.

    Default Value Validator

    The DefaultValueValidator is not a true validator. It sets default values for empty fields.

    Let's change the rule for occurred to set a default date value using the current date. We'll also remove the required validator to allow the default validator to fill the value.

    When we create a new Sample and leave the occurred field blank, you can see the resulting view includes the current date filled in by the default value validator.

    Validators Default Value

    Filters

    The FilterValidator is also not a true validator. It performs a transformation on a provided value. Most commonly, you might use this to trim whitespace off the ends of a string. 

    FilterValidators are defined with inline function callbacks such as this custom validation function:

    Since trim is a native PHP function, we can just declare our validation rule inline:

    If you submit a form with pre-pending or trailing spaces on the thought field, the FilterValidator will remove them.

    Now, let's look at some of the built-in type validators.

    The Type Validators

    Type validators ensure that user data conforms to specific types, often those specified in your database schema. Gii will generate these automatically.

    String and Number Validator

    The StringValidator ensures a value is a string. The NumberValidator ensures a value is numeric, e.g. integer or float. 

    Here are sample rule definitions:

    I'm also temporarily removing the required validation to see how string and number validations work independently.

    Here's what the validation error messages will look like:

    Validators Number and String

    Goodness as high fails because it's not a number, whereas rank as 27 passes. Censorship is blank (NULL) and fails the string validation.

    Boolean Validator

    The BooleanValidator ensures a value is true or false. You can define the values for true and false. The defaults are integer 0 or 1. This validator may be more useful when the field is used with a drop-down selector, e.g. Yes / No.

    Here's how I defined my rule for Boolean:

    Here's the boolean validator error message:

    Validators Boolean

    Date Validator

    The DateValidator ensures the value is a properly formatted date which can be customized with a format attribute. With Yii ActiveForm, this is currently a server side validation. Therefore, I also added back a required rule for the Occurred field.

    Here are my rule definitions with the Date validator for the Occurred field:

    Here's what it looks like when we submit the form:

    Validators Date

    What's Next?

    Watch for upcoming tutorials in my Programming With Yii2 series as I continue diving into different aspects of the framework. In the next two episodes, I'll guide you through the remaining validators and show you how to build advanced extensions to Yii's validation framework.

    You may also want to check out my Building Your Startup With PHP series, which is using Yii2's advanced template as I build a real world application.

    I welcome feature and topic requests. You can post them in the comments below, ping me @reifman on Twitter, or email me at my Lookahead Consulting website.

    If you'd like to know when the next Yii2 tutorial arrives, check my Tuts+ instructor page. It always includes all my articles immediately after they are published. 

    Related Links

     

    0 Comments

    Leave a comment › Posted in: Daily

    1. Closures in JavaScript

      What You'll Be Creating

      Understanding Closures

      To recap the concepts outlined in the video, note that:

      We covered the concept of variable scope. Specifically, we talked about the following two items:

      • Global Scope is a variable with global scope is accessible everywhere.
      • Local Scope is a variable with local scope is accessible only within a function body.

      In Summary

      Closure is what happens when we manipulate variable scope in our functions. We might do this either to make variable contents accessible where they would not otherwise be, or to protect a variable from unwanted access.

       

      0 Comments

      Leave a comment › Posted in: Daily

    1. Accessibility, Part 4: Operable

      Broadly speaking this is the principle that your website must be able to be safely navigated for all users. This includes the guideline that your entire website should be accessible by using the keyboard alone. Furthermore, the way your website responds to user input (by keyboard or otherwise) should be predictable, clear and safe. 

      This last point refers chiefly to ensuring that any potentially seizure-inducing feature of your site is disabled by default, and users warned before enabling it. This principle also provides guidelines on providing 'enough time' for users to complete tasks, but we don't cover it here.

      Keyboard Accessibility (2.1)

      Being able to navigate and use your site with only a keyboard is one of the most important aspects of accessibility. Blind users will rely on keyboards almost exclusively, and those with motor disabilities may have difficulty controlling a mouse, and so also rely on keyboard access. Some individuals may have little or no use of their hands, and rely on larger keyboards, mouth sticks, head wands, single-switch, or Sip 'n' Puff. 

      You can find descriptions of these devices on the WebAIM website, but they all essentially channel user input into keyboard strokes. If your website isn't accessible by keyboards, then all users relying on these devices will be unable to use your site.

      Fortunately, making your theme or plugin keyboard accessible is relatively simple. Here are some key points:

      Ensure Your Entire Menu Can Be Accessed by Keyboard

      A lot of themes rely on hovering over a menu item to reveal any sub-menus. This is fine, but generally the sub-menu will not appear if the parent menu item has focus (rather than hover). If you duplicate any relevant rules for :hover and apply them to :focus also, this will get you halfway there: the sub-menu items will appear as the user tabs across the menu. However, once the user tabs down to the sub-menu, the parent menu loses focus and the sub-menu disappears. This can be corrected using JavaScript. Details on this and how to provide a non-JavaScript fallback will be covered in the next article of this series.

      Don't "Trap" Users

      You do not need to do anything to make 'native' form inputs (select, input, radio, etc.) keyboard accessible. However, should any aspect of your page (including form fields) gain focus, it must be possible to move away from it using only a keyboard—otherwise the user is effectively trapped. This is normally default behaviour, so you should just avoid overriding it.

      Make Navigating Easy and Clear (2.4)

      This guideline has two types of recommendations: make finding where the user currently is obvious, and make getting to where they want to go easier. 

      Part of following the recommendations in doing this involves something a lot of themes already do: Have a consistent navigation menu across pages, highlight the current page, and allow users to quickly determine where they are on the site (e.g. with breadcrumbs).

      Styling :Focus Properly

      A key part of being able to use a keyboard to navigate around a web page is being able to see precisely what has currently got focus. The element which currently has focus should be visibly different, and distinguishable from the rest of the page. For this reason you should avoid outline:none; unless you are going to provide alternative styling:

      Focus Order and Tabindex

      Another important part of keyboard accessibility is that tabbing behaves predictably and in a natural way. For instance, if the focus is currently a form field, I would expect that the next tab should take me to the next field in that form. If tabbing causes the focus to jump up and down the page erratically, then this will frustrate and disorientate the user.

      Avoid using tabindex: The tabindex attribute allows you to alter the order in which elements are reached by tabbing. However, if you followed the advice in article 2 of this series regarding the DOM structure, the tab order should reflect the "natural" order of the page. While tabindex has its uses, these are rare, and its use to 'patch' poor site structure can create further issues. The best method is to avoid using tabindex, and instead have your theme produce a logical DOM structure, with CSS used to alter the visual presentation.

      Avoid "Read More" or "Continue Reading"

      Screen reader users will often jump between links, skipping the text between, and at each link the screen reader will read out "link [link text]". As such, it's incredibly unhelpful to such users if they repeatedly hear "link read more", "link click here" or "link continue reading". Adding context to the link in this case simply involves providing the post's title. So instead of "Continue reading", we have "Continue reading [post title]".

      To do this in a WordPress theme, we simply need to hook onto the excerpt_more filter and append our "continue reading" link:

      This gives the "read more" link proper context. However, there are a couple of improvements that can be made.

      Firstly, the addition of the article title will typically ruin the aesthetics of the theme and, for sighted users, will be redundant, as the position of the "read more" link in relation to the article title and excerpt will make the context obvious. To get around these problems, we can "hide" the article title, but in a way that screen readers will still read them.

      This means we cannot use display:none or visibility:hidden; as screen-readers understand these properties and will ignore the content. Instead we can position the text off-screen or use the clip property:

      There are plenty of different examples of "screen reader classes"; this particular one is taken from Bootstrap 3. Next, add the appropriate class to the article title, specifically replacing line 5 above with:

      Secondly, while this would give users an indication as to where that link was pointing, they would still have to listen through "link continue reading..." before reaching the post title. Ideally you should put redundant information at the end of the link text, or omit it from the anchor tag entirely, to reduce the time it takes to identify a link. 

      Another benefit to screen reader users of not preceding linked text with redundant information is that screen readers will often generate a list of links on a page. If a lot of your links start with the same text, this can make finding a desired link harder—particularly if the link for your contact page is under "H" because it reads "How to contact us".

      Use the <title> Tag Properly

      The <title> tag should be used to identify the current location of the user. This is read out by screen readers, and appears in search results and on the screen window and browser tab. To make it easy for users to identify where they are (or what the search has found), this title tag should contain the page's title and the website name. Ideally the website name should come last, so that people using screen readers do not have to listen to the name of your site on every page load before they hear the page title.

      The title tag can be added to a theme with:

      To add the site title:

      Skip to Content

      Typically websites will have a common header and navigation menu which, with the exception of highlighting the user's current position, will remain exactly the same. Having to tab through all these links, or listen to a screen-reader repeat them on every page load, is tedious and frustrating. Those of us with good (enough) eyesight and motor skills can immediately jump down to the content—and we can make this just as easy for those that don't.

      If you're in your WordPress admin, and press Tab after the page loads, you'll notice a link that says Skip to main content appears on the top-left (If you press tab again, a Skip to toolbar link will appear). This link sits at the very top of the page, so that it is the first link that receives focus when tabbing, and the first link of the website read out by a screen-reader. Following that link jumps the user straight to the main content, skipping out all the unnecessary links and site logos in between.

      Creating a skip to content is a great way of making your website easier to navigate, and it's incredibly easy, requiring only a minor bit of HTML and some CSS. 

      First the HTML. The link should go at the very top of your page, immediately under the <body> tag. In most themes this will be the header.php file:

      The only things to note here are:

      1. The href value, in this case 'main'. This must match the ID of the element that contains the page's content.
      2. The class of the link, which we'll use for styling.

      Regarding (1), your loop will then look something like:

      and your page templates might look something like:

      Now all that remains is to add some styling to the link. 

      First, we want the link hidden but not hidden to screen-readers, so we'll position the link off-screen rather than using display:none (in which case screen-readers ignore it). 

      Secondly, when it gains focus we want to make the link obvious, so it is clear that a previously hidden link is now visible and has focus.

      Make Navigating Your Site Safe (2.3)

      Lastly, be aware that some people are susceptible to photosensitive epileptic seizures. This can be caused by flickering or flashing effects. Last December Jeff Chandler removed a "snow" effect from WP Tavern after a visitor warned him that it could trigger a seizure.

      This isn't limited to seizures—it can trigger migraines or panic attacks in some individuals. Nor is it limited to snow effects—a video, carousel or audio file autoplaying can also trigger these. 

      Although this is largely an editor's decision and as developers it is not our job to prevent auto-play, we can at least discourage it, by disabling it by default. Jeff mentions in his article that he couldn't find a plugin providing the "snow" effect which visitors themselves could play.

       

      0 Comments

      Leave a comment › Posted in: Daily

    1. Bootstrap3- Innovative CSS Features You’d Love To Know About

      Author Bio :
      Sophia Phillips has been working as a professional in custom WordPress development services company and loves sharing information about leveraging multiple benefits of WordPress in the best possible manner. Currently, she has an impressive count of WordPress-related articles under her name.



      Having being released for web developers in August 2011 on GitHub, Bootstrap has serves as a remarkable free front-end framework for creating brilliant responsive designs. Loaded with HTML and CSS based design templates for forms, typography, tables, modals, buttons etc. Bootstrap can be used by anyone with the basic knowledge of HTML and CSS. If you’ve been an avid fan of Bootstrap, then you might be well familiar with the release of its version 3. While a lot has already been spoken about the mobile-first styles which form a crucial component of the core framework, there are many other CSS features which must not be missed by a developer. This is exactly what my post is all about. Here, I’ve jotted down some of the eye-catchy CSS features that have been incorporated into this latest Bootstrap release named version 3. So, let’s get to know more about these CSS features.


      1. Images are fully responsive by default
      Unlike Bootstrap2 where images weren’t responsive by default, in Bootstrap3, images are fully responsive via the perfect use of tag. Additionally, the users are also rendered the flexibility of extending the responsiveness of images by addition of img-responsive to any of the tags. Doing this would ensure that the height and width of image stays in proportion to each other even while the image is being scaled. Moreover, the name of img-polaroid class(the one which is being used for creating thumbnails) is being changed to img-thumbnail. This is being done for ensuring that the name of this class is in syc with the other terms used throughout the library. A key point to be noted here is that the img-rounded and img-circle classes are still operational for Bootstrap3, thereby rendering a rounded-rectangle and circular thumbnail effect to the images.


      2. Changes in list elements
      While the list layout is exactly similar to what it was in Bootstrap2, some changes have been introduced in list elements. Just like the normal list elements which were made up of

      < ul>, < dl> and < ol>

      elements, the same concept is still applicable in case of Bootstrap3. Also, the list-unstyled and list-inline along with dl-horizontal classes available for definition lists are also similar to what they were in the version 2 of Bootstrap.


      3. Changes to image’s visibility
      In Bootstrap2, under typography classes, a set of color classes was introduced. This was primarily used for setting the color of text element to the same colors as used in other elements available within the framework. With Bootstrap3, this concept takes a new step with the introduction of a scenario wherein contextual backgrounds would also use the colors for the text element. One of the greatest advantages of this add-on feature is that if you opt for using the contextual color classes on anchor tags and somewhere else where there’s a use of hover-over set by default, then the colors would automatically dim slightly for showcasing that they have been hovered over by the viewer. When it comes to naming the color-based classes, the classes available here include: text-muted, text-primary, text-success, text-warning, text-info and text-danger for span, paragraph and a range of other inline or block-based text elements. Additionally, for background colors, class names include bg-primary, bg-success, bg-warning, bg-info and bg-danger.


      4. Table changes
      While the tables are still styled the same way as they were in Bootstrap2, table striping now utilizes :nth-child pseudo selector. That means, the table in Bootstrap3 no longer works in IE8 or an earlier browser version. Quite similar to Bootstrap2, even in Bootstrap3, tables must be constructed with the help of a full range of

      < thead>, < table> and < tbody>

      HTML elements. Have a look at this example:

      < table class="table">

      < thead>

      < tr>

      < th>

      Heading 1

      < th>

      Heading 2

      < th>

      Heading 3

      < /tr>

      < /thead>

      < tbody>

      < tr>

      < td>

      ABC

      < td>

      PQR

      < td>

      XYZ

      < /tr>

      < tr>

      < td>

      ABC

      < td>

      PQR

      < td>

      XYZ

      < /tr>

      < /tbody>

      < /table>

      The output achieved from the above markup is shown below:




      In addition to above, there has been two latest additions to classes that are utilized for supporting tables. Firstly, there is an innovative responsive class which considers the size of the grid system and provides a realigned table or vertical scroll bars so as to fit the varied size displays. Secondly, the classes have been enriched with an ability to use the prior mentioned color row classes on individual cells instead of just the rows, as was prevalent in case of Bootstrap2.


      5. Changes in typography
      While the multiple classes which form Bootstrap 3’s typography section haven’t undergone much of a change like the other elements, the added flexibility of using

      < small>

      in line with any of the header element has eliminated any extra markup. That means, you just have to work on the markup only when you want the block heading to be underlined using a separate paragraph margin. 

      Conclusion
      After having a good drive through these absolutely stunning CSS features available in Bootstrap3, I’m quite sure you too would have decided to leverage the same in your upcoming web development project.

       

      0 Comments

      Leave a comment › Posted in: Daily

    1. A Walkthrough on Conditional Tags in WordPress: 14 to 26

      In this series, we're going through one of the fundamental features of WordPress: Conditional Tags. In this third part, we'll continue introducing and reviewing the Conditional Tags. Be sure to check out the previous parts if you haven't yet.

      Let's begin!

      14. Checking Whether We're on the Front Page: is_front_page()

      In WordPress, the "front page" can be set to a static WordPress page or the list of the latest blog posts (Settings > Reading). Either way, the Conditional Tag is_front_page() returns TRUE when the front page is being displayed.

      Accepted Parameters

      This Conditional Tag doesn't accept any parameters.

      15. Checking Whether the Post Has a Thumbnail: has_post_thumbnail()

      "Featured images" are one of the key parts of the New Post/Page screen. The Conditional Tag has_post_thumbnail() determines whether there's an assigned featured image to the given post or not.

      Accepted Parameters

      This Conditional Tag has only one parameter:

      • $post_id (integer, optional): The post ID. (Default: Current post ID)

      Usage Example for has_post_thumbnail()

      Let's say you're developing a theme and in it, every single blog post needs to have a "featured image", so you want to display a "default image" if no featured image is set. Here's what you do:

      16. Checking Whether the Theme Is Using the "Comments Popup": is_comments_popup()

      You shouldn't judge anyone who uses a 10-year-old theme—or loves retro. If you're developing a plugin, you need to take everything into account, and that includes themes that use the comments popup window. To determine this, you can use the Conditional Tag is_comments_popup().

      Accepted Parameters

      This Conditional Tag doesn't accept any parameters.

      17. Checking Whether the Page Is a 404 Error Page: is_404()

      The "Not Found" error pages are usually the ones we hate to see in our websites, and thus we don't really care how they look. But when you use these error pages correctly, you can turn them into useful pages that inform your users or help them navigate. The Conditional Tag is_404() helps us determine whether a 404 error is being displayed to the user.

      Accepted Parameters

      This Conditional Tag doesn't accept any parameters.

      Usage Example for is_404()

      Let's say you're developing a plugin that logs broken internal links, and you want your function to run each time a 404 error page is viewed. Here's what you do:

      18. Checking Whether the Given Taxonomy Exists: taxonomy_exists()

      If you ever need to check whether a custom taxonomy is already registered, you can use the taxonomy_exists() Conditional Tag to make your code determine it.

      Accepted Parameters

      This Conditional Tag has only one parameter:

      • $taxonomy (string, required): Taxonomy's name. (Default: None)

      19. Checking Whether the Page Is the "Search Results" Page: is_search()

      While being a little underrated, "Search Results" pages are an important part of WordPress websites. And if you're developing a plugin or a theme, you can detect these pages with the help of the is_search() Conditional Tag.

      Accepted Parameters

      This Conditional Tag doesn't accept any parameters.

      Usage Example for is_search()

      Let's say you want to include a link for a Google search with the same terms. Here's what you do:

      20. Checking Whether the Page Is a "Tag Archives" Page: is_tag()

      Want to treat tag archives differently? The Conditional Tag is_tag() can help you with that. Want to treat specific tags differently? Just pass a tag name, slug or ID (or an array of those) as the parameter!

      Accepted Parameters

      This Conditional Tag has only one parameter:

      • $tag (array/string, optional): Tag's ID, name, slug or an array of those. (Default: None)

      21. Checking Whether the Post Has a Custom Excerpt: has_excerpt()

      There are two kinds of "excerpts" in WordPress posts: If you want to write one yourself, it's called a "custom excerpt", and if you don't, an "automatic excerpt" is generated (by default, it's the first 55 words of the post). The has_excerpt() Conditional Tag checks whether the user set a custom excerpt for the given post.

      Accepted Parameters

      This Conditional Tag has only one parameter:

      • $post_id (integer, optional): The post ID. (Default: Current post ID)

      Usage Example for has_excerpt()

      Let's say you're making a theme and you want to display custom excerpts in the homepage, but you don't want to display automatic excerpts. Here's what you do:

      22. Checking Whether It's the Main Query: is_main_query()

      WordPress uses the WP_Query class to list posts—whether it be just a list of post titles or the index of full posts in an archive page. A number of functions use the WP_Query class, and is_main_query() is one of them. This Conditional Tag detects whether the query is not a "secondary query", but the "main query".

      Accepted Parameters

      This Conditional Tag doesn't accept any parameters.

      23. Checking Whether the Post Has the Given Tag: has_tag()

      Sometimes, you may need to check if a post has some tag to make the post (or posts) act differently than others. To achieve this, you can use has_tag() to check whether a post is tagged with the tag you specify. (Note: It allows you to specify more than one tag to look for.)

      Accepted Parameters

      This Conditional Tag has two parameters:

      • $tag (array/string, optional): Tag's name, ID, slug, or an array of those. (Default: None)
      • $post (object, optional): Post to check. (Default: Current post)

      Usage Example for has_tag()

      Let's say you have "badges" for your blog posts (like "NEW", "FEATURED" and "OBSOLETE") that are going to be activated by using corresponding tags, and you want to echo the images inside posts. Here's what you do:

      24. Checking Whether the Blog Is Installed (?): is_blog_installed()

      This particular Conditional Tag returns TRUE if WordPress is installed. I'm including this Conditional Tag just for reference, because technically it can't be useful for plugin or theme developers—it could be used in some external WordPress tool, maybe.

      Accepted Parameters

      This Conditional Tag doesn't accept any parameters.

      25. Checking Whether the User Is a "Super Admin": is_super_admin()

      In a Multisite network, there is a "super admin" which can administer all the sites. To detect if the user is a "super admin" (or a regular admin in regular WordPress installations), you can use the is_super_admin() Conditional Tag.

      Accepted Parameters

      This Conditional Tag has only one parameter:

      • $user_id (integer, optional): User's ID. (Default: Current user)

      Usage Example for is_super_admin()

      Let's say you don't like the "Howdy" greeting and you want to change it, but your users like it and want it to stay. In that case, you need a solution to apply to you only. Here's what you do:

      26. Checking Whether the Page Is a "Page" Page: is_page()

      In WordPress, "pages" are one of the five built-in post types along with posts, revisions, attachments and navigation menus. And if you want to detect a certain page (or any page in general), you can use the Conditional Tag is_page().

      Accepted Parameters

      This Conditional Tag has only one parameter:

      • $page (array/string, optional): Page ID, title, slug or an array of those. (Default: None)

      Conclusion

      In this part, we reviewed another batch of the 65 documented Conditional Tags in WordPress. In the next parts, we're going to go through the remaining 39. If you have any questions or comments, shoot them below—and if you liked this article, don't forget to share it!

      See you in the next part!

       

      0 Comments

      Leave a comment › Posted in: Daily

  • Page 1 of 65 pages  1 2 3 >  Last ›
  • Browse the Blog

    Syndicate

    governing-bruise