Шпаргалка по интеграции на WordPress

Эта шпаргалка без заморочек для тех, кто уже знает как интегрировать HTML шаблон на систему управления WordPress. Здесь нет пошаговой инструкции и объяснения кода. Эта страница создана для себя, чтобы каждый раз не копировать один и тот же код при натяжке верстки. Страница будет дополняться.

Стартовый пустой шаблон Wordpress для натяжки верстки

Скачать — прямая ссылка
underscores.me — также можно скачать здесь, задав своё имя шаблона

  • Удаляем все стили из файла style.css шаблона
  • Переносим все файлы и папки верстки в папку шаблона

Подключение своих стилей и скриптов в файле functions.php в WordPress


function load_style_script()
{
	wp_enqueue_style('qam-css', get_template_directory_uri() .  '/css/main.min.css');

	/*-------------------------------------------------*/
	
	wp_deregister_script('jquery-core');
	wp_deregister_script('jquery');
	wp_register_script('jquery-core', get_template_directory_uri() . '/js/jquery.js', false, null, true);
	wp_register_script('jquery', false, array('jquery-core'), null, true);
	wp_enqueue_script('jquery');

	wp_enqueue_script('qam-js', get_template_directory_uri() . '/js/app.min.js', array('jquery'), true);

}
add_action('wp_enqueue_scripts', 'load_style_script');

Создание шаблона страницы WordPress 


<?php
/*
Template Name: Моя страница шаблона
*/
get_header();
?>

Контент

<?php
get_footer();

Получаем URL до родительского шаблона

Прописываем путь до любого файла который находится в папке шаблона, так как все файлы верстки мы скинули в эту папку.


<?php echo get_template_directory_uri(); ?>

Пример:


<img src="<?php echo get_template_directory_uri(); ?>/images/dist/logo.svg" alt="">

Регистрация меню WordPress

В файле functions.php прописываем следующее:


add_action( 'after_setup_theme', function(){ 
register_nav_menus( [ 
'header_menu' => 'Меню в шапке',
'footer_menu' => 'Меню в подвале' ] );
 } );

Чтобы удалить контейнер у всех навигационных меню сразу, используем следующий код:


add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );
function my_wp_nav_menu_args( $args = '' ){ 
$args['container'] = false; return $args; 
}

Выводим меню в шаблоне:


<?php wp_nav_menu( [
'theme_location'  => 'header_menu'
] ); ?>

Как вставить шорткод внутри html документа WordPress


<?php echo do_shortcode('[ваш шорткод]'); ?>

Создаем таксономию и кастомный тип записей

в файл functions.php добавляем

// Register Custom Taxonomy
function collection_category_taxonomy() {

	$labels = array(
		'name'                       => _x( 'Service Categories', 'Taxonomy General Name', 'text_domain' ),
		'singular_name'              => _x( 'Категория', 'Taxonomy Singular Name', 'text_domain' ),
		'menu_name'                  => __( 'Категории услуг', 'text_domain' ),
		'all_items'                  => __( 'All Items', 'text_domain' ),
		'parent_item'                => __( 'Parent Item', 'text_domain' ),
		'parent_item_colon'          => __( 'Parent Item:', 'text_domain' ),
		'new_item_name'              => __( 'Новая категория', 'text_domain' ),
		'add_new_item'               => __( 'Добавить категорию услуг', 'text_domain' ),
		'edit_item'                  => __( 'Редактировать категорию', 'text_domain' ),
		'update_item'                => __( 'Обновить категорию', 'text_domain' ),
		'view_item'                  => __( 'Посмотреть категорию', 'text_domain' ),
		'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ),
		'add_or_remove_items'        => __( 'Add or remove items', 'text_domain' ),
		'choose_from_most_used'      => __( 'Choose from the most used', 'text_domain' ),
		'popular_items'              => __( 'Popular Items', 'text_domain' ),
		'search_items'               => __( 'Search Items', 'text_domain' ),
		'not_found'                  => __( 'Not Found', 'text_domain' ),
		'no_terms'                   => __( 'No items', 'text_domain' ),
		'items_list'                 => __( 'Items list', 'text_domain' ),
		'items_list_navigation'      => __( 'Items list navigation', 'text_domain' ),
	);
	$rewrite = array(
		'slug'                       => 'services',
		'with_front'                 => true,
		'hierarchical'               => false,
	);
	$args = array(
		'labels'                     => $labels,
		'hierarchical'               => true,
		'public'                     => true,
		'show_ui'                    => true,
		'show_admin_column'          => true,
		'show_in_nav_menus'          => true,
		'show_tagcloud'              => false,
		'rewrite'           => array( 'slug' => 'services' ),
	);
	register_taxonomy( 'collection_categories', array( 'collections' ), $args );

}
add_action( 'init', 'collection_category_taxonomy', 0 );



