Home >CMS Tutorial >WordPress >Coding Safe Themes with Built-In WordPress Functions

Coding Safe Themes with Built-In WordPress Functions

Jennifer Aniston
Jennifer AnistonOriginal
2025-02-10 11:53:09137browse

Coding Safe Themes with Built-In WordPress Functions

Core points

  • WordPress developers should treat all data as insecure until they prove safe; use WordPress functions wherever possible; and keep the code updated to ensure the security of the theme.
  • SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF) are common threats developers need to pay attention to when writing WordPress themes.
  • Verification, cleaning, and escaping are critical to WordPress theme security. Verify that the input data is in line with expectations; clean up filters or cleanses the data before storing it to the database; escapes ensures that the data is displayed safely.
  • WordPress provides many built-in validation, cleaning and escape functions. These functions include is_email(), username_exists(), term_exists(), validate_file(), sanitize_email(), sanitize_option(), sanitize_text_field(), sanitize_hex_color(), wp_kses_post(), esc_html(), esc_url(), esc_attr(), esc_textarea(),
  • ,
,

, Coding Safe Themes with Built-In WordPress Functions ,

,

and .

This article is part of a series of articles created in collaboration with SiteGround. Thank you for supporting the partners who made SitePoint possible.

Given that WordPress accounts for 27% of the network share, security is the top concern for anyone running a website on this popular open source platform. Although the security of WordPress core code is maintained by a dedicated development team, this is not the case with thousands of third-party plug-ins and themes that extend the capabilities of WordPress to do almost anything you want. Just one plug-in or theme with a vulnerability can pose a high risk to millions of websites.

Unless you use a reliable hosting provider (such as our partner SiteGround), which allows automatic updates to WordPress plugins and periodic security checks, the security of your website themes and plugins is entirely up to you, unless you use a reliable hosting provider (such as our partner SiteGround), which allows automatic updates to WordPress plugins and periodic security checks, the security of your website’s themes and plugins is entirely up to you. .

In this article, I will introduce some guidelines and WordPress functions that you can apply in WordPress theme development to ensure that your product puts user safety first when it is written.

Principles for developers with strong security awareness For dedicated WordPress plugins and theme developers, security is a factor they put first in writing every line of code. The overall approach to writing a safe WordPress theme includes focusing on the following general principles:
  • Treat all data as unsafe until it is proven to be secure.
  • Use WordPress functions wherever possible. Most WordPress APIs have built-in security mechanisms, which means using them can greatly reduce the risk of vulnerabilities in your code.
  • Keep your code up to date with the latest technologies and best practices.

Things to note

The most common threats you need to pay attention to are:

  • SQL Injection: An attacker injects malicious SQL code to control the website's database server.
  • Cross-site scripting (XSS): The attacker injects malicious JavaScript code into a web page.
  • Cross-site Request Forgery (CSRF): The attacker forces the user to perform unwanted actions on an authenticated website.

Cybersecurity has been developing, so it is crucial to be aware of the latest threats. When it comes to WordPress, Sucuri blogs are a great place to understand vulnerabilities and attacks.

Data verification, cleaning and escape

Before accepting any input data from any source (such as users, network services, APIs, etc.), you must check that it meets your expectations and is valid. This task is called Verification.

For example, if you collect emails from a user through a form on a website, your code needs to check if the user has entered some text input (e.g., not some numbers or nothing), and that input corresponds to a valid one Email address and then enter the data into the database.

You may think this kind of check is almost unnecessary in the subject. In fact, it is better to use plugins instead of themes to include forms. However, this is not exactly the case. For example, if you plan to add topic options through a customizer, you may need to perform some data validation on the user's input.

CleaningIncluding filtering or cleaning up data from users, network services, etc., which will be stored in the database soon. In this process, you can delete anything from the data that may cause harm or are not needed, such as JavaScript statements, special characters, and more.

EscapeIncluding ensuring the safe display of data, such as deleting special characters, encoded HTML characters, etc. The recommended approach here is to escape as late as possible, i.e., to escape before data is displayed on the screen.

