Useful code inserts (snippets) for WordPress. PHP code in WordPress - best practices Conflict-free connection of scripts and styles in WordPress

To ensure that WordPress code is designed in the same style everywhere and is easy to read in the core, plugins and themes, it is recommended to follow the coding standards adopted by WordPress developers. These standards are very similar to the PEAR standard, but there are significant differences. I recommend that you familiarize yourself with them and, if possible, follow them when creating plugins or themes.

In addition to standards for writing PHP code itself, there are also standards for documenting code - these are comments on functions and hooks: PHP Documentation Standards (English)

Single and double quotes

If there are no variables in the string, use single quotes, otherwise double quotes. There is no need to escape quotes in a string, and if they are present, it is recommended to alternate them:

Echo "Link name"; echo "$linkname";

The second line in this example does not clear the output variables, which must be done for security reasons. Therefore, for such a write, the variables must be cleared in advance. In general, such a recording can be considered unacceptable! See the tutorial section on safe output.

Indentations

Indentation should always show the logical structure of the code. Use tabs (Tab key) rather than spaces - this gives more flexibility. Spaces should be used when you need to align something within a line.

Rule: tabs should be used at the beginning of a line for indentation, while spaces can be used in the middle of a line for alignment.

If (condition) ( $foo = "somevalue"; $foo2 = "somevalue2"; $foo_bar = "somevalue3"; $foo5 = "somevalue4"; )

And this is what the code looks like if you show invisible tab and space characters:

If (condition) ( ---$foo.....= "somevalue"; ---$foo2....= "somevalue2"; ---$foo_bar.= "somevalue3"; ---$foo5 ....= "somevalue4"; )

For associative arrays, values ​​must start on a new line. It is recommended to put the “last” comma when listing array elements - this makes it more convenient to add new elements...

$my_array = array(---"foo"..=> "somevalue", ---"foo2"..=> "somevalue2", ---"foo3"..=> "somevalue3", -- -"foo34".=> "somevalue3",);

Curly brace style

Curly braces must be used for all blocks in the style, as shown below:

If (condition) ( action1(); action2(); ) elseif (condition2 && condition3) ( action3(); action4(); ) else ( defaultaction(); )

If there is a long block, it should be broken down into two or more short blocks or functions if possible. If such a long block is necessary, add a short comment at the end to make it clear what exactly the curly brace closes. This approach is logical to use for a block with 35 or more lines.

Any code that is not intuitive should be commented out.

Always use curly braces, even if they are not required.

If (condition) ( action0(); ) if (condition) ( action1(); ) elseif (condition2) ( action2a(); action2b(); ) foreach ($items as $item) ( process_item($item); )

Note that the requirement to use curly braces always means that single line-style constructs are prohibited.

$var = "dangerous""; // raw data that may or may not be escaped $id = some_foo_number(); // data expected as a number, but we're not sure $wpdb->query($wpdb->prepare( "UPDATE $wpdb->posts SET post_title = %s WHERE ID = %d", $var, $id));

%s is used for strings and %d for integers. Please note that they are not "in quotes"! $wpdb->prepare() itself escapes strings and adds quotes if necessary. The advantage of prepare() is that you don't have to remember to manually use esc_sql() , and also that the query string with placeholders is more visual than if it used variables wrapped in esc_sql() .

Database queries

Try not to write direct queries to the database. If there is a suitable function, and there are many of them in WP, that can get the necessary data, use it.

Using functions instead of queries helps maintain future code compatibility. In addition, many functions work with the cache, and this can significantly speed up the code.

Names of classes, functions, files, constants, variables

Names of functions, variables, hooks

Use lowercase letters a-z in variables, hooks and function names and never CamelCase . Separate individual words with underscores _. Don't shorten variable names unless necessary; keep the code unambiguous and self-documenting.

Function some_name($some_variable) ( [...] )

Class names

You must use words with Capital_Letters separated by underscores. Any abbreviations (acronyms, abbreviations) must be CAPITAL.

Class Walker_Category extends Walker ( [...] ) class WP_HTTP ( [...] )

Constants must be UPPERCASE words separated by underscores:

Define("DOING_AJAX", true);

File names

Must be clear and must also contain only lowercase letters, and words must be separated by a hyphen - .

My-plugin-name.php

Class file names

Should be based on the class name with the prefix class- , the underscores in the class name are replaced with a hyphen, for example WP_Error becomes:

Class-wp-error.php

