Reading list Switch to dark mode

    How to configure Basic PHPCS, WPCS & WCCS for WooCommerce projects

    Updated 17 April 2024

    If you’re developing a WooCommerce project, it’s important to ensure that your code follows coding standards and best practices.

    This not only helps you maintain a consistent codebase, but it also ensures that your code is secure, maintainable, and easy to understand.

    To achieve this, you can use PHP_CodeSniffer (PHPCS) along with the WordPress Coding Standard (WPCS) and WooCommerce Code Standards (WCCS) to ensure that your code adheres to the recommended coding standards.

    In this blog, we will guide you through the process of configuring PHPCS, WPCS, and WCCS for your WooCommerce project and it would also be helpful in case of WooCommerce Development Services.

    If you require expert assistance or want to develop custom unique functionality, hire WooCommerce Developers for your project.

    Searching for an experienced
    Woocommerce Company ?
    Find out More

    Step 1: Install PHPCS

    The first step is to install PHPCS globally on your system using Composer. This will enable you to use PHPCS from the command line. You can do this by running the following command:

    composer global require "squizlabs/php_codesniffer=*"

    Step 2 : Installing WordPress Coding Standards as a dependency

    Standards can be installed with the Composer dependency manager:

    composer create-project wp-coding-standards/wpcs --no-dev

    Running this command will:

    1. Install WordPress standards into wpcs directory.
    2. Install PHP_CodeSniffer.
    3. Register WordPress standards in PHP_CodeSniffer configuration.
    4. Make phpcs command available from wpcs/vendor/bin.

    For the convenience of using phpcs as a global command, you may want to add the path to the wpcs/vendor/bin directory to a PATH environment variable for your operating system

    Step 3: Set up the Coding Standards

    Once you have installed PHPCS, WPCS, and WCCS, you need to set up the WooCommerce and WordPress Coding Standards (WPCS) as a coding standard for PHPCS. You can do this by running the following command:

    phpcs --config-set installed_paths /path/to/wp-coding-standards/wpcs,/path/to/woocommerce/woocommerce-coding-standards

    This command sets up the WPCS as a coding standard for PHPCS.

    Step 4: Create a PHPCS Configuration File

    The next step is to create a PHPCS configuration file (phpcs.xml or phpcs.xml.dist) in the root of your WooCommerce project. This configuration file sets up the WooCommerce and WordPress coding standards as rules for your project.

    Here is an example configuration file that uses the WooCommerce and WordPress Coding Standards:

    <?xml version="1.0"?>
    <ruleset name="WooCommerce Project">
        <description>Custom coding standard for WooCommerce project</description>
        <arg name="basepath" value="."/>
        <file>.</file>
        <rule ref="WordPress-WP-Theme"/>
        <rule ref="WooCommerce"/>
    </ruleset>

    The command “phpcs -i” is used to check the installed coding standards in PHP CodeSniffer. PHP CodeSniffer is a tool that helps to enforce coding standards in PHP code.

    phpcs -i

    When you run “phpcs -i” in the command line, it will display a list of installed coding standards available for use. Each coding standard represents a set of rules and guidelines for writing PHP code.

    Here’s an example output of the “phpcs -i” command:

    The installed coding standards are MyStandard, PSR1, PSR2, Squiz, Zend.

    This output indicates that you have several coding standards installed, including “MyStandard,” “PSR1,” “PSR2,” “Squiz,” and “Zend.” These coding standards can be used to check the PHP code against their respective rulesets.

    Note that the actual output may vary depending on the specific installation and configuration of PHP CodeSniffer on your system.

    Here is the extension you can use in your code editor for phpcs

    phpcs

    Step 6: Integrate PHPCS with Your Text Editor or IDE

    Finally, you can integrate PHPCS with your text editor or IDE to get real-time feedback on coding standards violations as you write code. Most modern text editors and IDEs have plugins or extensions that can be used to integrate PHPCS.

    In conclusion, using PHPCS along with the WooCommerce and WordPress Coding Standards (WPCS) can help you maintain a consistent codebase, ensure that your code is secure, maintainable, and easy to understand.

    By following the steps outlined in this blog, you can easily configure PHPCS, WPCS, and WCCS for your WooCommerce project

    How to set path in VS Studio Code Editor manually

    1. Open VSCode and navigate to the settings by clicking on the gear icon in the bottom left corner and selecting “Settings” from the dropdown menu. Alternatively, you can use the keyboard shortcut Ctrl + , (control + comma) (Cmd + , on macOS) to open the settings directly.
    settingjson-1

    2. In the settings panel, click on the “Extensions” icon on the left sidebar and search for “PHP” in the search bar. Select the “PHP” extension by Microsoft from the search results.

    3. Scroll down until you find the “PHP › Executable Path” setting. Click on the “Edit in settings.json” link to open the JSON configuration file for the PHP extension.

    visibleeditjson

    4. In the settings.json file, you can specify the path to the PHP CodeSniffer executable (phpcs). Add the following line to the JSON object:

    "php.executablePath": "/path/to/phpcs"

    5. Replace /path/to/phpcs with the actual path to the phpcs executable on your system. Make sure to provide the correct path according to your operating system (Windows, macOS, or Linux).

    Save the settings.json file, and the path to PHP CodeSniffer should now be configured in VSCode.

    How to generate PHPCS xml file using command terminal

    phpcs --standard= { path of the core phpcs.xml file containing ruleset } --error-severity=1 --warning-severity=2 --report-source --report-xml={path where you want to generate file containing the errors and warning phpcs xml } --ignore-annotations --extensions=php,html {path of the plugin/module you want to be checked}
    1. This command tells PHPCS to use the “xml” coding standard and redirects the output to a file named “phpcs.xml”. You can replace “xml” with the coding standard of your choice.
    2. After executing the command, PHPCS will scan the PHP files in the current directory and generate an XML report based on the specified coding standard. The report will be saving in the “phpcs.xml” or the name provided for that file.

    You can then open the generated XML file using a text editor or XML viewer to review the PHPCS results and coding standards violations.

    Note: Make sure that you have appropriate permissions in the directory where you want to create the XML file.

    Types of warning and errors detected through phpcs :

    PHPCS (PHP CodeSniffer) identifies various types of errors and warnings in PHP code based on the defined coding standards. Here are some common error and warning types reported by PHPCS:

    1. Errors:
      • Coding Standards Violations: PHPCS checks for violations of coding standards, such as indentation, naming conventions, and spacing rules.
      • Syntax Errors: PHPCS can detect syntax errors in PHP code, such as missing semicolons, mismatched parentheses, or invalid statements.
      • Undefined Variables: PHPCS will stop identifying the use of variables not defined within the code.
      • Undefined Functions/Methods: PHPCS can detect calls to functions or methods that are not defined or not within the codebase.
      • Deprecated Functions/Methods: PHPCS can identify the usage of deprecated functions or methods.
    2. Warnings:
      • Potential Bugs: PHPCS can flag potential bugs in the code, such as unused variables or unreachable code blocks.
      • Deprecated Features: PHPCS can warn about the usage of deprecated features in PHP versions.
      • Code Quality Issues: PHPCS can detect code quality issues, such as long lines of code, excessive nesting, or complex expressions.
      • Performance Considerations: PHPCS can provide warnings about code constructs that may have performance implications, such as inefficient loops or excessive function calls.

    Different coding standards may have different rules and guidelines, resulting in varying error and warning messages.

    We are listing the set of errors of PHPCS and their solution

    1)Yoda Condition

    Yoda condition, also known as “Yoda notation,” is a programming style where the order of operands in a conditional statement is reversed to check for type and value in an equality conditional expression

    In a typical conditional statement, the order of operands is as follows:

    if ($variable == 5) {
        // Code block
    }

    In Yoda condition style, reversing the order of operands, like this:

    if (5 === $variable) {
        // Code block
    }

    The notable difference is that the constant value or literal is placed on the left side of the comparison operator (e.g., ==), while the variable being tested is on the right side.

    The main benefit of using Yoda condition is to prevent accidental assignment instead of comparison and also checks the type . In some programming languages, a single equals sign (=) is used for assignment, while a double equals sign (==) or triple equals sign (===) is used for comparison and type check.

    Accidentally using a single equals sign in a conditional statement can lead to a logic error, as it assigns a value instead of performing a comparison.

    2)Nonce Verification

    <error line="225" column="39" source="WordPress.Security.NonceVerification.Missing" severity="5" fixable="0">Processing form data without nonce verification.</error>

    The PHPCS (PHP CodeSniffer) issue you mentioned, “Processing form data without nonce verification,” refers to a potential security vulnerability in PHP code that handles form submissions.

    Nonce verification is a security measure commonly used to protect against Cross-Site Request Forgery (CSRF) attacks.

    To solve the issue of processing form data without nonce verification in WordPress, you can follow these steps:

    1. Generate and Include Nonce in Forms:
      • When rendering your HTML forms in WordPress, you can make use of the wp_nonce_field() function to generate and include a nonce field in the form.
      • Use the wp_create_nonce() function to generate a secure nonce value.
    <?php wp_nonce_field( 'my_form_action', 'my_form_nonce' ); ?>

    2 ) Validate Nonce on Form Submission:

    • You can use the wp_verify_nonce() function to check if the nonce is valid.
    • If the nonce is valid, proceed with processing the form data or it rejects the form.
    if ( isset( $_POST['my_form_nonce'] ) && wp_verify_nonce( $_POST['my_form_nonce'], 'my_form_action' ) ) {
        // Nonce verification passed, process the form data
        // ...
    } else {
        // Nonce verification failed, reject the form submission
        // ...
    }

    WordPress provides built-in functions that handle the creation and verification of nonces, making it easier to implement nonce verification in your WordPress forms.

    Make sure to replace 'my_form_action' with a unique identifier for your form. This identifier helps ensure that the nonce is specific to your form and cannot be reused by other forms.

    By incorporating these steps into your WordPress form processing code, you can ensure that form submissions are validated using nonces, providing protection against CSRF attacks.

    Brief introduction of elements regarding phpcs xml file

    The xml file is written in XML (eXtensible Markup Language) format and contains various configuration settings for PHPCS. Here are some of the common elements and their purposes:

    • <ruleset>: This is the root element of the .xml file and contains all other elements. It defines the coding standards and rules to be applied.
    • <rule>: This element represents an individual coding rule or standard. It can have attributes such as ref, which specifies the rule code or identifier, and severity, which defines the level of importance for that rule (e.g., error, warning, or notice).
    • <exclude-pattern>: This element allows you to exclude specific file patterns or directories from being analyzed by PHPCS. It can be useful if you want to skip certain files or directories that are not relevant to the coding standards.
    • <arg>: This element is used to provide arguments or options for PHPCS. It can be used to customize the behavior of specific rules or to pass additional configuration parameters to PHPCS.
    • <config>: This element is used to set global configuration options for PHPCS. It can include settings like the PHP version, tab width, and line ending preferences.
    • <file>: This element is currently allowing you to define specific file or directory paths to be checked by PHPCS. It can be useful if you want to analyze only a subset of files or directories

    <!-- Exclude paths -->
    	<exclude-pattern>tests/</exclude-pattern>
    	<exclude-pattern>woo-includes/woo-functions.php</exclude-pattern>
    	<exclude-pattern>woo-includes/class-wc-dependencies.php</exclude-pattern>
    	<exclude-pattern>*/node_modules/*</exclude-pattern>
    	<exclude-pattern>*/vendor/*</exclude-pattern>

    PHPCS won’t Analyze these directory or files you have mentioned here in these tags like node_modules and vendor ! isn’t it interesting ?

    <!-- Configs -->
    	<config name="minimum_supported_wp_version" value="5.0" />
    	<config name="testVersion" value="6.2" />
    	<config name="text_domain" value="wkpos-addon"/>

    Now, you can see in above code , we have used config tag for setting PHPCS global configuration options for text domain , wp_version and php version .Now, these options will be setting globally for PHPCS .

    <!-- WordPress Rules -->
    	<rule ref="WordPress-Core"/>
    	<rule ref="WordPress.CodeAnalysis.EmptyStatement"/>
    
    	<rule ref="WordPress-Docs"/>
    	<rule ref="WordPress-Extra">
    		<exclude name="WordPress.WP.TimezoneChange.timezone_change_date_default_timezone_set"/>
    		<exclude name="Squiz.Commenting.FileComment.SpacingAfterComment" />
    	</rule>
    
    	<rule ref="WordPressVIPMinimum"/>
    	<rule ref="WordPress-VIP-Go"/>
    	<rule ref="WordPress.WP.I18n"/>
    
    	<!-- WooCommerce Rules -->
    	<rule ref="WooCommerce"/>
    	<rule ref="WooCommerce-Core"/>
    
    	<!-- Covers rule: Use single and double quotes when appropriate.
    		 If you're not evaluating anything in the string, use single quotes. -->
    	<rule ref="Squiz.Strings.DoubleQuoteUsage.NotRequired"/>

    You can see above we have defined certain set of rule that may be related to individual coding rule or standard

    Conclusion

    This Standardization improves code collaboration, readability, and maintainability. By automatically identifying violations, PHPCS saves developers time and effort in manual code reviews in WooCommerce plugins, leading to increased productivity and reduced bugs.

    For the purpose ,PHPCS offers extensibility through the creation of custom rules and sniffs.

    This allows developers to tailor the tool to their specific project requirements and coding conventions, compared enhancing code quality and ensuring adherence to project-specific guidelines.

    PHPCS is a robust and flexible tool that promotes code quality, consistency, and adherence to coding standards in PHP development.

    By integrating it into the development process, developers can enhance collaboration, reduce technical debt, and produce cleaner, more maintainable code.

    Support

    For any technical assistance kindly raise a ticket or reach us by email at [email protected]. Thanks for Your Time! Have a Good Day!

    Also, discover various solutions to add more features and enhance your online store by visiting the WooCommerce plugins.

    Thanks for Your Time! Have a Good Day! 🙂

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home