PHP Categories (Category tree). PHP class for convenient and safe work with MySQL Convenience and brevity of the application code

) I showed you an example of using regular expressions to find certain pieces of a page's source code. Now we will learn how to write them yourself. This skill will help you write, clear text from unnecessary fragments, search for the right parts in large volumes of text, and so on.

Publication date: 20.10.2013

We continue to write a liveinternet visitor statistics parser. If someone has just joined us, then I advise you to start with, where we connected to the service without authorization. There we learned how to get content from open pages that are not password protected. But, in fact, access to most sites is closed, so there is very little benefit from a script that does not know how to log in, as you understand. But don't worry, we'll fix it now.

Publication date: 08.10.2013

Good afternoon, readers! It's time to get some practice. You already have enough knowledge to start writing useful scripts that will make your work easier. One of these can be a parser. What it is, I described in detail in my own, so if you don’t know, I advise you to read it. Briefly, the essence of the parser is to search for and isolate the necessary information from a large piece of text. In the case of the Internet, this is most often pulling out the required data from the pages of sites. In our case, this will be Liveinternet. So let's go!

Publication date: 03/10/2013

This article will focus on such a powerful tool as cURL, as well as a php library that provides access to this tool - libcurl. What is all this for? To communicate with the server via data transfer protocols, such as http or ftp. The rest of the protocols are not of particular interest to us, if someone wants to delve into this topic, then they will have to dig English-language resources, and this article will contain the basics and examples of use.

Publication date: 24.11.2012

Publication date: 05.11.2012

And now there will be a rather large, but not complicated lesson about working with files in php. First of all, what are the files for? After all, you can store everything in a MySQL or PostgreSQL database or any other. But sometimes there are such tasks when using the database, with all the processing and concern for the security of the connection, is not advisable. For example, you need to make a regular counter, and before that, we did not use a database in our project. So, for the sake of one tiny counter, should we start a database and store only a couple of lines in it? it's much easier to use files. In addition, sometimes hosting does not support databases at all, then files generally remain the only way out.

Publication date: 04.11.2012

Whenever you allow your users to submit text to your site (name, or any other information), you must be careful. You need to be sure that you do not have security holes in the site that attackers can use to hack. If you still need to receive data from the user, be sure to use the htmlentities function to prevent running HTML code or scripts that can be harmful and dangerous!

Publication date: 04.11.2012

In this lesson, we will look at techniques for passing data between forms and pages. These methods are POST and GET. We will talk about each separately and in more detail. Generally speaking, it is necessary for communication between forms. For example, we fill in some fields on the page and we need to transfer them to another page for processing.

Publication date: 03.11.2012

In fact, as you might have guessed by now, the do while loop is a slightly modified version of the while loop we saw in previous tutorials. If you remember how the regular while works, then it will be easier for you to understand the new loop. Let's repeat: the body of the while loop is executed if the condition is true and not executed if it is not true, but it may not be executed even once if the condition is false from the very beginning. How does do while work?

Publication date: 03.11.2012

Imagine that you have an associative array that you want to iterate over. PHP provides an easy way to use each element of an array in turn using the Foreach construct.

Returns an array of objects containing category information.

The parameters passed to this function are very similar to the parameters passed to the wp_list_categories() function and can be passed either as an array or as a query string: type=post&order=DESC .

✈ 1 time = 0.005625s = So slow| 50000 times = 11.98s = slowly| PHP 7.1.11, WP 4.9.5

Usage

$categories = get_categories($args);

Usage pattern