This file naming standard is valid for all existing and new class files. However, there are exception files: class.wp-dependencies.php, class.wp-scripts.php, class.wp-styles.php. These files are prefixed with class. , a period after the word class instead of a hyphen.

Clear values ​​of variables in function parameters

Boolean values ​​are preferred over string values. Those. Instead of true/false when calling functions, it is better to use some kind of string explaining the value of the parameter.

Bad code:

Function eat($what, $slowly = true) ( ​​... ) eat("mushrooms"); eat("mushrooms", true); // what does true mean? eat("dogfood", false); // what does false mean, the opposite of true?

Since PHP doesn't support named arguments, the flag values ​​are meaningless and every time we encounter a function call, like in the examples above, we need to look at the documentation for the function. Code can be more readable by using descriptive string values ​​instead of boolean values.

Good code:

Function eat($what, $speed = "slowly") ( ... ) eat("mushrooms"); eat("mushrooms", "slowly"); eat("dogfood", "quickly");

When you need more function parameters, use the $args array. He's even better!

Very good code:

Function eat($what, $args) ( ... ) eat("noodles", array("speed" => "moderate"));

Interpolation for dynamic hook names

For ease of readability and detection, hooks with variables in their names should be interpolated (enclosed in curly braces ( and )), and should not be concatenated:

The parentheses are needed so that PHP can correctly parse the data types of the variables in the interpolated string.

// correct do_action("($new_status)_($post->post_type)", $post->ID, $post); // incorrect do_action($new_status "_". $post->post_type, $post->ID, $post);

Where possible, dynamic values ​​in tag names should also be as short and precise as possible. $user_id is much clearer than, say, $this->id .

Ternary operator

Ternary operators are good, but they recommend that you always test for a true statement rather than a false statement. Otherwise it is simply misleading due to the double negative. The exception is use! empty() because sometimes it's just hard to write it any other way.

How to check:

// (if the condition is true = true) ? (then we do this) : (otherwise this); $music_type = ("jazz" == $music) ? "cool" : "blah"; // (if the value is not empty - ! empty) ? (then we do this) : (otherwise this);

How not to write:

// (if the condition is not met!= true) ? (then we do this) : (otherwise this); $music_type = ("jazz" != $music) ? "blah" : "cool";

Master Yoda's Conditions

When performing logical comparisons, always put constants or literals on the left and a variable on the right.

If (true == $the_force) ( $victorious = you_will($be); )

If we omit the second = sign in the above example (admittedly, this happens to even the most experienced of us), we will get a PHP error and we will immediately see it because the code will not work. But if the construction were the opposite - $the_force = true , then the condition would always be met and we would not see any error, and we could miss such a serious bug, which is also sometimes difficult to catch!

You just need to get used to this “upside down” spelling.

This also applies to == , != , === and !== . "Yoda's Conditions" for< , > , <= или >= much more difficult to read and it is better not to use them here.

Smart code

In short, the readability of the code should be in the foreground, it is more important than brevity or some not obvious, but convenient abbreviations.

Isset($var) || $var = some_function(); // or! isset($var) && $var = some_function();

Yes - this is a cool recording, it’s clear that it was made by an experienced programmer. But any other developer, and often even the author, in order to understand such a record needs to delve a little and spend extra seconds or minutes. This is not an obvious or clear entry and should be avoided, and it is better to write it longer, but more clearly:

If (! isset($var)) ( $var = some_function(); )

Error Suppression Operator @

PHP supports one error control operator: the @ sign. In case it precedes any expression in PHP code, any error messages generated by that expression will be ignored.

While this operator exists in the kernel, it is often used because one is too lazy to process a variable properly. Its use is strongly Not recommended since even the PHP documentation states:

Attention: Today, the "@" operator suppresses the output of messages even about critical errors that interrupt the script. Among other things, this means that if you used "@" to suppress errors that occur when running a function, if it is not available or is written incorrectly, further execution of the script will be stopped without any notification.

One day you decided to create your own website or blog, and for the management system you chose WordPress... As time passed, your site became more and more readable and then you realized that for even greater popularity you need to add a little functionality to the site or simply automate some that action.

You go to the “warehouse” of wordpress plugins and discover that the plugin you need is not there. What to do? What should I do? If you are at least a little familiar with the basics of programming in PHP, layout, then it will not be difficult for you Write a plugin for WordPress yourself.

Now let’s go to the “kitchen” to prepare our plugin.