You need to do a lot of cleanup and escape in your WordPress theme. In fact, for security reasons, the best way is to clean/escape all dynamic data, i.e. any data that is not hardcoded in the HTML source code.

WordPress verification function

You can perform basic verification using many convenient PHP functions.

For example, to check if the variable does not exist or its value is set to false, you can use empty().

But to make verification a breeze, WordPress provides these useful functions.

  • You can use the is_email( $email ) function to check if the data is a valid email address.

    Example:

    <code class="language-php"> if ( is_email( 'test@domain.com' ) ) {
       echo '有效的电子邮件地址。';
     }</code>
  • To check for a valid username, WordPress provides username_exists( $username ):

    <code class="language-php"> $username = 'testuser';
     if ( username_exists( $username ) ):
       echo "用户名已存在。";
     endif;</code>
  • To ensure that tags, categories, or other taxonomic terms exist, you can use term_exists( $term, $taxonomy = '', $parent = null ):

    <code class="language-php"> // 检查类别“cats”是否存在
     $term = term_exists('cats', 'category');
     if ($term !== 0 && $term !== null) {
       echo "“cats”类别存在。";
     }</code>
  • To make sure the file path is valid (but not if it exists), use validate_file( $file, $allowed_files ):

    <code class="language-php"> $path = 'uploads/2017/05/myfile.php';
     // 返回 0(有效路径)
     return validate_file( $path );</code>

WordPress Cleanup/Escape Function

Using the built-in WordPress function to clean and escape data is the fastest and safest way to do this, so make it your first choice.

The following are just some functions that I often use when developing WordPress themes.

  • sanitize_email( $email ) Delete all characters that are not allowed in a valid email address. Here is an example from a Codex entry:

    <code class="language-php"> $sanitized_email = sanitize_email(' admin@example.com!  ');
     // 将输出:admin@example.com
     echo $sanitized_email;</code>
  • sanitize_option( $option, $value ) Clean up option values ​​according to the nature of the options, such as values ​​from customizer inputs. Here is an example:

    <code class="language-php"> sanitize_option( 'admin_email', 'admin@test.com!' );</code>
  • sanitize_text_field( $str ) Clean up strings provided by users or databases, but you can use it to clean up any data you wish to be just plain text:

    <code class="language-php"> // 输出:标题
     echo sanitize_text_field('<h1>标题</h1>');</code>
  • sanitize_hex_color( $color ) and sanitize_hex_color_no_hash( $color ) work in the context of a WordPress customizer.

    Your themes are very convenient when they allow users to choose colors for various website elements.

    The first function verifies the hexadecimal color entry prefixed with the # symbol, while the second function handles color data without #.

    Example from WordPress.org code reference:

    <code class="language-php"> $wp_customize->add_setting( 'accent_color', array(
       'default' => '#f72525',
       'sanitize_callback' => 'sanitize_hex_color',
     ) );</code>
  • wp_kses_post( $data ) Filter content, leaving only allowed HTML tags. In a customizer context, this is very useful when your topic allows users to enter some text with HTML format:

    <code class="language-php"> function yourtheme_sanitize_html( $input ) {
       return wp_kses_post( force_balance_tags( $input ) );
     }</code>
  • esc_html( $text ) is a simple way to escape HTML blocks. For example, if you want to output some text inside an HTML tag to make sure that this text itself does not contain any HTML tags or other invalid characters, you can write:

    <code class="language-php"> <h2><?php echo esc_html( $title ); ?></h2></code>
  • esc_url( $url ) is useful when you want to check and clean URLs, including URLs in the href and src properties. For example:

    <code class="language-php"> <a href="https://www.php.cn/link/9e52112668804599bae71e241e4b4548'https://website.com'%20);%20?>">很棒的网站</a></code>
  • esc_attr( $text ) Anywhere for dynamic output HTML attributes for your theme:

    <code class="language-php"> <a href="https://www.php.cn/link/1649f854581e9c03bc2c4e06023c5b99'/'%20)%20);%20?>" rel="home"></a></code>
  • You can use esc_textarea( $text ) to escape the text that the user typed in the text area:

    <code class="language-php"> <textarea><?php echo esc_textarea( $text ); ?></textarea></code>

