Привет!
Сегодня разберем такую тему как добавляются пользовательские типы данных в WordPress.
Чтобы добавить пользовательский тип данных можно использовать следующий код
1 2 3 4 5 6 7 8 9 10 11 12 13 |
add_action( 'init', 'prowp_register_my_post_types' ); function prowp_register_my_post_types() { $args = array( 'public' => true, 'has_archive' => true, 'labels' => array( 'name' => 'Products222' ), 'taxonomies' => array( 'category' ), 'rewrite' => array( 'slug' => 'pppp' ),// 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'comments' ) ); register_post_type( 'products222', $args ); } |
Мы задали rewrite, значит после регистрации наши продукты доступны по ссылке вида http://wordpress.my/pppp/ .
[note]Но ссылка не доступна и выкидывает ошибку 404. Для того чтобы такого небыло нам нужно обновить постоянные ссылки в Настройки -> постоянные ссылки и нажмите сохранить изменения. Это вручную, а можно сделать и автоматический используя функцию flush_rewrite_rules(). ЕЕ вызываем из функции register_activation_hook() вызывающейся при активации плагина. [/note]
1 2 3 4 5 6 7 8 9 10 |
// вызывается когда плагин активируется register_activation_hook( __FILE__, 'simple_add_store_install' ); function simple_add_store_install() { //регистрируем новый тип данных prowp_register_my_post_types(); //сброс данных flush_rewrite_rules(); } |
При активации плагина у нас сразу обновятся постоянные ссылки после создания продукта.
Бывает часто нужно вывести наши пользовательские типы, например на главной странице или в какой то категории, для этого существует специальный хук
1 2 3 4 5 6 7 8 |
add_action('pre_get_posts', 'prefix_pre_get_posts'); function prefix_pre_get_posts($query) { // if ($query->is_category) { if($query->is_home()){ $query->set('post_type', array('products222','post')); } return $query; } |
Все у нас теперь на главной странице блога где выводятся все посты, будет между постов отображаться и наш новый тип как пост.
Полностью пример в виде плагина добавления пользовательского типа
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
<?php /* Plugin Name: test-example Plugin URI: http://kselax.ru/ Description: test plagin how to create custom type Version: 1.0 Author: Hacker Kselax Author URI: http://kselax.ru License: GPLv2 */ /* Copyright 2016 Hacker Kselax (email : neovich@mail.ua) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ // вызывается когда плагин активируется register_activation_hook( __FILE__, 'test_store_install' ); function test_store_install() { //регистрируем новый тип данных test_register_my_post_types(); //сброс данных flush_rewrite_rules(); } //добавляем пользовательский тип add_action( 'init', 'test_register_my_post_types' ); function test_register_my_post_types() { $args = array( 'public' => true, 'has_archive' => true, 'labels' => array( 'name' => 'Products333' ), 'taxonomies' => array( 'category' ), 'rewrite' => array( 'slug' => 'kkkk' ), 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'comments' ) ); register_post_type( 'products333', $args ); } // выводим посты на главной странице add_action('pre_get_posts', 'test_pre_get_posts'); function test_pre_get_posts($query) { if($query->is_home()){ $query->set('post_type', array('products333','post')); } return $query; } |