$categories = get_categories(array("taxonomy" => "category", "type" => "post", "child_of" => 0, "parent" => "", "orderby" => "name", " order" => "ASC", "hide_empty" => 1, "hierarchical" => 1, "exclude" => "", "include" => "", "number" => 0, "pad_counts" => false, // see the full list of parameters in the function description http://wp-kama.ru/function/get_terms)); if($categories)( foreach($categories as $cat)( // Data in the $cat object // $cat->term_id // $cat->name (Category 1) // $cat->slug (rubrika- 1) // $cat->term_group (0) // $cat->term_taxonomy_id (4) // $cat->taxonomy (category) // $cat->description (Description text) // $cat->parent (0) // $cat->count (14) // $cat->object_id (2743) // $cat->cat_ID (4) // $cat->category_count (14) // $cat->category_description (Description text) // $cat->cat_name (Category 1) // $cat->category_nicename (rubrika-1) // $cat->category_parent (0) ) ) taxonomy (line) The name of the taxonomy to process. Added since version 3.0.
Default: "category" type (line)
  • post - post categories (default);
  • link - sections of links.
    Default: "post"
child_of (line) Get child categories (including all nesting levels) of the specified category. The parameter specifies the ID of the parent category (the category whose nested categories you want to show). parent (number) Gets the categories whose parent category is equal to the specified ID parameter. The difference from child_of is that one level of nesting will be shown.
Default: "" order by (line)

Sorting the received data according to certain criteria. For example, by the number of posts in each category or by category name. The following criteria are available:

  • ID - sorting by ID;
  • name - sort by name (default);
  • slug - sorting by alt. name (slug);
  • count - by the number of entries in the category;
  • term_group - by group.

Default: "name"

order (line)

The sorting direction specified in the "orderby" parameter:

  • ASC - in order, from smallest to largest (1, 2, 3; a, b, c);
  • DESC - in reverse order, from largest to smallest (3, 2, 1; c, b, a).

Default: "ASC"

Hide_empty (logical)

Whether or not to get empty categories (having no entries):

  • 1 (true) - do not receive empty,
  • 0 (false) - get empty.

Default: true

Hierarchical (logical) If the parameter is set to true, the result will include empty child categories whose child categories have entries (non-empty).
Default: true exclude (string/array) Exclude any categories from the list. You must specify category IDs separated by commas or in an array. If this parameter is specified, the child_of parameter will be overridden.
Default: "" include (string/array) List only the specified categories. You need to specify category IDs separated by commas or in an array.
Default: "" number (number) Limit. The number of categories to be retrieved. By default, no restrictions - all categories will be retrieved. pad_counts (logical) If you pass true, then the number that shows the number of entries in the parent categories will be the sum of its own entries and entries from child categories.
Default: false

Examples

#1 Dropdown list

In order to create a dropdown list of categories, we can use another special function wp_dropdown_categories() :

wp_dropdown_categories(array("hide_empty" => 0, "name" => "category_parent", "orderby" => "name", "selected" => $category->parent, "hierarchical" => true, "show_option_none" => __("None")));

however, with this approach, we will lose some flexibility in setting up the list, since we will end up with a fully formed list.

Therefore, in some cases it will be more logical to create a drop-down list using the function get_categories(). Here's an example (assuming we want to display the subcategories (children) of category 10):

#2 List of categories and their description

This example will show us how to list links to categories, where immediately after each link there will be a description of the category (specified when creating / editing a category):

"name", "order" => "ASC")); foreach($categories as $category)( echo "

Category: term_id) . ""title="" . sprintf(__("View all posts in %s"), $category->name) . "" " . ">" . $category->name."

"; echo "

Description:". $category->description . "

"; echo "

Post Count: ". $category->count . "

"; } ?>

Notes

  • See: get_terms() Type of arguments that can be changed.

List of changes

Since version 2.1.0 Introduced.

The code getcategories : wp-includes/category.php WP 5.3.2

"category"); $args = wp_parse_args($args, $defaults); /** * Filters the taxonomy used to retrieve terms when calling get_categories(). * * @since 2.7.0 * * @param string $taxonomy Taxonomy to retrieve terms from. * @param array $args An array of arguments. See get_terms(). */ $args["taxonomy"] = apply_filters("get_categories_taxonomy", $args["taxonomy"], $args); // Back compat if (isset($args["type"]) && "link" == $args["type"]) ( _deprecated_argument(__FUNCTION__, "3.0.0", sprintf(/* translators: 1: " type => link", 2: "taxonomy => link_category" */ __("%1$s is deprecated. Use %2$s instead."), " type => link", "taxonomy => link_category")); $args["taxonomy"] = "link_category"; ) $categories = get_terms($args); if (is_wp_error($categories)) ( $categories = array(); ) else ( $categories = (array ) $categories; foreach (array_keys($categories) as $k) ( _make_cat_compat($categories[ $k ]); ) ) return $categories; )

For each post and entry wordpress user can set one or more headings (categories). This feature allows you to group posts that are close in meaning and allow visitors to read and view only those headings that they like. For example, when I created my main blog Tod's Blog, I was going to write about all the nuances of the Internet - from design to programming. Suppose a person came from a search engine to an article about wordpress and would like to read even more about the system - he would have to rummage through the archives, reuse the search, or view all the posts in a row. Of course, all this could have been avoided by going to a special category called wordpress. Or, for example, for those who are only interested in design, a blog section could be interesting.

If you look closely at the header of the blog, you can see a kind of menu where the wordpress headings act as sections of the project. As for me, this is a fairly convenient and visual way of dividing the subject of entries.