Resources

The following great resources are very helpful for me to really get to the point of writing security code in WordPress themes:

  • Theme security in WordPress.org Theme manual
  • Safe writing topic guide, Frank Klein
  • Clean, escape and validate data in WordPress, Narayan Prusty
  • WordPress Theme: XSS Vulnerabilities and Secure Coding Practices, Tony Perez
  • Writing secure plugins and themes in WordPress, Ben Lobaugh.

Or, you can learn how hosting providers can help with WordPress security in this handy comparison we have organized for you.

If you are interested in the theme development itself, you can learn to create a basic theme from scratch by learning in SitePoint's "Build Your First WordPress Theme" course: Loading the Player...

Conclusion

Security must be top of all WordPress developers. WordPress gives you a good start by providing a large number of ready-made functions that you can insert into your theme.

So, using WordPress to validate and clean/escap functions is the easiest way you can start writing a safe and reliable WordPress theme (users will learn to trust).

How much do you consider security when writing a WordPress theme or plugin? How do you solve security issues?

Click the comment box below to share!

FAQs about WordPress theme validation and escape functions

What are WordPress coding standards and why are they important?

The WordPress coding standard is a set of specific rules and guidelines formulated by WordPress to ensure consistency and quality of WordPress code. These standards are important because they make the code easier to read, understand, and maintain. They also help prevent common encoding errors and security vulnerabilities. For developers, following these standards is essential to ensure that their themes and plugins are compatible with WordPress and other themes and plugins.

How to safely edit WordPress code?

Editing WordPress code can be dangerous if it is not done properly. It is recommended to use subtopics when changing the theme code. This way, you can make changes without affecting the original theme. Also, be sure to back up your website before making any changes. Use the appropriate code editor instead of the WordPress editor to edit the code. Finally, test your changes on the staging site before applying them to your live site.

What is the difference between code and topic in qualitative analysis?

In qualitative analysis, code is used to label, compile, and organize your data, while topics are used to identify patterns and relationships in the data. Code is usually a single word or phrase that represents a specific piece of data. On the other hand, the topic is more broad, representing a larger concept or idea that emerges from the encoded data.

What is theme coding and how does it work in WordPress?

Theme coding is a method used in qualitative research to identify and analyze patterns or topics in data. In WordPress, theme coding can refer to the process of developing a theme with a specific design or function. This involves writing and organizing code in a way that reflects the intended design or function of the topic.

What are validation and escape functions in WordPress?

Verification and escape functions are security measures in WordPress. Verification is a process of checking the data entered by the user to ensure that it meets certain conditions before processing. Escape is a process of ensuring the output is secure by removing harmful data that can cause security vulnerabilities. These functions are critical to prevent security issues such as SQL injection and cross-site scripting (XSS).

Why is it important to verify and escape data in WordPress?

Verification and escape data are very important to keep your WordPress website safe. Without these processes, your website could be attacked and an attacker could inject harmful data into your website, resulting in potential data loss or unauthorized access to your website.

How to verify and escape data in WordPress?

WordPress provides some functions for validating and escaping data. For example, you can verify text input using the sanitize_text_field() function and escape HTML output using the esc_html() function. Be sure to use these functions when processing user input or outputting data to the browser.

What are the best practices for writing secure WordPress code?

Some best practices for writing secure WordPress code include following WordPress coding standards, validating and escaping all data, using nonce to verify the source of requests, checking user permissions before performing an action, and keeping WordPress, themes, and plugins up to date.

How to learn more about WordPress coding standards?

The WordPress Developer Manual is an excellent resource for learning WordPress coding standards. It provides detailed explanations and examples of the standards. There are also many online tutorials and courses that cover WordPress coding standards.

What are some common mistakes you should avoid when encoding WordPress?

Some common mistakes that should be avoided when encoding WordPress include not following WordPress encoding standards, not verifying or escaping data, hard-coded URLs, not using nonce for form submissions, and not keeping WordPress, themes, and plugins up to date.

The above is the detailed content of Coding Safe Themes with Built-In WordPress Functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn