wp_nav_menu()
есть фильтр wp_nav_menu_items
<li id="menu-item-265" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-265">
<a href="http://wp-test.ru/post-99">Обратная связь</a>
</li>
<li id="menu-item-266" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-266">
<a href="http://wp-test.ru/post-98">Все статьи</a>
</li>
wp_get_nav_menu_items()
и вывести свою разметку// Получаем элементы меню по ID.
$nav_menu_items = wp_get_nav_menu_items( $menu_id );
// Или получаем элементы меню по location.
$menu_location = 'primary';
$locations = get_nav_menu_locations();
if ( isset( $locations[ $menu_location ] ) ) {
$nav_menu_items = wp_get_nav_menu_items( $locations[ $menu_location ] );
}
register_post_type()
или использовать WooCommerce, плагин для интернет-магазинов$products = array(
1 => array(
'category' => 'NP',
'title' => 'Титановое основание мидентика совместимое с mis',
'image' => 'data/product/1.jpg',
'price' => '€10',
);
2 => array(
'category' => 'SP',
'title' => 'Титановое основание мидентика non hex совместимое с mis',
'image' => 'data/product/2.jpg',
'price' => '€10',
);
3 => array(
'category' => 'WP',
'title' => 'Титановое основание мидентика совместимое с mis',
'image' => 'data/product/3.jpg',
'price' => '€10',
);
);
<div>
// Задаем нужные нам критерии выборки данных из БД.
$args = array(
'post_type' => 'projects',
'posts_per_page' => 9,
);
$query = new WP_Query( $args );
$counter = 1;
// Цикл.
if ( $query->have_posts() ) {
echo '<div>';
while ( $query->have_posts() ) {
$query->the_post();
echo '<div>' . get_the_title() . '</div>';
if ( is_int( $counter / 3 ) ) {
echo '</div>';
echo '<div>';
}
$counter++;
}
echo '</div>';
}
else {
// Постов не найдено.
}
// Возвращаем оригинальные данные поста. Сбрасываем $post.
wp_reset_postdata();
ключ => значение
с терминами, которые нужно опубликовать, получаете существующие термины get_terms()
, в цикле простой проверкой in_array()
проверяете существует ли такой термин в БД и при его отсутствии собираете набор аргументов и функцией для публикации на сайте с помощью wp_insert_category()
// Массив терминов, которые нужно добавить.
$brands = array(
'audi' => 'Audi',
'bentley' => 'Bentley',
'bmw' => 'BMW',
'cadillac' => 'Cadillac',
);
$taxonomy = 'car-brand'; // Основная таксономия.
$category_parent = 12; // Родительская категория.
// Получаем все термины таксономии.
$args = array(
'taxonomy' => $taxonomy,
'fields' => 'id=>slug',
'hide_empty' => false,
);
$terms = get_terms( $args );
foreach ( $brands as $brand_slug => $brand_title ) {
if ( ! in_array( $brand_slug, $terms, true ) ) {
$term_args = array(
'cat_name' => $brand_title,
'category_description' => '',
'category_nicename' => $brand_slug,
'category_parent' => $category_parent,
'taxonomy' => $taxonomy,
);
$term_id = wp_insert_category( $term_args );
if ( is_wp_error( $term_id ) ) {
var_dump( 'Ошибка инсерта термина ' . $brand_title . ' таксономии ' . $taxonomy . ': ' . $term_id->get_error_message() );
} else {
var_dump( 'Термин ' . $brand_title . ' таксономии ' . $taxonomy . ' опубликован удачно!' );
}
}
}
if ( ! function_exists( 'wpgen_search_highlight' ) ) {
/**
* Highlight search results.
*
* @param string $text is text for highlight.
*
* @return string
*/
function wpgen_search_highlight( $text ) {
$s = get_query_var( 's' );
if ( is_search() && in_the_loop() && ! empty( $s ) ) :
$style = 'background-color:#307FE2;color:#fff;font-weight:bold;';
$query_terms = get_query_var( 'search_terms' );
if ( ! empty( $query_terms ) ) {
$query_terms = explode( ' ', $s );
}
if ( empty( $query_terms ) ) {
return '';
}
foreach ( $query_terms as $term ) {
$term = preg_quote( $term, '/' ); // like in search string.
$term1 = mb_strtolower( $term ); // lowercase.
$term2 = mb_strtoupper( $term ); // uppercase.
$term3 = mb_convert_case( $term, MB_CASE_TITLE, 'UTF-8' ); // capitalise.
$term4 = mb_strtolower( mb_substr( $term, 0, 1 ) ) . mb_substr( $term2, 1 ); // first lowercase.
$text = preg_replace( "@(?<!<|</)($term|$term1|$term2|$term3|$term4)@i", "<span style=\"{$style}\">$1</span>", $text );
}
endif; // is_search.
return $text;
}
}
add_filter( 'the_title', 'wpgen_search_highlight' );
add_filter( 'the_content', 'wpgen_search_highlight' );
add_filter( 'the_excerpt', 'wpgen_search_highlight' );
function is_user_role( $string ) {
if ( ! function_exists( 'wp_get_current_user' ) || ! is_user_logged_in() ) {
return 'unknown';
}
$user = wp_get_current_user();
return in_array( $string, (array) $user->roles, true );
}
if ( is_user_role( 'professional' ) ) {
# Вывод для авторизованного пользователя с ролью professional
} else {
# Для всех остальных
}
function is_user_role( $string ) {
if ( ! function_exists( 'wp_get_current_user' ) || ! is_user_logged_in() ) {
return 'unknown';
}
$user = wp_get_current_user();
return in_array( $string, (array) $user->roles, true );
}
if ( is_user_role( 'employer' ) ) {
# Вывод для авторизованного пользователя с ролью employer
} else {
# Для всех остальных
}
wp_is_mobile()
, которая проверяет переменную HTTP_USER_AGENT по ключевым словам на наличие мобильного устройства у пользователя, но на нее нельзя полагаться на 100% /**
* Add postMessage support for site title and description for the Theme Customizer.
*
* @param WP_Customize_Manager $wp_customize Theme Customizer object.
*/
function wpgen_customize_register( $wp_customize ) {
//...
}
add_action( 'customize_register', 'wpgen_customize_register' );
the_title()
— выводит заголовок записиthe_author()
— выводит автора записиthe_content()
— выводит контент записиthe_post_thumbnail()
— выводит изображение записиadd_filter( 'query_vars', 'add_query_vars' );
function add_query_vars( $qvars ) {
$qvars[] = 'location';
$qvars[] = 'from';
$qvars[] = 'to';
$qvars[] = 'type';
return $qvars;
}
<form method="get" class="block obj-filter">
<div class="row d-flex align-items-center">
<div class="col-12 col-md-6 col-lg-3 col-margin-bottom-small col-lg-margin-bottom-none">
<input type="text" name="location" id="location" class="obj-filter-input" value="">
</div>
<div class="col-12 col-md-6 col-lg-3 col-margin-bottom-small col-lg-margin-bottom-none">
<input type="date" name="from" id="from" class="obj-filter-input" value="">
</div>
<div class="col-12 col-md-6 col-lg-3 col-margin-bottom-small col-lg-margin-bottom-none">
<input type="date" name="to" id="to" class="obj-filter-input" value="">
</div>
<div class="col-12 col-md-6 col-lg-3 col-margin-bottom-small col-lg-margin-bottom-none">
<select name="type" id="type" class="obj-select">
<option value="solo">Один взрослый</option>
<option value="two-adults">Два взрослых</option>
<option value="family">Двое взрослых + ребенок</option>
</select>
</div>
<div class="col-12 col-md-6 col-lg-3 col-margin-bottom-small col-lg-margin-bottom-none">
<input id="obj-filter-submit" type="submit" class="button" value="Фильтровать">
</div>
</div>
</form>
https://example.loc/?location=yerevan&from=2807&to=0408&type=solo
pre_get_posts
можно поправить основной запрос вытянув данные из гет-параметров. Вам нужно установить новые tax_query или meta_query в зависимости от логики сайтаadd_action( 'pre_get_posts', 'custom_pre_get_posts', 1 );
function custom_pre_get_posts( $query ) {
// Выходим, если это админ-панель или не основной запрос.
if ( is_admin() || ! $query->is_main_query() )
return;
// предположим, что это таксономия с машинами
if ( $query->is_tax( 'location' ) ) {
$meta = array();
$meta['meta_query']['relation'] = 'AND';
// выбираем записи с GET запросами
$query_vars = array( 'location', 'from', 'to', 'type' );
foreach ( $query_vars as $key => $query_var ) {
if ( $var = get_query_var( $query_var, false ) ) {
// Тут пишем логику по которой собирается переменная meta_query и/или tax_query
}
}
$query->set( 'meta_query', $meta );
}
}