wp_nav_menu()
get_posts()
и wp_insert_post()
// получаем данные исходного поста по слагу
$post_slug = '1543';
$args = array( 'name' => $post_slug, 'post_type' => 'post', 'post_status' => 'publish, draft, future', 'numberposts' => 1 );
$post = get_posts($args)[0];
for ( $i = 1; $i < 2771; $i++ ) {
// Создаем массив данных новой записи
$post_data = array(
'ID' => $post->ID++,
'post_title' => $post->post_title,
'post_name' => $post_slug . '-' . $i,
'post_date' => $post->post_date,
'post_date_gmt' => $post->post_date_gmt,
'post_content' => $post->post_content,
'post_status' => 'publish',
'post_type' => 'post',
'post_author' => 1,
);
// Вставляем запись в базу
$post_id = wp_insert_post( wp_slash( $post_data ) );
// пишем ошибку/успех
if( is_wp_error( $post_id ) ) {
var_dump( 'Ошибка инсерта поста ' . $post->post_title . ' таксономии category: ' . $post_id->get_error_message() );
} else {
var_dump( 'Пост ' . $post->post_title . ' таксономии category опубликован удачно!' );
//wp_set_object_terms( $post_id, 'cat_id', 'category' ); // если нужно назначить категорию, заменить cat_id
}
}
<?php echo do_shortcode( '[shortcode var="' . $var . '"]' ); ?>
add_shortcode()
вам нужно добавить var в список атрибутов шорткода, чтобы использовать ее. Пример #1.2 тут $descriptionJson = json_decode(file_get_contents($path), true);
$titles = array();
foreach ( $descriptionJson as $key => $descriptionJsonValue ) {
$titles[] = $descriptionJsonValue['title'];
}
$count = count($requests); // получаем кол-во объектов для ключа
foreach ( $requests as $key => $request ) {
if ( array_search($request->title, $titles) == false ) {
$count++;
$descriptionJson[$count]['title'] = $request->title;
$descriptionJson[$count]['thumbnail'] = ImageGenerator::imageDescriptions($request->file('photo'));
$descriptionJson[$count]['descriptions'] = $request->description;
}
}
$product->descriptions = json_encode($descriptionJson);
$product->save();
$arr1 = [
1 => ['id' => 1, 'name' => 'DJ'],
2 => ['id' => 2, 'name' => 'Bass'],
3 => ['id' => 3, 'name' => 'Vocal'],
];
$arr3 = array();
foreach ( $arr1 as $key => $arr1_value ) {
$arr3[$arr1_value['id']] = $arr1_value['name'];
}
$arr2 = [
['name' => 'Alex', 'specId' => 1],
['name' => 'Tim', 'specId' => 2],
['name' => 'Dave', 'specId' => 3],
];
echo '<ul>';
foreach ( $arr2 as $key => $arr2_value ) {
echo '<li>' . $arr3[$arr2_value['specId']] . '</li>';
}
echo '</ul>';
woocommerce_product_subcategories()
запрещена (устарела) с версии 3.3.1if ( is_product_category() ) {
$term = get_queried_object();
$taxonomy = $term->taxonomy;
echo '<h3>Категория: ' . $term->name . '<h3>'; // выводим текущую категорию
// получаем дочерние, если существуют
if ( $term_children = get_term_children( $term->term_id, $taxonomy ) ) {
echo '<ul>';
foreach ( $term_children as $key => $term_child ) {
$term_child = get_term_by( 'id', $term_child, $taxonomy );
// выводим дочерние
echo '<li><a href="' . get_term_link( $term_child->term_id, $taxonomy ) . '">' . $term_child->name . '</a></li>';
}
echo '</ul>';
}
}
// проверяем наличие тегов
if ( has_tag() ) {
$tags = wp_get_post_tags( get_the_ID() );
$tags_array = array();
foreach ( $tags as $key => $tag ) {
$tags_array[] = $tag->term_id; // собираем в массив
}
$args = array (
'post_type' => 'post',
'tag__in' => $tags_array, // получаем посты, имеющие такой же тег
'post__not_in' => array( get_the_ID() ), // исключаем текущий пост
'posts_per_page' => 3,
'orderby' => rand
);
} else {
// или получаем любые последние посты
$args = array (
'post_type' => 'post',
'posts_per_page' => 3,
'orderby' => date
);
}
pre_get_posts
с условием $query->is_front_page() && $query->is_main_query()
pre_get_posts
установить для него значение не равное true:if( $query->is_front_page() && $query->is_main_query() ) {
$query->set( 'meta_key', 'custom_hide_post' );
$query->set( 'meta_value', 'true' );
$query->set( 'meta_compare', '!=' );
}
the_views()
уже имеет echo. Вообще кодстайл ВП подразумевает, что функции с префиксом the_ отвечают за вывод контента с помощью echo, а с префиксом get_ за получение данных для дальнейшей обработки, т.е. returnecho '<span class="postviews">';
the_views();
echo '</span>';
sanitize_title()
; Но некоторые спецсимволы будут конвертированы в юникод-формат вида %2С и т.д. Лучше всего декодировать их с помощью urldecode()
и удалить из строки все символы за исключением латинских букв, цифр, дефиса и нижнего подчеркивания$post_slug = urldecode( sanitize_title($post_title) );
$post_slug = preg_replace('/([^a-z\d\-\_])/', '', $post_slug);
remove_action()
и add_action()
$post_date = get_the_date( "Y-m-d" ); // дата поста
$current_time = date( "Y-m-d H:i:s" ); // текущее время
$post_date_unix = strtotime($current_time); // Unix
$future_time = date( "Y-m-d H:i:s", strtotime($current_time . ' + 3 hours') ); // +3 часа от текущего времени