// Register Custom Post Type
function collection_post_type() {

	$labels = array(
		'name'                  => _x( 'Услуги', 'Post Type General Name', 'text_domain' ),
		'singular_name'         => _x( 'Услуга', 'Post Type Singular Name', 'text_domain' ),
		'menu_name'             => __( 'Услуги', 'text_domain' ),
		'name_admin_bar'        => __( 'Услуги', 'text_domain' ),
		'archives'              => __( 'Item Archives', 'text_domain' ),
		'attributes'            => __( 'Item Attributes', 'text_domain' ),
		'parent_item_colon'     => __( 'Parent Item:', 'text_domain' ),
		'all_items'             => __( 'Все Услуги', 'text_domain' ),
		'add_new_item'          => __( 'Add New Item', 'text_domain' ),
		'add_new'               => __( 'Добавить услугу', 'text_domain' ),
		'new_item'              => __( 'Новая услуга', 'text_domain' ),
		'edit_item'             => __( 'Редактировать услугу', 'text_domain' ),
		'update_item'           => __( 'Обновить услугу', 'text_domain' ),
		'view_item'             => __( 'Посмотреть услугу', 'text_domain' ),
		'view_items'            => __( 'Посмотреть услуги', 'text_domain' ),
		'search_items'          => __( 'Поиск услуги', 'text_domain' ),
		'not_found'             => __( 'Not found', 'text_domain' ),
		'not_found_in_trash'    => __( 'Not found in Trash', 'text_domain' ),
		'featured_image'        => __( 'Featured Image', 'text_domain' ),
		'set_featured_image'    => __( 'Set featured image', 'text_domain' ),
		'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
		'use_featured_image'    => __( 'Use as featured image', 'text_domain' ),
		'insert_into_item'      => __( 'Insert into item', 'text_domain' ),
		'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
		'items_list'            => __( 'Items list', 'text_domain' ),
		'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
		'filter_items_list'     => __( 'Filter items list', 'text_domain' ),
	);
	$args = array(
		'label'                 => __( 'Service', 'text_domain' ),
		'description'           => __( 'Service Post Type', 'text_domain' ),
		'labels'                => $labels,
		'supports'              => array( 'title', 'editor', 'thumbnail', 'revisions', 'custom-fields' ),
		'taxonomies'            => array( 'collection_categories' ),
		'hierarchical'          => false,
		'public'                => true,
		'show_ui'               => true,
		'show_in_menu'          => true,
		'menu_position'         => 5,
		'menu_icon'             => 'dashicons-images-alt2',
		'show_in_admin_bar'     => true,
		'show_in_nav_menus'     => true,
		'can_export'            => true,
		'has_archive'           => false,
		'exclude_from_search'   => false,
		'publicly_queryable'    => true,
		'capability_type'       => 'page',
	);
	register_post_type( 'service', $args );

}
add_action( 'init', 'collection_post_type', 0 );

Вывод записей кастового пост тайпа

$args = array('post_type' => 'service', 'posts_per_page' => 5, 'taxonomy' => 'collection_categories');
$myposts = get_posts($args);
foreach ($myposts as $post) {
setup_postdata($post);
php the_title(); }
wp_reset_postdata();

Оцените автора
Qamos
Добавить комментарий