- Saved searches
- Use saved searches to filter your results more quickly
- beaucharman/wordpress-custom-post-types
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Custom post types php
- Summary
- Exercises
- Quiz
- Создаем кастомный тип записи (Custom Post Type) с кастомными категориями (Custom Taxonomy)
- Вариант 1 — самый правильный. Выводим записи в таксономии так же как и в обычной категории.
- Вариант 2 — если нет кастомных таксономий, то можно просто получить все кастомные записи в виде Архива
- Вариант 3. Просто выводим все кастомные записи Articles на странице с заданным шаблоном
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A PHP class to help register and maintain WordPress custom post types. It also comes with some rad built in properties and methods that can be used in templates to maintain clean code modular development.
beaucharman/wordpress-custom-post-types
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
WordPress Custom Post Types
Bamboo — WordPress Custom Post Types is a PHP class to help register and maintain WordPress custom post types. It also comes with some rad built-in properties and methods that can be used in templates to maintain clean code and modular development.
For more information about registering post types, including a full list of options, visit the WordPress Codex.
This class works well with the WordPress Custom Taxonomy class. They were made for each other
Include custom-post-type.php in your functions.php file, with something like require_once(get_template_directory() . ‘/includes/custom-post-types.php’); .
Declare the various argument arrays (within funtions.php or another include file) to setup the new post type as needed ( name is required):
// required $args['name'] = ''; // optional $args['labels'] = array( 'singular' => '', 'plural' => '', 'menu' => '' ); $args['options'] = array( 'public' => true, 'hierarchical' => false, 'supports' => array('title', 'editor', 'thumbnail'), 'has_archive' => true ); $args['menu_icon'] = ''; // The Unicode of the desired font $args['help'] = array( array( 'message' => '' ), array( 'context' => 'edit', 'message' => '' ) );
Then create a variable (for future reference, but is not required) from an instance of the bamboo_Custom_Post_Type class:
$PostType = new Bamboo_Custom_Post_Type($args);
You can even quick declare a Post Type by just passing the name as a string. So for a Post Type of movie, just pass:
$Movie = new Bamboo_Custom_Post_Type('movie');
The custom post type class creates a handfull of useful properties and methods that can be accessed through the post type’s instance variable and can be used in template and admin files.
$PostType->name
$PostType->lables
An array of the singular, plural and menu lables.
$PostType->get()
Get all entries assigned to this post type. Accepts an array of arguments, and a boolean value to retrieve just a single value (true, useful to use along side ‘include’ => $single_id ) or an array of results (false).
Note: A declaration of global $PostType; might be required on some template files to make use of the required post type’s instance.
See the Get Posts => Default Usage codex reference for the list of possible arguments, and the Get Pages => Return codex reference for the list of return values.
get_font_awesome()
To utilise the menu_icon feature of this class, Font Awesome needs to be reference, and there is nice helper function included in Bamboo that will include Font Awesome in the admin for you. Just call the method before declareing any post types:
/* Include Font Awesome */ Bamboo_Custom_Post_Type::get_font_awesome();
Working with Custom Taxonomies
To get posts within (or maybe even not within) terms of particular taxonomies, you can use the Tax Query option within your get function’s $args . For example:
$args = array( 'tax_query' => array( array( 'taxonomy' => 'foo_category_slug', 'field' => 'bar_term_slug', 'terms' => array('qux', 'baz'), 'include_children' => true, 'operator' => 'IN' ) ) ); $post_types = $PostType->get($args);
If there are issues with permalinks and the new post types, even after flushing them in the administrator area (Settings > Permalinks > Save Changes), use the following function to flush permalink rewrites for new custom post types and taxonomies.
add_action('init', 'bamboo_flush_rewrites'); function bamboo_flush_rewrites() < global $wp_rewrite; $wp_rewrite->flush_rules(); >
About
A PHP class to help register and maintain WordPress custom post types. It also comes with some rad built in properties and methods that can be used in templates to maintain clean code modular development.
Custom post types php
Tip: Feel free to read the dashboard icons lesson to learn how to customize the icon added for your new post type.
Summary
A custom post type is a regular post with a different post_type value in the database which is designed to hold a type of content different from standard posts and pages. You should think about creating a custom post type when you want your new content type to be different in looks, meaning, and content from the post types you already have registered on your site. Ideally, you should create a plugin when you need custom post types, but you also can modify your theme’s functions.php file. The basic modification resembles the following piece of code:
function my_custom_post_type() < $args = array(); register_post_type( 'custom_post', $args ); >add_action( 'init', 'my_custom_post_type' );
Arguments should be modified when you need your post to be public, displayed in the admin dashboard, and/or further customized.
Exercises
Using the lesson’s materials and arguments section in the Code Reference create a new post type «Movie Review» with the following characteristics:
- public
- displayed in the admin dashboard under «Comments»
- supporting comments
- no archive
- [additional task] using the video icon from Dashicons
Quiz
A short quiz for students to evaluate their retention of the material presented.
What best describes the situation when you need to create a custom post type?
- You need to create a portfolio site
- You want your items to be ordered chronologically
- Your new content type is different in looks, meaning, and content
Answer: 3.Your new content type is different in looks, meaning, and content
Which of the following is the main benefit of creating your custom post type as a new plugin?
Answer: 1. Portability
Создаем кастомный тип записи (Custom Post Type) с кастомными категориями (Custom Taxonomy)
Создаем кастомный тип записи (Custom Post Type) Articles с кастомными категориями (Custom Taxonomy) Articles Category.
[vc_row][vc_column][vc_message color=»alert-warning» message_box_color=»alert-warning» icon_type=»pixelicons» icon_pixelicons=»vc_pixel_icon vc_pixel_icon-alert»]Это будет наиболее полезная статья по Custom Post Type[/vc_message][/vc_column][/vc_row]В моем случае все стандартные записи — это Товары, поэтому Статьи выведем через кастомные записи.
В файле функций functions.php регистрируем кастомный тип записи Articles:
function wptp_create_post_type() < $labels = array( 'name' =>__( 'Articles' ), 'singular_name' => __( 'Articles' ), 'add_new' => __( 'New Article' ), 'add_new_item' => __( 'Add New Article' ), 'edit_item' => __( 'Edit Article' ), 'new_item' => __( 'New Article' ), 'view_item' => __( 'View Article' ), 'search_items' => __( 'Search Articles' ), 'not_found' => __( 'No Articles Found' ), 'not_found_in_trash' => __( 'No Articles found in Trash' ), ); $args = array( 'labels' => $labels, 'has_archive' => true, 'public' => true, 'hierarchical' => false, 'menu_position' => 5, 'supports' => array( 'title', 'editor', 'excerpt', 'custom-fields', 'thumbnail' ), ); register_post_type( 'articles', $args ); > add_action( 'init', 'wptp_create_post_type' );
Если вы хотите, чтобы в кастомных постах выводились стандартные категории, тогда привяжите их к таксономии Категорий:
'taxonomies' => array('category'),
Если для кастомных постов вы создаете еще и кастомные таксономии, то связывать их надо с созданными таксономиями, если брать пример ниже, то это будут articles_category
'taxonomies' => array('articles_category'),
Затем для кастомного типа записи Articles регистрируем таксономии ‘Article Category’, чтобы разные записи могли принадлежать разным категориям.
function wptp_register_taxonomy() < register_taxonomy( 'articles_category', 'articles', array( 'labels' =>array( 'name' => 'Article Categories', 'singular_name' => 'Article Category', 'search_items' => 'Search Article Categories', 'all_items' => 'All Article Categories', 'edit_item' => 'Edit Article Categories', 'update_item' => 'Update Article Category', 'add_new_item' => 'Add New Article Category', 'new_item_name' => 'New Article Category Name', 'menu_name' => 'Article Category', ), 'hierarchical' => true, 'sort' => true, 'args' => array( 'orderby' => 'term_order' ), 'show_admin_column' => true ) ); > add_action( 'init', 'wptp_register_taxonomy' );
Для кастомной таксономии можно изменить слаг на более красивый, чтобы он не был articles_category , но нужно учесть, чтобы таких слдагов больше не было на других страницах или постах, иначе будут проблемы:
'rewrite' => array( 'slug' => 'blog' ),[vc_row][vc_column][vc_message color=»alert-warning» message_box_color=»alert-warning» icon_type=»pixelicons» icon_pixelicons=»vc_pixel_icon vc_pixel_icon-alert»]При изменении слагов необходимо обновить настройки «Постоянных ссылок» в админке, иначе будете получать 404 ошибку вместо нужной страницы.[/vc_message][/vc_column][/vc_row]
Больше примеров можно найти здесь и здесь. Но привести весь этот код в порядок помогла эта статья, за что автору большая благодарность.
За внешний вид кастомной записи отвечает файл single.php , но чтобы изменить вид кастомной записи можно создать файл single-.php — в моем случае будет single-articles.php со своим содержимым.
Теперь нужно вывести кастомные записи на странице. По умолчанию за отображение архива кастомных записей отвечает файл index.php . Но можно создать файл, который будет отвечать за вывод кастомных записей в своей таксономии.
Вариант 1 — самый правильный. Выводим записи в таксономии так же как и в обычной категории.
Для этого создаем файл taxonomy-.php — в моем случае будет taxonomy-articles_category.php и в нем выводим обычный цикл, как и для стандартных записей в категории:
В файле tax-item.php выводим данные, которые нам нужно получить из каждой записи, например, заголовок, ссылку на запись, миниатюру и excerpt.
В файле pagination.php выводим пагинацию вот такого формата.
Цикл не изменяем, пагинация отлично работает. Это самый оптимальный вариант для отображения Кастомных Таксономий.
Вариант 2 — если нет кастомных таксономий, то можно просто получить все кастомные записи в виде Архива
Для этого в шаблоне создаем файл archive-.php — в моем случае будет archive-articles.php , в котором точно так же как и в таксономии выводим обычный цикл, только вместо заголовка Таксономии выводим имя кастомного типа записи :
При этом варианте, если не создана страница архива для кастомной записи, тогда получить список всех кастомных записей можно по прямой ссылке BLOG_URL?post_type= или в моем случае http://site.com/articles/ .
Вариант 3. Просто выводим все кастомные записи Articles на странице с заданным шаблоном
'articles', 'posts_per_page' => -1 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); get_template_part( 'include/tax-item' ); endwhile; ?>
get_template_part( ‘include/tax-item’ ); — в файле tax-item.php я вывожу содержимое записи, которое нужно мне для отображения записей внутри цикла (заголовок, миниатюру, дату, цитату и т.д.)
Этот вариант выводит все записи Articles на странице, не зависимо от таксономий (категорий).
А если нам нужно вывести каждую категорию отдельно со своими новостями, тогда используем первый вариант, описанный выше.
При этом, если вы используете плагин Yoast SEO и используете его хлебные крошки:
Тогда при выборе в настройках плагина таксономии «Articles Category» в «Taxonomy to show in breadcrumbs for post types», в хлебных крошках вы получите ссылку на категорию, к которой принадлежит Новость, при других вариантах вывода кастомных записей это не получалось сделать.
Решение нашел на сайте byheart.ru wp-admin/upgrade.php ?_wp_http_referer= %2Fwp-admin%2F Ошибка wp-admin/upgrade.php ?_wp_http_referer=wp-admin появилась, когда произвел обновление…
Суть задачи — у нас есть записи с дополнительными полями, в которых указан рейтинг записи,…
Получает массив данных о категориях относящихся к указанному посту. Функцию можно использовать за пределами Цикла…
Выводим 8 самых просматриваемых записей. Количество просмотров каждой записи считает плагин Post Views Counter. Небольшое…