Inactivity add review php. Custom Post Types Guide: Creation, Display, and Additional Fields

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__))); // The 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 the 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 this 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"); ## Get data $output = ob_get_contents (); ## Disable buffering ob_end_clean (); ; ) 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:


A full stack framework that is faster than most if not all micro frameworks. This framework is not for beginners. It gives you the tools, but it"s up to the developer to implement them. If you have a genuine understanding of PHP, and performance is of concern, look no further. The documentation is thorough, but not beginner oriented, and the community is somewhat sparse, but I can't stress performance enough. This framework puts my PHP applications on a performance level with JAVA applications.

Phlacon is from my point of view not just the fastest framework on the market, but also it offers various features and nice components. Also very good to use as MicroFramework for restfull API"s or full MVC framework. Comes with C ORM, and twig template engine. Also what I really appreciate is how the framework is dynamic, you use only what you want, you can simply replace classes and libraries for custom ones or affect flow with events.

Very good job, only one problem is the community but I believe it will grow very fast:)

Phalcon is undoubtedly one of the fastest frameworks out there, and that"s its strong point. On the other hand, the documentation is a bit disorganized, Web tools (code generator) has major issues in Windows, and it is still lacking a bit more of a community to help new developers. But once again, performance, WOW.

Answer

Based on https://toster.ru/q/276441 It’s clear that a lot depends on the project, so this post should be adapted to your case.

* Safety:
- Each argument of a simple type method must be checked for type in case of proxying and for boundary values ​​in case of processing. If something goes wrong, an exception is thrown. If a method with several arguments consists of 80% verification of arguments, this is quite normal))
- No trigger_error, only exceptions.
- Exceptions MUST be human-understandable, all sorts of “Something went wrong” can be given to the user, but the log should contain an exception with a stack trace and a human-understandable description of what went wrong there.
- Each argument (object) of a method must be type-hinted to its class or interface.
- As a rule, eval is severely reprimanded
- @ is allowed only in desperate situations, for example the json_last_error check.
- Before working with the database, it is mandatory to check the data.
- No == and!=. With swtich - the only exception, depending on the situation.
- If the method returns not only bool, but something else, a strict check with ===, or!== is required.
- No conditions with assignments inside. while($row = ...) is also unacceptable.
- Magic getters/setters are allowed only in desperate situations, otherwise they are prohibited.
- Concatenations in sql - only in hopeless situations.
- Parameters in sql - ONLY through placeholders.
- No global variables.
- Dates in the form of a string are allowed only in templates and in the database; in PHP code they are immediately converted to \DateTimeImmutable (in desperate situations, \DateTime is allowed)
- Of course, it depends on the project, but as a rule there should be only two entry points: index.php for the web and console (or something else called) for the console.

* Codestyle PSR-2 + PSR-5 at least, + a bunch of more stringent requirements (for starters, everything that is marked as SHOULD in PSR becomes MUST)
- In PhpStorm, not a single line should be highlighted (the exception is typo errors, for example, the dictionary does not know some of the abbreviations adopted in your project). In this case, it is allowed to use /** @noinspection *** */ for hopeless situations.
- If someone says that they are writing in another editor and it is not highlighted, they still send it for revision.

* Code organization:
- No global functions.
- Classes without namespace are allowed only in extremely desperate situations.

* Testability (in the sense of ease of testing) of the code should be high.
- Code coverage is required for all possible cases of using each public method with dependency mocks.

* MVC principles:
- No processing of user input in models, literally at all.
- No queries to the database from templates.
- No layout/js/css/sql-in in controllers.
- There is NO MAGIC in the models, only private properties + getters with setters.
- Models are allowed to use the save method (if there is one, of course) only in exceptional situations. In all others - either insert or update.

* SOLID principles:
- No universal objects that can do everything.
- If the method for internal use is private, no public.
- Static methods are allowed only in cases of hopelessness.

* The DRY principle is allowed to be violated in the following cases:
- Explicit separation of duties
- In tests (each test should be as independent as possible)

* Working with the database:
- The request in the cycle must be REALLY justified.
- Severe reprimand for ORDER BY RAND()
- Search not by keys (of course, if the table is NOT 5 rows) is prohibited.
- Search without LIMIT (again, if the table is NOT 5 rows) is prohibited.
- SELECT * - prohibited.
- Denormalization of the database must be justified.
- MyISAM is not used (so)))
- Multiple operations are required in a transaction, with a rollback if something goes wrong.
- The database should not contain business logic, only data in a holistic form.
- There should be no unnecessary twitching of the database where it can be done without it.

* The cache must be cleared under two conditions (not one of them, but two):
- Time.
- Failure according to business logic.
It is only allowed for time in desperate situations, but then the time is a short period.
- When calculating cache keys, a variable from the application configuration should be used (in case of updates, the cache is reset by code, not by cache server flash). In the case of using many servers, this is a very convenient and flexible tool for diplomacy.

* About people:
- “I’m used to writing this way and will continue to do so” is not a question, you will only pass the review when you change your opinion.
- “I write in vim and it’s so convenient for me” - great, I also write console code in it)) but there are requirements for the code, if you can’t do them, you won’t pass the review.
- “I copied this terrible method and changed 2 lines” - this is of course wonderful, but according to the label, you are the author of this entire method, so let’s not talk nonsense, okay?
- “It works!” - this phrase translates roughly like this: “yes, I understand that I’m writing complete nonsense, but I can’t write normally because I can’t,” did I understand you correctly?))
- “Everything works for me!” - I'm happy for you, but what about the production?
- “Everything is simple there” - do not use the word “simple”, from the word “absolutely”. Here’s a piece of code (the first one you come across with complex business logic), where is the error (it doesn’t matter whether there is one or not)? You've been watching it for 2 minutes already, what's the problem, everything is "simple"))

* Anything:
ActiveRecord (I’m telling you this as a former Yii fan) is complete crap, take it as the original one. In fact, you have models connected to the database wandering around the project uncontrollably. More than once I came across that in the same templates they call save or update (you should be burned for this).

Basics:
1. The presence of critical errors and outdated functions.
2. Use of patterns, elegance of solutions.
3. Readability of the code, presence of comments, presence of docks.
4. Compliance with paradigms and conventions (for example, violation of MVC).

Secondary/not important:
1. Code performance (except for highload)
2. Memory consumption (excluding bigdata)
3. Efficiency of SQL queries (with the exception of very awkward ones)
4. Avoiding unimportant but potentially bottlenecks in the data (for example, slowing down the file system when there are a large number of images in the upload folder)
5. Novelty of the technologies used.
6. Justified\Unjustified\Excessive Cycling.

  1. The code does not contain obvious or potential errors.
  2. The code works as described in the documentation, technical specifications or accompanying comments.
  3. Coding style follows accepted coding rules
  4. The code has accompanying comments according to phpDoc
  5. The nesting of blocks does not exceed the 4th level.
  6. The code does not generate messages at the Strict, Warning, Notice, or Deprecated levels. If this cannot be avoided, then immediately before the line that generates this, you must force error_reporting to be disabled, and immediately after the line, error_reporting must be turned on to the original value (which was before). Such code must be documented in a special way.
  7. The commented out piece of code should be removed.
  8. HTML and JavaScript inserts are prohibited in PHP code (except for phpTemplate). All insertions must be made using special templates.
  9. Classes, functions, variables and constants must be named logically in a human-readable way in English according to coding standards. Naming in transliteration in Russian or other languages ​​is not allowed
  10. The scope of variables and methods of classes must always be defined (private, protected, public).
  11. The size of one method should not exceed 40-50 lines.
  12. A variable used in a loop or in a conditional block must be initialized in advance.
  13. A variable must contain only one type at any time. An empty variable must contain null. ($var = false; $var = "test"; is not allowed. $var = null is allowed; $var = "test";).
  14. When passing class objects to methods, type checking must be used.

First, from a code organization standpoint, it’d be better to put all of the review logic into one or more includable files and then include it on product pages:

Include("includes/reviews.php");

This way, the product pages can remain unadulterated and the same review code can easily be used, or modified, as needed. The reviews.php script would do several things:

  • Show the review form
  • Handle the review form
  • List the existing reviews
  • Handle secondary actions, such as flagging reviews or comments as inappropriate, indicating that reviews were helpful, adding comments to reviews, indicating that comments where helpful, and so forth

Hopefully you’ve done plenty of web development already, so you know that a form for adding reviews would just be like so:

Review This Product

5 4 3 2 1

Clearly you’d want to use some CSS to make it pretty, but that’s the basic idea. The main catch is that the product ID and product type (or whatever the database must have in order to associate a review with an item) must be stored in hidden inputs. You’d have the PHP script that displays the product write these values ​​to the inputs.

If login is required, you might add (PHP) code that only shows the form to logged-in users, or prints a comment saying the user must log in to review the product. Similarly, if you have a system in place for guaranteeing a person only ever reviews a product once, you’d have PHP check for that scenario before showing this form.

The form submission could go to a new page, but then the user would need to click the Back button to return to the product page, which isn’t ideal. I would instead submit the form back to the product page. For example, on any dynamic website, the same PHP script is used to display all the content of a specific type. In my Effortless E-Commerce with PHP and MySQL book, the first example site uses the page.php script to show any page of content. The action attribute of the form would point to the same page.php . You can accomplish this by just leaving the attribute empty, or by using PHP to dynamically set the value.

If the PHP page that lists the products requires that a value identifying the product be passed in the URL, then the form would need to store that value in a hidden input as well. (That may already be the case, with the product_id input, depending upon how the site is set up.) Secondarily, the product script would also need to be updated to allow for the product value to be received via POST .

For the reviews.php script to know when to handle a form submission, it can check how the script was accessed:

If ($_SERVER["REQUEST_METHOD"] == "POST") ( // Handle the form.

When the review form is submitted, the form data should be validated. You should also apply strip_tags() to the data to prevent Cross-Site Scripting (XSS) attacks or other bad behavior. And non-numeric values ​​would be run through an escaping function, such as mysqli_real_escape_string() . Or you could just use prepared statements or stored procedures for better security and performance.

If you add an anchor to the form’s action attribute action="page.php#reviews"the user will be taken to the reviews section of the page upon the submission, which is a nice touch.

If the reviews.php script is also handling some of the other actionsinappropriate reviews or comments, helpful indicators, etc.the script would need to watch for those submissions, too. I would use hidden inputs named “task” to indicate which action is being taken.

In a separate article, I demonstrate how to use Ajax for a simple rating system. Similar Ajax code could be used for the review system, too.

Get a valuable feedback from your customers by giving them the freedom to share their impressions freely. Let them rate your products and/or services straight on your website. See below the key features that come standard with our online review system.

    Reviews & Ratings

    Embed PHP Review Script into your website and let clients share their experience with the products and services you offer. They can rate by criteria and give both positive and negative feedback.

    Multiple Languages

    The PHP review system can speak not only English, but any language you may need. You can translate all titles and system messages from the admin page using unique IDs for each piece of text.

    Editable Rating Criteria

    Depending on the type of business, review system admins can
    set different rating criteria to be shown in the front-end form.
    Each of these criteria is rated with 1 to 5 stars.

    Email & SMS Notifications

    Set up the online review system to send Email & SMS alerts when a new review has been posted. You can easily specify which users to receive these messages from the Users menu.

    Multiple User Types

    Create unlimited client types depending on the industry and services used. Hotel ratings can go with the following user types: Family with kids, Couple, Business trip etc. They appear as labels in the reviews.

    Responsive & Attractive

    The review and rating script runs on all devices, seamlessly adapting to various screen sizes. In accord with your website branding, you can pick the best matching front-end theme among 10 color options.

    A quick tips box next to the review form allows you to add some witty words and draw customers out. The review system filters reviews by user type. Customers can rate other clients" ratings, too.

    With a Developer License you get the source code and can make any custom changes to the PHP Review Script. We can also modify the customer review system upon request.