In the very center of the page, you will see a form for adding a new category. Here you need to specify its name (name), label (part of the url link for CNC), parent category (if any), and you can also set a short description. The parent category allows you to create sections in wordpress with several levels of nesting - for example, for the category "Wordpress" on some IT blog, you can add the same templates, plugins, etc.

On the right side of the Categories page, all wordpress categories are displayed, with the option to edit or delete them. To perform actions, just move the mouse cursor over the name of a category, after which you will see a small pop-up menu.

When editing, you will see in one of the information blocks one where you can select one or more categories for the article. Just check the boxes next to the names you want.

Here you can also add new headings by clicking on the appropriate link. The only drawback of this mechanism is that when creating, you can only specify the name and parent category, while to set the label field, you will have to go to the "Headings" section and edit the information there.

In addition, you can edit categories for blog posts through their list in the menu Posts - Edit. There, when you hover over a particular publication, you will see the link “Quick Editing”. Click on it and see the form for editing:

Here you can change categories, tags, and all additional information on the article. The thing is very convenient + works without reloading the page.

wp_list_categories function for wordpress category

By tradition, I consider not only the issue of working with certain elements of the system, but also give special functions for templates. Just like I talked about. So, to display a list of categories with links to them, use wp_list_categories. It has a number of arguments:

  • show_option_all - displays a link to all categories if the list is selected as the display style.
  • orderby - sorting for categories by ID, name (name), label (slug), number of posts (count).
  • order - sort order (ASC - ascending, DESC - descending).
  • show_last_updated - Show the date of the last update.
  • style - design style: list (list), division through
    (none).
  • show_count - display the number of posts in the category.
  • hide_empty - hide empty categories where there are no posts.
  • use_desc_for_title - Use the description for the title attribute in the link.
  • child_of - display only categories for the given parent rubric.
  • feed - display a link to the feed for categories.
  • feed_type - feed type.
  • feed_image - An image for the rss icon.
  • exclude - exclude categories from the list, while the child_of parameter is automatically disabled.
  • exclude_tree - exclusions of the whole category branch.
  • include is an inverse parameter that includes only the specified wordpress categories in the list.
  • hierarchical - parameter for displaying subcategories.
  • title_li - title of the list of categories.
  • number - the number of categories to display (if there are too many).
  • echo - Displays categories, default is True.
  • depth - Specifies the number of levels for subcategories to display.

Finally, I will give a number of examples of using wp_list_categories. First, the variant from the header of this blog.

"hide_empty=1&exclude=1&title_li=&orderby=count&order=desc&use_desc_for_title=0") ; ?>

Here, the display of hidden categories is set, the category with is excluded from the list, an empty line for the block title, sorting by the number of articles and by decrease (that is, I have the most articles in the section). The last argument does not substitute the category description in the title for the link.

Well, a couple more simple situations. Use of exclusions and inclusions of categories.

If you have something to add about the headings and categories of wordpress, write in the comments.

update: You may also need a little hack to . In wordpress, by default, the title text is defined, something like “view all posts in the category ....”, you can instead just leave the name of the category - read the article at the link above.

Today our goal is to create a hierarchical structure of categories. It is important for us that it is convenient to store categories and that it is easy to display them where we need them.

Sometimes the simple seems complicated, that's why I'll lay out a few code snippets that I hope will be useful to you for implementing php categories in the form of a tree.

So, the structure should consist of the category id (id), the category name (name) and of course the parent category id (parent_id). In MySQL it looks like this:

CREATE TABLE IF NOT EXISTS `category` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `parent_id` int(11) NOT NULL, PRIMARY KEY (`id`)) ENGINE =InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0 ;

Minimal and understandable table structure for storing categories.

INSERT INTO `category` (`id`, `name`, `parent_id`) VALUES (1, "Phones and tablets", "0"), (2, "Cars", "0"), (3, "Samsung ", "1"), (4, "Apple", "1"), (5, "LG", "1"), (6, "Ford", "2"), (7, "Lexus", "2"), (8, "BMW", "2"), (9, "Galaxy Tab 4", "3"), (10, "Galaxy S6", "3");

Where parent_id=0, this category has no parent category.

Everything is clear and simple here. Now let's move on to listing the categories. But for the correct output of the list, we first need to get the entire list of php categories, and only then, using recursion, form our tree. The following function is to get this list:

Function get_cat() ( // query the database $sql = "SELECT * FROM category"; $result = mysql_query($sql); if(!$result) ( return NULL; ) $arr_cat = array(); if( mysql_num_rows($result) != 0) ( //For($i = 0; $i< mysql_num_rows($result);$i++) { $row = mysql_fetch_array($result,MYSQL_ASSOC); //Формируем массив, где ключами являются адишники на родительские категории if(empty($arr_cat[$row["parent_id"]])) { $arr_cat[$row["parent_id"]] = array(); } $arr_cat[$row["parent_id"]] = $row; } //возвращаем массив return $arr_cat; } }

//get the catalog array $result = get_cat();

Now we need a function with recursion

Function view_cat($arr,$parent_id = 0) ( //Recursion exit conditions if(empty($arr[$parent_id])) ( return; ) echo "

    "; // loop through the array and display for($i = 0; $i< count($arr[$parent_id]);$i++) { echo "
  • " .$arr[$parent_id][$i]["name"].""; //recursion - check if there are any child categories view_cat($arr,$arr[$parent_id][$i]["id"] ); echo "
  • "; ) echo "
"; }

Now it remains only to display the directory on the screen using the recursive function

View_cat($result);

And in general, that's all. This way we can get a complete tree of categories with infinite subcategories.

And so, to begin with, I will describe what we will work with and what we will need.
System: PHP 5 and above, mySQL 4 and above
Helper classes: dbsql.class.php (database class)
Nested category class: classTreeCategory.php (directly the main class, its listing and explanations are given below.

Create a table in the database with the following structure:

Viewing MySQL Code

This table contains a field ID- serial number of the category, podcat- has a value of zero for categories of the first order or the ID of the parent category, name- name of category.

An example of the class, displaying categories as a list with subcategories:

View PHP code

include("dbsql.class.php") ; include("classTreeCategory.php" ) ; $DB = new DB_Engine("mysql" , $settings [ "dbHost" ] , $settings [ "dbUser" ] , $settings [ "dbPass" ] , $settings [ "dbName" ] ) ; // connect to the database, specifying access data$category = new TreeCategory ($DB ) ; // pass to the category class, the object of work with the database$category -> table = "category" ; // table name in the database with categories$array = $category -> getCategory() ; // get all categories from the database in the form of a multi-level array, sorted and nested already in the order we need$category -> outCategory ($array , "option" ) ; // preparing the output of categories (forming HTML), passing an array with categories echo $category -> html ; // output categories as HTML

As you can see from the example above, everything is extremely simple, we create a new $category object, set which database table we work with: 'category', then we get from the table a list of all categories already formatted as an array and decomposed in a hierarchical order, taking into account all subcategories. then we pass the array to the outCategory() method, which generates a ready-made HTML code for us, which remains only to be displayed in the browser.

The outCategory() method, as we can see, takes two parameters @array and @string in the first parameter an array with all categories, and in the second a string containing a value option or table, this value specifies what type of HTML code to generate.
Meaning option

View HTML code

To insert the given HTML code into the select field of any form.

Meaning table- generates the following HTML code:

View HTML code

This HTML code is handy for pasting into a table that displays all of our categories subcategories.

The class also has the following methods:
deleteItem($id);- removes one category, despite the nested ones
delCategory($array, $id);- deletes a category with all nested subcategories, $array - an array with all categories prepared by the $category->getCategory() method, $id - number of the category to be deleted
addItem();- this method should be called if you want to add a category, while this method reads the values ​​from the data transmitted by the POST method, i.e. from the $_POST array.
$name=$this->PHP_slashes(strip_tags($_POST['name'])); // category name
$podcat=intval($_POST['podcat']); // ID of the parent category, if 0 is specified, the category will be at the root.
updateItem(); - similar to the previous method, except that this method updates the category, its name and nesting level.

table="category"; // request to select a list of categories, table name * $category->outCategory($category->getCategory()); // prepare category output (request an array of categories) * echo $category->html; // display categories in HTML name * */ /** * Dump the table being worked on * * DROP TABLE IF EXISTS `category`; * CREATE TABLE `category` (* `id` int(11) NOT NULL auto_increment, * `podcat` int(11) NOT NULL, * `name` varchar(255) NOT NULL, * PRIMARY KEY (`id`), * KEY `id` (`id`) *) ENGINE=MyISAM DEFAULT CHARSET=utf8; * */ class TreeCategory ( /** * Database query string */ var $table; /** * Database interface */ var $DB; /** * Array of categories with nested subcategories */ var $arrayCat; / ** * Auto-count the number of dashes before the category name when displaying */ var $countPodcat; /** * HTML code for displaying categories with subcategories */ var $html; /** * Get the interface for working with the database and put it into a local variable */ function __construct($DB) ( $this->DB=$DB; $this->component=$_GET["component"]; ) /** * Gets a list of categories, sorts and puts into an array with nested arrays, etc. * @return array category */ function getCategory () ( $all = $this->DB->getAll("SELECT * FROM `($this->table)` ORDER BY `id` ASC"); $path = array(); if(count($all)>0) ( foreach($all as $item): if($item["podcat"]==0)$sort[$item[ "id"]]=$item; if($item["podcat"]>0) ( if(isset($path[$item["podcat"]])) ( $str="$sort"; foreach( $path[$item["podcat"]] as $pitem): $rep =$item["podcat"]; $str.="[$pitem]"; endforeach; $str.="[($item["podcat"])]"; $str.="[($item["id"])]"; $str.="=$item;"; eval($str); foreach($path[$item["podcat"]] as $pitem): $path[$item["id"]]=$pitem; endforeach; $path[$item["id"]]=$item["podcat"]; ) else ( $sort[$item["podcat"]]["sub"][$item["id"]]=$item; $path[$item["id"]]=$item["podcat" ]; ) ) endforeach; ) $this->arrayCat=$sort; return $this->arrayCat; ) /** * Prints the categories, puts the rendered HTML in $this->html * @param array Array with categories and nested subcategories * @param string Type of generated HTML to output, option or table */ function outCategory(&$arrayCat, $type="option", $idSel=0) ( foreach($arrayCat as $sub) ( $this->countPodcat++; $this->outItem($sub, $type); if(!empty($sub[" sub"]))$this->outCategory($sub["sub"], $type, $idSel); $this->countPodcat--; ) ) /** * Helper method for preparing HTML code * @param array Array with category * @param string Type of generated HTML code to output, option or table */ function outItem($sub, $type="option", $idSel=0) ( for($i=0;$icountPodcat;$i++) ($out. ="-"; ) if($idSel==$sub["id"])$se="selected"; else $se=""; if($type=="option")$this->html.=" ($out) ($sub["name"]) "; if($type=="table")$this->html.= ($out) ($sub["name"]) HTML; ) function delCategory(&$a_tree,&$id=0) ( foreach($a_tree as $sub) ( if($sub["id"]$id and isset($sub["sub"]))$this- >delCategory($sub["sub"],$id); if($sub["id"]==$id) ( $sql="DELETE FROM ($this->table) WHERE id = "$id" LIMIT 1"; $this->DB->execute($sql); if (isset($sub["sub"])) $this->delCategory_process($sub["sub"]); ) ) ) function delCategory_process (&$a_tree) ( foreach($a_tree as $sub) ( $sql="DELETE FROM ($this->table) WHERE id = "($sub["id"])" LIMIT 1"; $this-> DB->execute($sql); if(isset($sub["sub"]))$this->delCategory_process($sub["sub"]); ) ) function updateItem() ( $name=$this- >PHP_slashes(strip_tags($_POST["name"])); $podcat=intval($_POST["podcat"]); $id=intval($_POST["id"]); $sql="UPDATE `( $this->table)` SET `name` = "($name)",`podcat` = "($podcat)" WHERE `id`="($id)" LIMIT 1; "; $this->DB ->execute($sql); ) function addItem() ( $name=$this->PHP_slashes(strip_tags($_POST["name"])); $podcat=intval($_POST["podcat"]); $ id=intval($_POST["id"]); $sql="I NSERT INTO `($this->table)` (`id`,`podcat`,`name`) VALUES ("", "$podcat", "$name");"; $this->DB->execute($sql); ) function deleteItem($id) ( $id=intval($id); $sql="DELETE FROM `($this->table)` WHERE `id` = "($id)" LIMIT 1"; $DB- >execute($sql); header("Location: ?component=($this->component)"); ) function PHP_slashes($string,$type="add") ( if ($type == "add") ( if (get_magic_quotes_gpc()) ( return $string; ) else ( if (function_exists("addslashes")) ( return addslashes($string); ) else ( return mysql_real_escape_string($string); ) ) ) else if ($type == "strip") ( return stripslashes($string); ) else ( die("error in PHP_slashes (mixed,add | strip)"); ) ) )

The whole class was written within an hour and, of course, has flaws, but all this is fixable. Its use is advisable for educational purposes, although by the way, having finished it a little, you can embed it into any system and enjoy its work)).

I would be grateful if in the comments you offer your own options for solving this problem - organizing categories of an infinite nesting level.