P.s. If you don’t have knowledge in php and layout... don’t worry, ask someone to write you the necessary functionality :)

Before you start writing a plugin, you need to refer to the WordPress documentation, which describes the basic principles of writing plugins and some code examples.

I will not duplicate this information, but will go straight to writing the code.

Let's write a simple plugin that will allow you to save and display reviews about your site. Of course, such plugins already exist, but this will do just fine as an example.

The first thing we will do is come up with a unique name for our plugin - “ AdvUserReviews«.

Next, we will create a new directory “advuserreviews” in the directory of your site “/wp-content/plugins/”. And in it we will create a file “advuserreviews.php”. This will be the main file that will be responsible for general initialization. (It is advisable to use UTF-8 encoding for files).

At the very beginning of the file you must specify basic information about the plugin

Now, if you go to the control panel, you can see that the system has found a new plugin and offers to activate it. But it’s too early to do this yet.

We will write our new plugin in OOP style and all data processing will be located in one file. Let's create the main skeleton of the file.

// Stop direct call if(preg_match("#" . basename(__FILE__) . "#", $_SERVER["PHP_SELF"])) ( die("You are not allowed to call this page directly."); ) if (!class_exists("AdvUserReviews")) ( class AdvUserReviews ( // Storing internal data public $data = array(); // Object constructor // Initializing main variables function AdvUserReviews() ( ) ) ) global $rprice; $rprice = new AdvUserReviews();

Now let’s add the following code to the object constructor:

Function AdvUserReviews() ( global $wpdb; // Declare the initialization constant of our plugin DEFINE("AdvUserReviews", true); // File name of our plugin $this->plugin_name = plugin_basename(__FILE__); // URL address for our plugin $ this->plugin_url = trailingslashit(WP_PLUGIN_URL."/".dirname(plugin_basename(__FILE__))); // Table for storing our reviews // the $wpdb variable must be declared globally $this->tbl_adv_reviews = $wpdb->prefix . "adv_reviews"; // Function that is executed when the plugin is activated register_activation_hook($this->plugin_name, array(&$this, "activate")); // Function that is executed when the plugin is deactivated register_deactivation_hook($this->plugin_name, array (&$this, "deactivate")); // Function that is executed when uninstalling a plugin register_uninstall_hook($this->plugin_name, array(&$this, "uninstall")); )

In the object constructor we use 3 “hooks” or “hooks” (what are they?): register_activation_hook, register_deactivation_hook And register_uninstall_hook- these are the functions that are performed when the plugin is activated, deactivated and deleted, respectively.

Now let's directly implement these functions.

/** * Activate the plugin */ function activate() ( global $wpdb; require_once(ABSPATH . "wp-admin/upgrade-functions.php"); $table = $this->tbl_adv_reviews; // Determine the mysql version if ( version_compare(mysql_get_server_info(), "4.1.0", ">=")) ( if (! empty($wpdb->charset)) $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset"; if (! empty( $wpdb->collate)) $charset_collate .= "COLLATE $wpdb->collate"; ) // The structure of our table for reviews $sql_table_adv_reviews = "CREATE TABLE `".$wpdb->prefix."adv_reviews` (`ID` INT(10) UNSIGNED NULL AUTO_INCREMENT, `review_title` VARCHAR(255) NOT NULL DEFAULT "0", `review_text` TEXT NOT NULL, `review_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `review_user_name` VARCHAR(200) NULL, `review_user_email` VARCHAR(200) NULL, PRIMARY KEY (`ID`))".$charset_collate.";"; // Check for table existence if ($wpdb->get_var("show tables like "".$table.""" ) != $table) ( dbDelta($sql_table_adv_reviews); ) ) /** * Deactivate the plugin */ function deactivate() ( return true; ) /** * Removing a plugin */ function uninstall() ( global $wpdb; $wpdb->query("DROP TABLE IF EXISTS ($wpdb->prefix)adv_reviews"); )

Variable $wpdb Responsible for queries to the Database. Function dbDelta parses the current table structure, compares it to the desired table structure, and either adds or modifies the table as needed.

Accordingly, when the plugin is activated, a table structure is created to store reviews. When the plugin is deactivated, no action occurs, but when it is deleted, we delete our table. The actions can be understood in more detail from the source code.

The basic structure of the new plugin is ready. Now we need to start writing the functional part. To do this, we need to add the following lines of code to the class constructor:

// If we are in the admin. interface if (is_admin()) ( // Add styles and scripts add_action("wp_print_scripts", array(&$this, "admin_load_scripts")); add_action("wp_print_styles", array(&$this, "admin_load_styles")); // Add a menu for the plugin add_action("admin_menu", array(&$this, "admin_generate_menu")); ) else ( // Add styles and scripts add_action("wp_print_scripts", array(&$this, "site_load_scripts")) ; add_action("wp_print_styles", array(&$this, "site_load_styles")); add_shortcode("show_reviews", array (&$this, "site_show_reviews")); )

Let's look at this section of code in more detail. Let's start with the administration panel.
Function " is_admin» checks in what mode we are currently working - on the website or in the control panel.
Next, several hooks are used for functions:

  • wp_print_scripts- Add the necessary javascript files
  • wp_print_styles- Add the necessary styles
  • admin_menu- Adding a new menu to the control panel

Each hook corresponds to an implemented method in our class. In which the necessary operations are performed.
Let's look at the code for connecting styles and scripts

/** * Loading the necessary scripts for the management page * in the administration panel */ function admin_load_scripts() ( // Register scripts wp_register_script("advReviewsAdminJs", $this->plugin_url . "js/admin-scripts.js"); wp_register_script( "jquery", $this->plugin_url . "js/jquery-1.4.2.min.js"); // Add scripts to the page wp_enqueue_script("advReviewsAdminJs"); wp_enqueue_script("jquery"); ) /** * Loading the necessary styles for the control page * in the administration panel */ function admin_load_styles() ( // Register styles wp_register_style("advReviewsAdminCss", $this->plugin_url . "css/admin-style.css"); // Add styles wp_enqueue_style( "advReviewsAdminCss"); )

The following functions are used here.

Each action depends on the passed parameter “action”, respectively “edit” - editing a review, “submit” - saving an edited review and “delete” - deleting a review.

Data exchange with display pages occurs through the “data” object property. The source code of these pages will be posted in the archive with this module at the end of the article. I won’t insert them here, since the topic is already quite large.

This is where we finish with the administration panel and move on to displaying and adding reviews from users.

To tell WordPress when to call our plugin, we need to register “shortcode”, which is what was done in the constructor of our class. Read more about this.

Add_shortcode("show_reviews", array (&$this, "site_show_reviews"));

Now you can place the following code on any page of the site and it will force the function we specified (passed as the second parameter) to be executed. Below is the source code for this function.

/** * List of reviews on the site */ public function site_show_reviews($atts, $content=null) ( global $wpdb; if (isset($_POST["action"]) && $_POST["action"] == " add-review") ( $this->add_user_review(); ) // Select all reviews from the Database $this->data["reviews"] = $wpdb->get_results("SELECT * FROM `" . $this- >tbl_adv_reviews . "`", ARRAY_A); ## Enable output buffering ob_start (); include_once("site_reviews.php"); ## Receive data $output = ob_get_contents (); ## Disable buffering ob_end_clean (); return $output ; ) private function add_user_review() ( global $wpdb; $inputData = array("review_title" => strip_tags($_POST["review_title"]), "review_text" => strip_tags($_POST["review_text"]), " review_user_name" => strip_tags($_POST["review_user_name"]), "review_user_email" => strip_tags($_POST["review_user_email"]),); // Add a new review to the site $wpdb->insert($this-> tbl_adv_reviews, $inputData); )

In principle, there is nothing complicated here - an SQL query is made to select data, but if the “action” parameter is passed, then a new review is first added. But it is worth paying attention to output buffering. It is necessary in order to obtain the data of the inserted page.

That's all. Now we can see what we got. A download plugin and source codes you can here.

Of course, this is just an example of creating a plugin, but it will also work as a simple guest app if you modify it a little, for example, adding protection from bots and page-by-page output. Happy coding :)

Form on the website:

Plugin control panel:

Editing review:

You might also be interested in:


All novice webmasters are scared and put off by working with code - they are afraid of harming their site by adding HTML or PHP to it, or inserting it in the wrong place. Of course, if you put the code in the wrong place in WordPress, you can ruin everything. However, this CMS is so well tailored for beginners that it will be difficult to make a mistake.

In this article, we will look at how to safely insert HTML or PHP code into WordPress. But first, why this might be useful.

Why embed code in WordPress

During the life of the site, the webmaster may need to install code on WordPress that must be executed on the pages. This may be needed for various reasons: for example, installing a traffic counter, some unusual widget, or adding personality to the template.

WordPress offers two ways to install the code. Let's look at them.

Installation using the Text widget

In order to install code on WordPress using a widget, you need to go to the menu item in the “Appearance” console, and the sub-item “Widgets”. Among them, you should find “Text” and move it to the desired area with the mouse.

The widget will open and you can fill in its title, as well as place the required code in the appropriate field. After clicking the “Save” button, the operation will be performed on the site pages.

This method of installing code on WordPress is suitable for performing operations in HTML, PHP and even JavaScript. This method is often used because it is easy and works well for beginners.

Installation to file

Installing code on WordPress using file editing is not recommended for beginners, but sooner or later everyone will have to master it. This method is convenient because HTML or PHP can be placed in any part, not just the widget area, as described in the first method. The disadvantage of this installation method is that it can be dangerous and, if errors are made, it can lead to the site not working. Therefore, before using this method, you must make a backup copy of your files and database.

To install code directly into a file on WordPress, you need to know which area of ​​the site a particular file is responsible for. It is impossible to give precise recommendations here, since in different templates different files perform certain functions. However, you can learn something about theme files. In addition to installing the code in the template file on WordPress, this can also be done in the files of the CMS itself.

Code readability is a very sensitive topic and needs to be given due attention. In this article, you will learn 16 techniques that will help you advance in this topic.

1. Comments and Documentation

IDEs are becoming increasingly popular in the developer world because... they provide convenient tools for commenting and documenting code.

Here's an example:

Here's another example of calling your own method:

In this example, the commenting style is based on PHPDoc, and the IDE I'm using is Aptana.

2. Indents

I assume you already know the importance of indentation in your code. In general, there are several styles of code formatting.

Function foo() ( if ($maybe) ( do_it_now(); again(); ) else ( abort_mission(); ) finalize(); )

Function foo() ( if ($maybe) ( do_it_now(); again(); ) else ( abort_mission(); ) finalize(); )

Function foo() ( if ($maybe) ( do_it_now(); again(); ) else ( abort_mission(); ) finalize(); )

Personally, I most often use style #2, but sometimes I switch to #1. But this is all a matter of taste, of course. Most likely, there is no “best” style that would suit absolutely everyone. These rules, first of all, need to be followed by those who work in a team or participate in writing open-source projects.

There are also styles that combine certain characteristics. For example, the PEAR code writing standards, where the curly brace "(" in conditional statements remains on the same line, but is moved in functions.

PEAR style:

Function foo() ( // on a new line if ($maybe) ( // on the same line do_it_now(); again(); ) else ( abort_mission(); ) finalize(); )

It should also be noted that this style uses 4 spaces instead of tabs.

You can learn more about the different styles.

3. Avoid unnecessary comments

Yes, commenting code is good; however, there is no need to overdo it. Here's an example:

// get the country code $country_code = get_country_code($_SERVER["REMOTE_ADDR"]); // if the country is US if ($country_code == "US") ( // display the form echo form_input_state(); )

If the work of the code is obvious, then most likely you should not write unnecessary comments.

If you don’t have them, you can shorten them a little:

// display the form if the country is US $country_code = get_country_code($_SERVER["REMOTE_ADDR"]); if ($country_code == "US") ( echo form_input_state(); )

4. Code grouping

Most often, some tasks require writing several lines of code. Therefore, it is best to combine such tasks into separate blocks separated by spaces.

Here's a simple example:

// get the list of forums $forums = array(); $r = mysql_query("SELECT id, name, description FROM forums"); while ($d = mysql_fetch_assoc($r)) ( $forums = $d; ) // load the template load_template("header"); load_template("forum_list",$forums); load_template("footer");

If you add a comment before the start of each block, this will further improve the readability of your code.

5. Naming scheme

Sometimes even in the PHP language you can find inconsistencies in naming functions. And here are numerous examples:

  • strpos() vs str_split()
  • imagetypes() vs image_type_to_extension()

There are several popular styles:

  • camelCase: capitalizes the first letter of every new word.
  • underscores: Underscore between words: mysql_real_escape_string().

If you mix these techniques, sooner or later you can end up in an awkward situation. If you're working on a project that uses one of these techniques, you'll want to follow suit. This may still depend on the programming language. For example, most Java developers use camelCase, while PHP developers prefer underscores.

But even here there was a hybrid. Some developers use underscores in naming classes and methods (outside of classes), and in other cases use camelCase:

Class Foo_Bar ( public function someDummyMethod() ( ) ) function procedural_function_name() ( )

Once again I will say that there is no best style. You just have to stick to something.

6. DRY principle

DRY (Don’t Repeat Yourself) - don’t repeat yourself. Also known as DIE: Duplication is Evil.

The main task of any system, be it a web application or something else, is to automate repetitive tasks. This principle should be followed always and everywhere, especially if you are a developer. The same piece of code should not be repeated over and over again.

For example, most web applications consist of one or more pages. It is clear that these pages will contain the same elements. Header and footer are the most striking examples. You'd be surprised how many people still duplicate these elements on every page.

$this->load->view("includes/header"); $this->load->view($main_content); $this->load->view("includes/footer");

7. Avoid deep nesting

Code readability decreases sharply if you have deep nesting.

Function do_stuff() ( // ... if (is_writable($folder)) ( if ($fp = fopen($file_path,"w")) ( if ($stuff = get_some_stuff()) ( if (fwrite($ fp,$stuff)) ( // ... ) else ( return false; ) ) else ( return false; ) ) else ( return false; ) ) else ( return false; ) )

In order to correct the situation, you should reconsider how your code works and optimize it:

Function do_stuff() ( // ... if (!is_writable($folder)) ( return false; ) if (!$fp = fopen($file_path,"w")) ( return false; ) if (!$stuff = get_some_stuff()) ( return false; ) if (fwrite($fp,$stuff)) ( // ... ) else ( return false; ) )

8. Line length limit

Everyone knows that the reading process becomes much more enjoyable when the text is divided into columns. This is the main reason why our newspapers look like this:

A similar technique can be applied to our code:

// bad $my_email->set_from(" [email protected]")->add_to(" [email protected]")->set_subject("Methods Chained")->set_body("Some long message")->send(); // good $my_email ->set_from(" [email protected]") ->add_to(" [email protected]") ->set_subject("Methods Chained") ->set_body("Some long message") ->send(); // bad $query = "SELECT id, username, first_name, last_name, status FROM users LEFT JOIN user_posts USING (users.id, user_posts.user_id) WHERE post_id = "123""; // bad $query = "SELECT id, username, first_name, last_name, status FROM users LEFT JOIN user_posts USING(users.id, user_posts.user_id) WHERE post_id = "123"";

Most developers stick to 80 and 120 character limits.

9. Organizing Files and Folders

Technically, you can put all the code of your application in one file :) But what will you do when you need to change or add something.

I remember my first projects in which I attached files. However, my organization was very poor. I created an “inc” folder in which I placed several files: db.php and functions.php. During the process of writing the application, this folder grew larger and larger and ultimately it was difficult to figure out what was where.

To solve this problem, it is better to use various kinds of frameworks or at least adhere to their structure. This is what the project looks like on CodeIgniter:

10. Variable names

In general, variable names should be completely meaningful - this is ideal. An exception can be made for temporary variables.

Let's look at a few examples:

// $i for for loops ($i = 0; $i< 100; $i++) { // $j для вложенных циклов for ($j = 0; $j < 100; $j++) { } } // $ret для возвращаемых переменных function foo() { $ret["bar"] = get_bar(); $ret["stuff"] = get_stuff(); return $ret; } // $k и $v для foreach foreach ($some_array as $k =>$v) ( ) // $q, $r and $d for mysql $q = "SELECT * FROM table"; $r = mysql_query($q); while ($d = mysql_fetch_assocr($r)) ( ) // $fp for working with files $fp = fopen("file.txt","w");

11 - Write keywords in SQL in capital letters

Most web applications interact with databases. If you write SQL queries yourself, then they also need to be formatted accordingly... There is nothing complicated here. Just write your keywords in capital letters.

12. Separate code and data

This is another principle that will help you write more understandable programs. It involves preparing data in one place (for example, models), and interacting with it in another.

When PHP first began to develop, it was more like a templating system. Projects in this language contained mixed HTML and PHP code. Now everything has changed, and everyone should move to the next level of application writing.

You can develop a special style for yourself, or you can use the most popular means today.

Popular PHP Frameworks:

Template Systems:

Popular CMS

13. Special syntax for templates

If you don't want to use a template system, then you will most likely have to develop your own style of embedding PHP code into HTML.

And here is an example:

Hello, username; ?>
|

My Message Board

title; ?>

Forums as $forum): ?>

id, $forum->title) ?> (Threads->count(); ?> threads)

description; ?>

This technique will allow you to avoid unnecessary parentheses. Also, such code fits well into the HTML context.

14. Procedural and object-oriented approaches

Object-oriented programming will help you stick to a more or less clear structure, but that doesn't mean you should deviate from the procedural principles of writing applications.

Objects are great for representing data. Example:

Class User ( public $username; public $first_name; public $last_name; public $email; public function __construct() ( // ... ) public function create() ( // ... ) public function save() ( / / ... ) public function delete() ( // ... ) )

Procedural methods have their own specific benefits.

Function capitalize($string) ( $ret = strtoupper($string); $ret .= strtolower(substr($string,1)); return $ret; )

15. Read Open Source Code

Typically, Open Source projects are written by a large number of developers. From this point of view, studying the written code in similar projects can help you gain experience. So don't waste your time on this.

16. Refactoring

Refactoring is changing code without losing functionality. It can also be used to improve readability. There is no room for fixing bugs or adding functionality. You just change the structure of your code a little.

I hope you found this article helpful! Am I missing something? Share your experience!

I dare to assume that there have been times in your life when you wanted to add (correct) something to the theme of your WP site, or to the functionality of some plugin. Moreover, the developers did not include this feature in standard controls. And your soul does not recognize any restrictions and requires flights of fancy :) As you understand, there is a way out of any situation, in this case, we will have to correct the code of the plugin, theme...

The main difficulty in editing code is that the changes you make, unfortunately, are not saved for long, and will most likely be canceled during the next update. If the solution you see is to avoid updates, I dare to dissuade you from this dangerous ignoble decision, since updates contain important changes in terms of security and bug fixes, and often also add new functions.

As a result, it is preferable to use methods that will stand up in our dynamically changing world and at the same time save your precious time.

Cautions!

On the Internet you can often find advice that suggests making changes to the file functions.php- if there is any opportunity to do without this, it is better not to touch this file. In the methods below you will see a way to implement this. And in any case, you need to create a child theme and not touch the parent one.

When adding prefixes to a function, always use custom code in the form: _prefix(to the name of the function being changed). This action will protect you from conflicts with other functions of the theme or plugin.

So, how do you add code to a WP site?

1) Custom plugin

This way you can insert code snippets, and they will not be deleted during the update, and you can also edit, activate them in the future, or vice versa - deactivate them as necessary.

This is easy to do: first you need to create a directory for your plugin, and name it accordingly, for example moy-plugin (use only dashes, not underslashes)

Next, we create the main plugin file. As you understand, it should include a name, description and basic information, as well as code that will help secure the plugin from intruders. And we call this file, let’s say moy-plugin.php. The .php extension will tell WP what language the file was created in.

You can create a file using the method described above in any text editor, for example, NotePad, which is already carefully installed in the Windows operating system (TextEdit on Mac). It is better not to use the Microsoft Word editor, since it formats the text, and we absolutely do not need it in this situation.

So here's the code to add:

And below this code, make your changes as your creative soul requires. There is no need to add closing PHP tags at the end. In this case, the name, description and URL will be displayed in your admin panel. And, of course, you can replace the “ClubWP” information with your own information

After that, all that remains is to pack what you have created into a zip archive and send it to your site’s ftp. In the future, this way you can make any changes to your plugin.

In this easy way you will create a simple plugin for your needs.

2) Code Snippets plugin

If the method described above is difficult for you, or you are a very practical person and are used to getting results faster, Code Snippets was created especially for you. Just like the feature described above, the plugin adds your code with the ability to further edit it without using your theme.

After installing the plugin, a new “Snippets” window will appear in the admin panel, in which, accordingly, you can add new snippets. For which you can enter a code and information about its purpose.

Thus, you have the option to enable or disable custom code in the form of plugins. Very convenient and practical, because... Sometimes there may be conflicts with themes and plugins, and you can easily understand this and disable the generated code.

3) Editing Functions.php of a child theme

If using plugins is not suitable for you and you need to make changes directly to the theme of your site, then this method is for you. Let me remind you that you can only do this with child themes.

To use this method, I offer my template functions.php child theme. Unpack and edit the file style.css(template name and import URL)

P.S. Try to do everything possible to simplify your life in the future, including your hard share of eliminating bugs and editing custom code as the need arises.