<?php language_attributes(); ?> - выбор языковой оболочки.
1 |
<html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>> |
<?php bloginfo('stylesheet_url'); ?> - путь к файлу style.css
1 |
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" /> |
<?php bloginfo('name'); ?> - имя блога.
<?php wp_title('Привет', true, 'left'); ?> - выводит название страницы, категории.
1 |
//1 - строчка |
<?php bloginfo('stylesheet_directory'); ?> - путь к шаблону.
1 |
<?php bloginfo('stylesheet_directory'); ?> |
<?php bloginfo('html_type'); ?> - тип HTML файла.
<?php bloginfo('charset'); ?> - кодировка.
1 |
<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" /> |
<?php bloginfo('description'); ?> - описания блога.
1 |
<div class="description"><?php bloginfo('description'); ?> |
<?php echo get_option('home'); ?> - ссылка на главную страницу.
1 |
<a href="<?php echo get_option('home'); ?>/"><?php bloginfo('name'); ?></a> |
is_single() - служит для определения постов.
post_class() - получаем класс поста.
<?php the_ID(); ?> - получаем id поста, страницы.
1 |
<div <?php post_class(); ?> id="post-<?php the_ID(); ?>"> |
1 |
<?php if (have_posts()) : ?> |
<?php the_permalink() ?> - ссылка
1 |
<?php the_tags( '<p>' . __('Tags:', 'kubrick') . ' ', ', ', '</p>'); ?> - выводим теги под стаьей
|
<?php the_title(); ?> - название материала.
1 |
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a> |
<?php the_author() ?> - автор материала.
<?php the_time(__('F jS, Y', 'kubrick')) ?> - время написания.
1 |
<small><?php the_time(__('F jS, Y', 'kubrick')) ?> <!-- by <?php the_author() ?> --></small> |
<?php the_content('Прочитать остальную часть записи »'); ?> - вывод контента.
1 2 3 4 |
$content = get_extended($post->post_content); $first_content = apply_filters('the_content', $content['main']); $second_content = apply_filters('the_content', $content['extended']); echo $second_content; |
Форма комментариев
1 2 3 4 5 6 7 8 9 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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 |
if ( ! function_exists( 'twentyeleven_comment' ) ) : /** * Template for comments and pingbacks. * * To override this walker in a child theme without modifying the comments template * simply create your own twentyeleven_comment(), and that function will be used instead. * * Used as a callback by wp_list_comments() for displaying the comments. * * @since Twenty Eleven 1.0 */ function twentyeleven_comment( $comment, $args, $depth ) { $GLOBALS['comment'] = $comment; switch ( $comment->comment_type ) : case 'pingback' : case 'trackback' : ?> <li class="post pingback"> <p><?php _e( 'Pingback:', 'twentyeleven' ); ?> <?php comment_author_link(); ?><?php edit_comment_link( __( 'Edit', 'twentyeleven' ), '<span class="edit-link">', '</span>' ); ?></p> <?php break; default : ?> <li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>"> <article id="comment-<?php comment_ID(); ?>" class="comment"> <div class="com_block"> <div class="com_d"> <?php if ( '0' != $comment->comment_parent ) { ?> <div class="level_img"></div> <table width="100%"> <tbody><tr> <td valign="top"> <?php $avatar_size = 82; if ( '0' != $comment->comment_parent ) $avatar_size = 82; echo get_avatar( $comment, $avatar_size ); ?> </td> <td valign="top" width="100%" > <div class="p_rep"> <?php printf( __( '<span class="c_1">%1$s</span> <span class="c_2">(%2$s)</span>', 'twentyeleven' ), sprintf( '<span class="fn">%s</span>', get_comment_author_link() ), sprintf( '<time pubdate datetime="%2$s">%3$s</time>',esc_url( get_comment_link( $comment->comment_ID ) ),get_comment_time( 'c' ), sprintf( __( '%1$s at %2$s', 'twentyeleven' ), get_comment_date(), get_comment_time() ) ) ); ?> <div class="c_text"><?php comment_text(); ?></div> <?php comment_reply_link( array_merge( $args, array( 'reply_text' => '<div class="reply"></div>', 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?> </div> </td> </tr> </tbody></table> <? } else { ?> <table width="100%"> <tbody><tr> <td width="100%" valign="top"> <?php printf( __( '<span class="c_1">%1$s</span> <span class="c_2">(%2$s)</span>', 'twentyeleven' ), sprintf( '<span class="fn">%s</span>', get_comment_author_link() ), sprintf( '<time pubdate datetime="%2$s">%3$s</time>',esc_url( get_comment_link( $comment->comment_ID ) ),get_comment_time( 'c' ), sprintf( __( '%1$s at %2$s', 'twentyeleven' ), get_comment_date(), get_comment_time() ) ) ); ?> <div class="c_text"><?php comment_text(); ?></div> <?php comment_reply_link( array_merge( $args, array( 'reply_text' => '<div class="reply"></div>', 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?> </td> <td valign="top"> <?php $avatar_size = 82; if ( '0' != $comment->comment_parent ) $avatar_size = 82; echo get_avatar( $comment, $avatar_size ); ?> </td> </tr> </tbody></table> <? } ?> <?php edit_comment_link( __( 'Edit', 'twentyeleven' ), '<span class="edit-link">', '</span>' ); ?> </div> </div> <?php if ( $comment->comment_approved == '0' ) : ?> <em class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.', 'twentyeleven' ); ?></em> <br /> <?php endif; ?> </article> <?php break; endswitch; } endif; // ends check for twentyeleven_comment() |
Вставка
1 2 3 4 5 6 7 8 9 |
ob_start(); comment_form(array("title_reply"=>"Add a Comment","cancel_reply_link"=>" ")); $out1 = ob_get_contents(); ob_end_clean(); if ( !is_user_logged_in() ) { echo preg_replace("/id=\"respond\">/is",'id="respond"><a name="com_now"></a>',$out1); } else { echo preg_replace("/id=\"respond\">/is",' id="respond" class="respond_two"><a name="com_now"></a>',$out1); } |
Файл css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#reply-title{ color: #1F1F1F; font-family: Arial; font-size: 29px; position: relative; top:-47px} .fn{color: #AB2822; display: inline-block; font-family: Arial; font-size: 18px; } .logged-in-as{ font-family: arial; font-size: 12px; position: absolute; right: 0; top: -20px;;} .comment-form-author label{display: block; left: -5px; position: absolute; top: -25px;} .comment-form-email label{display: block; left: -5px; position: absolute; top: -25px;} .comment-form-url label{display: block; left: -5px; position: absolute; top: -25px;} .comment-form-comment label{display: block; left: -5px; position: absolute; top: -25px;} .comment-awaiting-moderation{display: block;} |
Seach form
1 2 3 4 5 6 7 |
<form action="/" method="get"> <fieldset> <label for="search">Search in <?php echo home_url( '/' ); ?></label> <input type="text" name="s" id="search" value="<?php the_search_query(); ?>" /> <input type="image" alt="Search" src="<?php bloginfo( 'template_url' ); ?>/images/search.png" /> </fieldset> </form> |
Регистрация сидербаров
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
function twentytwelve_widgets_init() { register_sidebar( array( 'name' => __( 'Main Sidebar', 'twentytwelve' ), 'id' => 'sidebar-1', 'description' => __( 'Appears on posts and pages except the optional Front Page template, which has its own widgets', 'twentytwelve' ), 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); register_sidebar( array( 'name' => __( 'First Front Page Widget Area', 'twentytwelve' ), 'id' => 'sidebar-2', 'description' => __( 'Appears when using the optional Front Page template with a page set as Static Front Page', 'twentytwelve' ), 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); } add_action( 'widgets_init', 'twentytwelve_widgets_init' ); |
Сортировка постов
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function custom_posts_order( $orderby = '' ) { if(is_category() || !empty($_GET["s"])) { if(isset($_GET["most_comment"])) { $orderby='wp_posts.comment_count DESC'; } else if(isset($_GET["rating"])) { $orderby='wp_posts.post_rating DESC'; } else if(isset($_GET["alphabetical"])){ $orderby='wp_posts.post_title'; } } return $orderby; } add_filter ( 'posts_orderby', 'custom_posts_order' ); |
Устанавливаем количество постов на странице
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function cat_pre($query) { global $wp_query; if($wp_query->is_category) { $idObj = get_category_by_slug($wp_query->query["category_name"]); $id_category = $idObj->term_id; if($id_category==16 || $wp_query->query_vars["cat"]==16) { $query->set('posts_per_page', 5); } } return $query; } add_action('pre_get_posts','cat_pre'); |
Добавляем в админку произвольное поле
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class new_general_setting { function new_general_setting( ) { add_filter( 'admin_init' , array( &$this , 'register_fields' ) ); } function register_fields() { register_setting( 'general', 'favorite_color', 'esc_attr' ); add_settings_field('fav_color', '<label for="favorite_color">Ссылка на каталог:</label>' , array(&$this, 'fields_html') , 'general' ); } function fields_html() { $value = get_option( 'favorite_color', '' ); echo '<input id="favorite_color" name="favorite_color" value="'.$value.'" class="regular-text code">'; } } Вывод <?php echo htmlspecialchars_decode(get_option( 'favorite_color', '' )); ?> |
Имя шаблона
1 2 3 |
/** * Template Name: Main */ |
Регистрируем функции для масштабирование картинок
1 2 3 4 5 6 7 |
if ( function_exists( 'add_image_size' ) ) { add_image_size('150-thumb', 150, 100 ); add_image_size('309-thumb', 309, 212 ); add_image_size('middle-thumb', 422, 263 ); add_image_size('news-thumb', 533, 366 ); add_image_size('big-thumb', 1024, 640 ); } |
Переработанная функция для галереи WP Simple Galleries на тот случай, если автор не внесет изменений, как я ему писал.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
private function get_thumb($id, $post_id) { // код автора до этой части $title = str_replace(array_keys($data), $data, $title_string); $list_thumb=array(); foreach(get_intermediate_image_sizes() as $val) { $t= wp_get_attachment_image_src($id,$val); $list_thumb[$val]=$t[0]; } $list_thumb["url"]=$url; $list_thumb["src"]=$image[0]; $list_thumb["alt"]=$info[0]->post_title; return $list_thumb; } |
Пример action wp_footer
1 2 3 4 5 6 7 8 9 |
function add_popup_script_footer() { echo ' <!-- Magnific Popup core CSS file --> <link rel="stylesheet" href="'.site_url().'/wp-content/plugins/pop_up/magnific-popup.css"> <link rel="stylesheet" href="'.site_url().'/wp-content/plugins/pop_up/all.min.css?v=1.0.0"> '; } add_action('wp_footer', 'add_popup_script_footer'); |
Пример файла function.php
1 2 3 4 5 6 7 8 9 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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
<?php function register_my_menu() { register_nav_menu('header-menu',__( 'Вверхнее меню' )); } add_action( 'init', 'register_my_menu' ); if ( function_exists( 'add_image_size' ) ) { add_image_size('middle-thumb', 400, 300, true ); add_image_size('blog-thumb', 1920, 900, true ); } add_theme_support('post-thumbnails'); function twentyfourteen_widgets_init() { register_sidebar( array( 'name' => __( 'Primary Sidebar', 'twentyfourteen' ), 'id' => 'sidebar-1', 'description' => __( 'Main sidebar that appears on the left.', 'twentyfourteen' ), 'before_widget' => '<aside id="%1$s" class="widget wow fadeInUp %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h5 class="widget-title">', 'after_title' => '</h5>', ) ); } add_action( 'widgets_init', 'twentyfourteen_widgets_init' ); add_action('init', 'my_action_callback'); // простая голосовалка /* $(".add_like").click(function(){ var id_post=$(this).attr("id"); var t=this; $.ajax({ method: "POST", url: "/index.php", data: { action: "vote_post", id_post: id_post } }).done(function(msg) { $(t).find("span").text(msg); }); }); */ function my_action_callback() { global $wpdb; // this is how you get access to the database if($_POST['action'] =="vote_post") { $id_post = intval( $_POST['id_post'] ); if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } $vote_post = get_post_meta( $id_post, 'vote_post' ); $vote_post=$vote_post[0]; if(!empty($vote_post)) { if(!in_array($ip,$vote_post["ip"])) { $vote_post["vote"]++; $vote_post["ip"][]=$ip; } update_post_meta( $id_post, 'vote_post', $vote_post ); } else { $vote_post["vote"]=1; $vote_post["ip"][]=$ip; add_post_meta( $id_post, 'vote_post', $vote_post ); } echo $vote_post["vote"]; exit; } } |
Перебор всех категорий для меню
1 2 3 4 5 6 7 8 9 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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
<?php $args = array( 'order' => 'ASC', 'orderby' => 'menu_order', 'post_type' => 'nav_menu_item', 'post_status' => 'publish', 'output' => ARRAY_A, 'output_key' => 'menu_order', 'nopaging' => true, 'update_post_term_cache' => false ); $menu_object = wp_get_nav_menu_items( "header-menu", $args ); foreach($menu_object as $key=>$val) { $find_post=false; foreach($menu_object as $v) { if($val->ID==$v->menu_item_parent) { $find_post=true; } } if($find_post) { $menu_object[$key]->find_child=1; } else { $menu_object[$key]->find_child=0; } } $cat_now = get_the_category( ); foreach($menu_object as $val) { if($val->menu_item_parent==0) { if($val->find_child==0) { $class=""; if($post->ID==$val->object_id || ($val->object_id==$cat_now[0]->category_parent)) { $class=' class="active" '; } echo ' <li '.$class.'> <a href="'.$val->url.'" title="'.$val->post_title.'">'.$val->title.'</a> </li> '; } else { echo ' <li class="dropdown"> <a href="#" title="'.$val->post_title.'" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">'.$val->title.' <span class="caret"></span></a> <ul class="dropdown-menu" role="menu">'; foreach($menu_object as $v) { if($val->ID==$v->menu_item_parent) { $class=""; if($post->ID==$val->object_id || ($v->object_id==$cat_now[0]->cat_ID)) { $class=' class="active" '; } echo ' <li '.$class.'> <a href="'.$v->url.'" title="'.$v->post_title.'"> '.$v->title.' </a> </li> '; } } echo ' </ul> </li> '; } } } ?> |
Получение родительской категории верхнего уровня
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function pa_category_top_parent_id ($catid) { while ($catid) { $cat = get_category($catid); // get the object for the catid $catid = $cat->category_parent; // assign parent ID (if exists) to $catid // the while loop will continue whilst there is a $catid // when there is no longer a parent $catid will be NULL so we can assign our $catParent $catParent = $cat->cat_ID; } return $catParent; } // usege $catid = get_query_var('cat'); echo pa_category_top_parent_id ($catid); |
Список стандартных виджетов WordPress
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function true_remove_default_widget() { unregister_widget('WP_Widget_Archives'); // Архивы unregister_widget('WP_Widget_Calendar'); // Календарь unregister_widget('WP_Widget_Categories'); // Рубрики unregister_widget('WP_Widget_Meta'); // Мета unregister_widget('WP_Widget_Pages'); // Страницы unregister_widget('WP_Widget_Recent_Comments'); // Свежие комментарии unregister_widget('WP_Widget_Recent_Posts'); // Свежие записи unregister_widget('WP_Widget_RSS'); // RSS unregister_widget('WP_Widget_Search'); // Поиск unregister_widget('WP_Widget_Tag_Cloud'); // Облако меток unregister_widget('WP_Widget_Text'); // Текст unregister_widget('WP_Nav_Menu_Widget'); // Произвольное меню } add_action( 'widgets_init', 'true_remove_default_widget', 20 ); |
Популярные записи
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
Популярные записи function wpb_set_post_views($postID) { $count_key = 'wpb_post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count==''){ $count = 0; delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); }else{ $count++; update_post_meta($postID, $count_key, $count); } } singel.php $post_id=get_the_ID(); wpb_set_post_views($post_id); // считаем самое популярное // вывод на сайте <?php $popularpost = new WP_Query( array( 'posts_per_page' => 3, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'wpb_post_views_count', 'order' => 'DESC' ) ); while ( $popularpost->have_posts() ) : $popularpost->the_post(); ?> <a href=""><?php the_title(); ?></a> <?php endwhile; ?> |
Меняем правила формирования ссылок
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function custom_rewrite_basic() { global $wp,$wp_rewrite; $wp->add_query_var('year_show'); add_rewrite_rule('category/(.+?)/year/?([0-9]{1,})/?, 'index.php?category_name=$matches[1]&year_show=$matches[2]', 'top'); $wp_rewrite->flush_rules( false ); } add_action('init', 'custom_rewrite_basic'); // kill_feed_rewrites - доступ ко всем правилам // Доступ к переменной global $wp_query; echo $wp_query->query_vars['year_show']; |
Сохранения значений переменных
1 2 3 4 5 |
if ( get_option( "site_url_real" ) !== false && isset($_POST["site_url_real"])) { update_option( "site_url_real", $_POST["site_url_real"] ); } else { add_option( "site_url_real", $_POST["site_url_real"], null ); } |