На работе мы ранее использовали KBPublisher для управления нашей базой знаний. Это стоило денег, его было сложно стилизовать, код был зашифрован с помощью ионного куба и т. Д., В основном, очень трудно поддерживать. WordPress может делать то же самое и даже лучше.
Из этого туториала Вы узнаете, как использовать пользовательские таксономии для разделов базы знаний и пользовательские публикации для статей базы знаний.
Шаг 1 Администрирование
Разделы базы знаний и статьи должны управляться. В WordPress это легко сделать с помощью пользовательских таксономий и пользовательских типов записей.
Просто зарегистрируйте новую таксономию и тип сообщения. Добавьте следующее в functions.php из вашей темы.
Для получения дополнительной информации о плюсах и минусах этой функции прочитайте наши другие статьи о пользовательских типах сообщений и пользовательских таксономиях .
|
01
02
03
04
05
06
07
08
09
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
|
function register_kb() {
register_post_type( ‘knowledgebase’,
array(
‘labels’ => array(
‘name’ => ‘Knowledge Base’,
‘menu_name’ => ‘Knowledge Base’,
‘singular_name’ => ‘Article’,
‘all_items’ => ‘All Articles’
),
‘public’ => true,
‘publicly_queryable’ => true,
‘show_ui’ => true,
‘show_in_menu’ => true,
‘show_in_nav_menus’ => true,
‘menu_position ‘ => 20,
‘supports’ => array( ‘title’, ‘editor’, ‘author’, ‘thumbnail’, ‘comments’, ‘post-formats’, ‘revisions’ ),
‘hierarchical’ => false,
‘taxonomies’ => array( ‘section’ ),
‘has_archive’ => true,
‘rewrite’ => array( ‘slug’ => ‘knowledgebase’, ‘hierarchical’ => true, ‘with_front’ => false )
)
);
register_taxonomy( ‘section’, array( ‘knowledgebase’ ),
array(
‘labels’ => array(
‘name’ => ‘Sections’,
‘menu_name’ => ‘Sections’,
‘singular_name’ => ‘Section’,
‘all_items’ => ‘All Sections’
),
‘public’ => true,
‘hierarchical’ => true,
‘show_ui’ => true,
‘rewrite’ => array( ‘slug’ => ‘knowledgebase-section’, ‘hierarchical’ => true, ‘with_front’ => false ),
)
);
}
add_action( ‘init’, ‘register_kb’ );
function kb_rewrite_rules( $wp_rewrite ) {
$new_rules = array( ‘knowledgebase/(.*)/(.*)’ => ‘index.php?post_type=knowledgebase§ion=’ . $wp_rewrite->preg_index( 1 ) . ‘&knowledgebase=’ . $wp_rewrite->preg_index( 2 ) );
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action( ‘generate_rewrite_rules’, ‘kb_rewrite_rules’ );
|
Это запустится после того, как WordPress завершит загрузку, но перед отправкой любых заголовков, регистрируя тип поста и таксономию. Также будут добавлены правила перезаписи для постоянных ссылок таксономии и типа записей.
register_post_type регистрирует пользовательский тип записи, это используется для статей базы знаний. register_taxonomy регистрирует пользовательскую таксономию, это используется для разделов KB. Статьи не будут иерархическими, а разделы будут, так что это дает возможность создать древовидную структуру.
Также было бы неплохо показать разделы, которым назначена статья.
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
|
function kb_columns( $defaults ) {
$defaults[‘section’] = ‘Sections’;
return $defaults;
}
add_filter( ‘manage_knowledgebase_posts_columns’, ‘kb_columns’ );
function kb_custom_column( $column_name, $post_id ) {
$taxonomy = $column_name;
$post_type = get_post_type( $post_id );
$terms = get_the_terms( $post_id, $taxonomy );
if ( !empty( $terms ) ) {
foreach ( $terms as $term ) {
$post_terms[] = «<a href=’edit.php?post_type={$post_type}&{$taxonomy}={$term->slug}’> » .
}
echo join( ‘, ‘, $post_terms );
}
else echo ‘<i>No terms.</i>’;
}
add_action( ‘manage_knowledgebase_posts_custom_column’, ‘kb_custom_column’, 10, 2 );
|

Теперь добавьте несколько разделов и статей, чтобы было что показать.
Шаг 2 Отображение разделов
Добавьте следующее в functions.php из вашей темы.
|
01
02
03
04
05
06
07
08
09
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
|
function kb_sections( $sections = array(), $active_section = null ) {
$taxonomy = ‘section’;
$link_class = »;
if ( empty( $sections ) ) {
$link_class = ‘root’;
$sections = get_terms( $taxonomy, array( ‘parent’ => 0, ‘hide_empty’ => 0 ) );
$active_section = kb_active_section();
echo ‘<ul id=»kb-sections» class=»unstyled»>’;
}
if ( empty( $active_section ) ) {
$active_section = »;
}
foreach ( $sections as $section ) {
$toggle = »;
$section_children = get_terms( $taxonomy, array( ‘parent’ => $section->term_id, ‘hide_empty’ => 0 ) );
if ( !empty( $section_children ) && $link_class != ‘root’ ) {
$toggle = ‘<i class=»toggle»></i>’;
}
echo ‘<li class=»‘ . ( $section->term_id == $active_section ? ‘active’ : » ) . ‘»>’;
echo ‘<a href=»‘ . get_term_link( $section, $taxonomy ) . ‘» class=»‘ . $link_class . ‘» rel=»‘ . $section->slug . ‘»>’ .
if ( !empty( $section_children ) ) {
echo ‘<ul id=»‘ . $section->slug . ‘» class=»children»>’;
kb_sections( $section_children, $active_section );
}
echo «</li>»;
}
echo «</ul>»;
}
function kb_active_section() {
$taxonomy = ‘section’;
$current_section = »;
if ( is_single() ) {
$sections = explode( ‘/’, get_query_var( $taxonomy ) );
$section_slug = end( $sections );
if ( $section_slug != » ) {
$term = get_term_by( ‘slug’, $section_slug, $taxonomy );
} else {
$terms = wp_get_post_terms( get_the_ID(), $taxonomy );
$term = $terms[0];
}
$current_section = $term->term_id;
} else {
$term = get_term_by( ‘slug’, get_query_var( $taxonomy ), get_query_var( ‘taxonomy’ ) );
$current_section = $term->term_id;
}
return $current_section;
}
|
В папке темы создайте файл с именем kb_sections где будет вызываться ваша функция kb_sections , выводя неупорядоченный и вложенный список разделов.
|
1
|
<?php kb_sections();
|
Таким образом, разделы базы знаний могут быть показаны везде, где нужно, включая боковую панель.
|
1
|
<?php get_sidebar( ‘sections’ );
|
Шаг 3 Отображение статей
Добавьте следующее в functions.php из вашей темы.
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
|
function kb_article_permalink( $article_id, $section_id ) {
$taxonomy = ‘section’;
$article = get_post( $article_id );
$section = get_term( $section_id, $taxonomy );
$section_ancestors = get_ancestors( $section->term_id, $taxonomy );
krsort( $section_ancestors );
$permalink = ‘<a href=»/knowledgebase/’;
foreach ($section_ancestors as $ancestor):
$section_ancestor = get_term( $ancestor, $taxonomy );
$permalink.= $section_ancestor->slug .
endforeach;
$permalink.= $section->slug .
return $permalink;
}
|
Примечание: этот метод необходим, потому что статья может быть связана с несколькими разделами.
Это создаст иерархическую структуру постоянных ссылок.
Как: /knowledgebase/section-slug/sub-section-slug/another-sub-section-slug/article-slug
Затем в папке темы создайте следующие файлы: archive-Knowledgebase.php , single-Knowledgebase.php , content-Knowledgebase.php , таксономия-section.php .
В архиве KnowledgeBase.php добавить следующее, чтобы показать разделы и последние статьи.
|
01
02
03
04
05
06
07
08
09
10
|
<?php
get_header();
get_sidebar( ‘sections’ );
while ( have_posts() ) : the_post();
$terms = wp_get_post_terms( $post->ID, ‘section’ );
$term = $terms[0];
echo kb_article_permalink( $post->ID, $term->term_id );
endwhile;
get_footer();
?>
|
В single-Knowledgebase.php добавить следующее.
|
1
2
3
4
5
6
7
|
<?php
get_header();
while ( have_posts() ) : the_post();
get_template_part( ‘content’, ‘knowledgebase’ );
endwhile;
get_footer();
?>
|
В content-Knowledgebase.php добавить следующее.
|
1
2
3
4
5
|
<?php
get_sidebar( ‘sections’ );
the_title();
the_content();
?>
|
В taxonomy-section.php добавьте следующее, чтобы показать список статей из раздела.
|
01
02
03
04
05
06
07
08
09
10
11
12
13
|
<?php
global $wp_query;
$args = array_merge( $wp_query->query, array( ‘posts_per_page’ => 100 ) );
query_posts( $args );
$term = get_term_by( ‘slug’, get_query_var( ‘term’ ), ‘section’ );
get_header();
get_sidebar( ‘sections’ );
while ( have_posts() ) : the_post();
echo kb_article_permalink( $post->ID, $term->term_id );
endwhile;
get_footer();
?>
|
Это может быть структурировано и стилизовано по желанию.
пример
Реальный пример того, как это работает и как это можно использовать: syneto.net