Categories
Typo

Base Type rules

  • Serif is subjectively considered easier to read (and more trusted), whereas sans-serif is considered more modern.
  • In general, the recommendation is to have a font-size of 16px, which translates into 12pt on a printed document.
  • Line height 1.2-1.5 – for short paragraph 1.2, 1.5 for long story.
  • Characters per line 55-75  Tame the flow
  • mobile phone, tablet, and desktop – different font sizes (mobile, tablet – characters per line – 35-50, line height – 2)
  • Use contrast – Pick one that has lots of weights, Four at least.
  • Think in blocks: Type is a beautiful group of letters, not a group of beautiful letters.
  • Type is not an exact science. It is aligned when it feels aligned.
  • Contrast
  • Headlines 2x – In doubt, skip a weight.
  • Don’t underline non-links
  • drop capital increases readership
  • Have the first paragraph’s text size be even bigger or less char on the line
  • Have good subheadings (<h2> and <h3>) in your content. Making them eye-catching helps the user segue into your content
  • Make your content scannable
  • Use bold and italics (but never underlines)
  • Use lists
  • Use <blockquotes> to highlight
  • Keep to shorter paragraphs – it makes the user feel like they are reading it faster
  • Do not use jargon – that limits your potential audience greatly
  • Be concise – you’re not writing a novel
  • Use images – people retain more information visually. To maximize shares, use animated or hand-drawn images.
  • Quotes can also be useful – people love sharing quotes
  • Make it easy to share – if it was interesting and a pleasure to read, they’ll want to share it

 

Google Play Books – Literata, Material Design – Roboto (The basic set of styles) / Noto (asian) / Amazon – Bookerly / Apple -Apple Garamond – Helvetica Black(headers)- Myriad-Myriad Set Pro(from-2001)- soft – Mac OS X Lucida Grande – IPhone – Helvetica, Helvetica Nue (retina) – Apple Watch – San Francisco

Serif fonts can be broadly classified into one of four subgroups: old style, transitional, Didone and slab serif.

A font is what you use, a typeface is what you see.

What Is Typography?, Matthew Butyric
Why Does Typography Matter?, Matthew Butterick
Elements of Typographic Style, Robert Bringhurst
Understanding the Difference Between Type and Lettering, Joseph Alessio
5 minutes Guide to better typography

Categories
CSS HTML

Спрайты

HTTP 1.1 – одно соединение TCP (браузеры создают параллельно от 2 до 8 параллельных соединений)

HTTP 2 – все запросы между браузером и сервером мультиплексированы (прим. уплотнены) в одно TCP соединение. Это позволяет загружать десятки изображений в параллели в одном TCP соединении.

 

  • один спрайт-сет загружается единожды используя один запрос
  • объединённый размер меньше чем сумма
  • время загрузки значительно короче

 

  • CSS код значительно проще без спрайт-сета
  • обновление браузерного кеша при каждой модификации спрайт-сета
  • Использование отдельных изображений вместо спрайт-сетов позволяет загружать только те из них, которые нужны из всей коллекции

 

Creating svg sprites using gulp and sass

Categories
Jquery

Событие on

$(‘#селектор’).on(‘событие мыши’, селектор, данные(литерал объекта), имя функции);

var linkVar = {message: 'linkVar text'};
var pVar = {message: 'pVar text'};

function showMessage (evt) {
 alert(evt.data.message);
}

$('a').on('mouseover', linkVar, showMessage);
$('p').on('click', pVar, showMessage);

//несколько имен событий
$(document).on('click keypress', function() {
    $('#lightbox').hide();
});

//передача объектной константы
$('#theElement').on({
    'click' : function() {
        //some action
    },
    'mouseover' : function() {
        //some action
    }
});

 Делегирование событий

$('ul').on('click', 'li', function() {
    $(this).css('color' : 'red'); // this - li
});

 

 

Categories
Jquery

События мыши

События мыши

click, dblclick, mousedown, mouseup, mouseover, mouseout, mousemove

События документа/окна

load, resize, scroll, unload

События форм

submit, reset, change, focus, blur

События клавиатуры

keypress, keydown, keyup

Использование событий

$('a').click(function() {});

 Ожидание загрузки HTML-кода

$(function() {})// сокращенная запись
$(document).ready(function() {})

ready() – ожидание загрузки HTML-кода, без ожидания загрузки изображений и роликов

альтернатива – размещение скрипта перед закрывающим тегом body.(загрузка и запуск кода замедлит браузер до тех пор, пока сценарий не загрузится и не прекратит выполняться) – минус – модификация HTML по мере прогрузки скриптов, и если приложение не работает без js.

События наведения и смещения указателя мыши

$('#селектор').hover(функция1, функция2);

$('menu').hover(function(){
    $('submenu').show();
},//окончание события mouseover
    function() {
    $('submenu').hide();
}//окончание события mouseout
);//окончание события hover

 Объект события

Во время запуска события браузер записывает информацию о нем и сохраняет его в так называемом объекте события. Объект события содержит данные, собранные в момент, когда произошло событие, такие, как координаты указателя мыши по горизонтали и вертикали, элемент, который инициировал событие, была ли нажата при запуске события клавиша Shift.

$(document).click(function(evt) {
    var xPos = evt.pageX;
    var yPos = evt.pageY;
    alert('X: ' + xPos + ' Y: ' + yPos);
}); //конец события click

В каждом браузере могут быть разные свойства, общие: pageX, pageY, screenX, screenY, shiftKey, which (используется с событием нажатия клавиши для определения числового кода нажатой клавиши. Можно узнать клавишу преобразовав с помощью метода String.fromCharCode(evt.which); ), target, data.

Отмена обычного поведения событий

$('#menu').click(function(evt) {
    //some code
evt.preventDefault(); // не переходи по ссылке

// другой вариант
return false;
});

Удаление событий

$('a').mouseover(function(){
    //some action
});

$('#disable').click(function() {
    $('a').off('mouseover') // удаляет событие mouseover, или все события, если не передать аргументы
});

Остановка события (всплытие события)

Каждый из элементов-предков так же может реагировать на событие дочернего элемента.

$('#thelink').click(function(evt) {
    //some action
    evt.stopPropagation(); // останавливает событие
});

 

 

Categories
Jquery

Селекторы

Селекторы
http://api.jquery.com/category/selectors/

$('#id');
$('.class');

$('#id .class');
$('parent > child');
$('tag + tag');
$('tag[attribute]');
$('tag[attribute="value"]');
$('tag[attribute^="value"]');
$('tag[attribute*="value"]');
$('tag[attribute&="value"]');

$('tag:even'); возвращает 0-2-4 элементы выборки
$('tag:odd'); возвращает 1-3-5 элементы выборки

$('tag:first');
$('tag:last');

$('tag:not(element)'); без класса element
$('tag:has(element)'); выбирает tag имеющий element
$('tag:contains(content)');

$('tag:hidden'); если не установлен visibility: invisible;
$('tag:visible');


Выборка элементов jQuery отличается от традиционной выборки getElementByTagName() или getElementById() и не понимает традиционных методов объектной модели.

Автоматические циклы

$(‘#slideshow img’).hide(); – автоматически пройдет по всем элементам выборки и к каждому из них применит функцию .hide();

Связывание функций

$('#popUp').width(300)
    .height(300)
    .text('Hi!')
    .fadeIn(1000);

Добавление содержимого на страницу

.html() –  считывает существующий HTML код только внутри первого элемента, а так же замещает текущее содержимое, но во всех элементах выборки другим HTML-кодом.

.text() – похожа на работу функции html, но не принимает HTML элементы.

.append() – добавляет HTML-код в качестве последнего дочернего элемента выбранного элемента.

.prepend() -добавляет HTML-код в качестве первого дочернего элемента выбранного элемента.

.before()

Замена и удаление выборок

.remove() – удаляет выборку

.replaceWith(value) – заменяет выборку на value

.clone() – создает клон

Установка и чтение атрибутов элемента

addClass(‘class-name’) – добавляет класс

removeClass(‘class-name’) – удаляет класс

toggleClass(‘class-name’) – добавляет или удаляет класс

Чтение и изменение свойств CSS

определение текущего значения свойства

var bgColor = $('#main').css('background-color');

$('body').css('font-size' : '200%'); // числовое знач. второго аргумента jQuery переведет в пиксели .css('padding', 100)

var baseFont = $('body').css('font-size');
baseFont = parseInt(baseFont); // вернет значение + px
$('body').css('font-size', baseFont * 2);


jQuery возвращает все цвета в rgb или rgba если есть прозрачность. Всегда все значения в пикселях.

Литерал объекта (объектная константа) – список пар свойств / значение

.css({
    'font-size' : '5em',
    'color' : 'red'
});

Чтение, установка и удаление атрибутов HTML.

.attr(); .removeAttr()

var imageFile = $('#banner img').attr('src','new/image/path');

 Работа с каждым элементом выборки

.each(function() {});

Ключевые слова this и $(this)

$(this) jQuery версия традиционному this – относится к элементу вызывающему анонимную функцию

$('a[href^=http://]').each(function(){
    var extLink = $(this).attr('href');
});
Categories
CSS

SMACSS

At the very core of SMACSS is categorization.

1.Base (exclusively – body, a, input[type=text]…)
2.Layout (reusable, modular parts of our design – container) – .l- or .layout- .grid-
3.Module (sidebar, product lists…)
4.State (hidden, expanded, active, inactive) .is-
5.Theme

#article {
    width: 80%;
    float: left;
}

#sidebar {
    width: 20%;
    float: right;
}

.l-fixed #article {
    width: 600px;
}

.l-fixed #sidebar {
    width: 200px;
}
/* Example Module */
.example { }

/* Callout Module */
.callout { }

/* Callout Module with State */
.callout.is-collapsed { }

/* Form field module */
.field { }

/* Inline layout  */
.l-inline { }
Categories
Полезное

Simple Steps Code

One of my readers sent this fantastic question which I’ve quoted anonymously here with permission:

“I have been learning about front-end web dev and web design for almost 2 years now but the more I learn, the more I realize how much I don’t know and it has put me in this spot where I’m absolutely crippled by procrastination and self-doubt. I feel like I’ve done enough learning and I now I want to build, build, build but I really don’t know where to start.

This could all be in my head but I feel as though, most front end development nowadays is built around these complex web apps involving React or whatever the newest framework on the block is. Is it possible for me as one person to do the UX research, layout, design AND build (incl. all the JS) for a single site? I’m not sure I have it in me to build something that impressive on my own. Something that will be worthy of a good portfolio that will get me hired. And because I’m so freaked out by this thought, I just keep plugging away at learning and trying to stay caught up with the industry instead of actually spending the time building something. It seems to be an endless cycle that I can’t get out of.”

What makes this question great is that it perfectly expresses exactly how a lot of people feel about web development.  It seems like there are so many things to know, and it can feel overwhelming.

My advice: Don’t magnify the monster.  Instead of approaching website creation as a big scary beast, let’s break this down into smaller pieces.

“I feel as though most front end development is built around these complex web apps involving React or whatever the newest framework on the block is.”

First, don’t even worry about frameworks.  You can build a beautiful, functional, responsvie site with a few HTML tags and a few CSS styles.  As far as the front end is concerned, that’s all it takes.  JavaScript only comes in if you want to add interactive features.

Second, remember that the whole point of frameworks is to make things easier.  If you can learn HTML, CSS, and JavaScript, those are the hard parts.  As an example, jQuery is just a bunch of prebuilt JavaScript that lets you write less code.  In fact, so many of the well-known frameworks involve JavaScript that if you get better at JavaScript, you’ll automatically be better at jQuery, Angular, React, Node, Socket.io, Meteor, and more, all in one strike.

The key is that if you get better with HTML, CSS, and JavaScript, you can adapt to any framework you would need to learn.  However, if you focus on one framework, you can spend all the time learning it only to find that the place you want to work at uses something else.

Now let’s look at the next piece:

“Is it possible for me as one person to do the UX research, layout, design AND build (incl. all the JS) for a single site?”

Yes, but the bigger you make it sound, the scarier it becomes. UX research and layout are big topics, but for the purposes of your website, you only need to ask yourself one question: Are the important parts of my site clear and easy to find? That question alone will put you ahead of a surprisingly large number of websites that are out there.

As for design, don’t overthink it for your portfolio pieces.  A lot of sites follow similar patterns anyway (such as the big hero image with a main call-to-action button).  Pick a site you like, modify it a little bit, and you’ll have a working design.  Remember the main point of a front-end developer’s portfolio is to show you can code a site.  First do the HTML and CSS.  That will give you a site.  Then you can add JavaScript if you want specialized interactive features.

Now on to the next part:

“I’m not sure I have it in me to build something that impressive on my own. Something that will be worthy of a good portfolio that will get me hired. And because I’m so freaked out by this thought, I just keep plugging away at learning and trying to stay caught up with the industry instead of actually spending the time building something.”

This happens to a lot of people.  For now, stop chasing trends and just build something.  Start with an HTML and CSS page with a common layout.  Then make it responsive.  Try making some more pages.  Then learn JavaScript.  Make small interactive things and post them on something like codepen or jsfiddle.  Don’t worry about any next steps until you’ve done that.

If you’re reading this, hopefully you’ve found it helpful.

Best,

Yaphi
Simple Steps Code

Copyright © 2016 Simple Steps Code, All rights reserved.
You are receiving this email because you signed up for coding tips on simplestepscode.com.

Simple Steps Code

9916 Kentsdale Dr

Potomac, MD 20854

Categories
Без рубрики

command line + MacOs structure

  • cd
  • cd ..
  • cd /path/
  • mkdir FolderName
  • touch filename.txt
  • Options modify the behavior of commands:
    • ls -a lists all contents of a directory, including hidden files and directories
    • ls -l lists all contents in long format
    • ls -t orders files and directories by the time they were last modified
    • Multiple options can be used together, like ls -alt
  • From the command line, you can also copy, move, and remove files and directories:
    • cp copies files
    • mv moves and renames files
    • rm removes files
    • rm -r(recursive) removes directories and child items
  • Wildcards are useful for selecting groups of files and directories

 

MacOS structure

Directory Description
/Applications Self explanatory, this is where your Mac’s applications are kept
/Developer The Developer directory appears only if you have installed Apple’s Developer Tools, and no surprise, contains developer related tools, documentation, and files.
/Library Shared libraries, files necessary for the operating system to function properly, including settings, preferences, and other necessities (note: you also have a Libraries folder in your home directory, which holds files specific to that user).
/Network largely self explanatory, network related devices, servers, libraries, etc
/System System related files, libraries, preferences, critical for the proper function of Mac OS X
/Users All user accounts on the machine and their accompanying unique files, settings, etc. Much like /home in Linux
/Volumes Mounted devices and volumes, either virtual or real, such as hard disks, CD’s, DVD’s, DMG mounts, etc
/ Root directory, present on virtually all UNIX based file systems. Parent directory of all other files
/bin Essential common binaries, holds files and programs needed to boot the operating system and run properly
/etc Machine local system configuration, holds administrative, configuration, and other system files
/dev Device files, all files that represent peripheral devices including keyboards, mice, trackpads, etc
/usr Second major hierarchy, includes subdirectories that contain information, configuration files, and other essentials used by the operating system
/sbin Essential system binaries, contains utilities for system administration
/tmp Temporary files, caches, etc
/var Variable data, contains files whose contents change as the operating system runs
Categories
CSS

Flexbox

display: flex;

/* Direction flex container*/

flex-direction: row;
flex-direction: row-reverse;
flex-direction: column;
flex-direction: column-reverse;

/* Wrap - enable multiline*/
flex-wrap: nowrap;
flex-wrap: wrap;
flex-wrap: wrap-reverse;

/* flex-flow - combaine flex-ditection flex-wrap*/ 

flex-flow: column wrap;

/* justify-content*/
/*  items: margin-right: auto; margin-left: auto; margin: auto;*/

justify-content: flex-start;
justify-content: flex-end;
justify-content: center;
justify-content: space-between;
justify-content: space-around;

/*  Order */
order: 5;
order: -5; 

/* flex grow */
flex-grow: 3;
flex-grow: 0.6;

/*  flex-basis */
/* Specify <'width'> */
flex-basis: 10em;      
flex-basis: 3px;
flex-basis: auto;

/* Intrinsic sizing keywords */
flex-basis: fill;
flex-basis: max-content;
flex-basis: min-content;
flex-basis: fit-content;

/* Automatically size based on the flex item’s content */
flex-basis: content;

/* flex-shrink антоним flex-grow*/
flex-shrink: 2;
flex-shrink: 0.6;

/* Alignment */

align-content: flex-start;
align-content: flex-end;
align-content: center;
align-content: space-around;
align-content: space-between;
align-content: stretch;
align-items: flex-start;
align-items: flex-end; 
align-items: center; 
align-items: baseline; 
align-items: stretch;


align-self: auto;
align-self: flex-start;
align-self: flex-end;
align-self: center;
align-self: baseline;
align-self: stretch;

/* center content */
/* first */
.container {
  display:flex;
  
  justify-content: center;
  align-items: center;
}

/* second */

.container {
  display: flex;
  justify-content: center;
}

.item-1 {
  align-self: center;
}

/*third*/

.container {
  display: flex;
}

.item-1 {
  margin: auto;
}


 

http://codepen.io/enxaneta/pen/adLPwv

A Complete Guide to Flexbox

Designing A Product Page Layout with Flexbox

Flexbox playgroung

Using CSS flexible boxes

Categories
WordPress

WordPress – Start new project

Get template part

get_template_part

// create file content-name.php

<?php get_template_part('content', 'name') ?>

main scripts

//return network home url
<?php echo network_home_url(); ?> 

//return template directory url
<?php get_template_directory_uri(); ?>

//post metaboxes
<?php echo get_post_meta( $post->ID, 'meta_name', true ) ?>

//the title link to post
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><h1><?php the_title(); ?></h1></a>

wp_query with loop

style.css

/*
Theme Name: 
Author: 
Author URI:
Version: 
*/

main.js

// no conflict for jQuery
jQuery( document ).ready(function( $ ) {
    // You can use the locally-scoped $ in here as an alias to jQuery.
    $( "div" ).hide();
});

header.php 

<html <?php language_attributes(); ?>>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="description" content="<?php bloginfo( 'description' ); ?>">

<title><?php bloginfo('name'); ?></title>

<?php wp_head(); ?>

<body <?php body_class(); ?>>

<?php get_template_part( 'navigation' ); ?>

navigation.php

<!-- insert navigation menu from WP / registration in function.php -->
<?php
    $defaults = array( 'menu_class' => 'menu class' );
    wp_nav_menu( $defaults );
?>

index.php

<? get_header(); ?> <!--include header.php-->
<? get_footer(); ?> <!--include footer.php-->

sidebar.php

<? get_sidebar(); ?> <!--include sidebar.php-->
<? get_sidebar( 'name' ); ?> <!--include sidebar-name.php-->

footer.php

<!-- put Yandex and Google metrika scripts here or in function.php>
<?php wp_footer(); ?>

function.php

<?php

//link styles
// wp_enqueue_style( 'name', PATH )
function theme_styles() {
 wp_enqueue_style( 'main', get_template_directory_uri() . '/css/main.css' );
}

add_action( 'wp_enqueue_scripts', 'theme_styles' );

//link scripts
// wp_enqueue_script ( 'name', PATH, 'array('scripts position')', '$ver',  "place in footer = true, false" )
function theme_js() {
 wp_enqueue_script( 'main', get_template_directory_uri() . '/js/main.js' );
}

add_action( 'wp_enqueue_scripts', 'theme_js' );



//add theme support
add_theme_support( 'post-thumbnails' );

// Navigation Menus
function register_theme_menus() {
 register_nav_menus(
  array(
   'header-menu' => __( 'Header Menu' )
  )
 );
}

add_action( 'init', 'register_theme_menus' );

/**
 * Link all post thumbnails to the post permalink.
 *
 * @param string $html Post thumbnail HTML.
 * @param int $post_id Post ID.
 * @param int $post_image_id Post image ID.
 * @return string Filtered post image HTML.
 */

function wpdocs_post_image_html( $html, $post_id, $post_image_id ) {
 $html = '<a href="' . get_permalink( $post_id ) . '" alt="' . esc_attr( get_the_title( $post_id ) ) . '">' . $html . '</a>';
 return $html;
}
add_filter( 'post_thumbnail_html', 'wpdocs_post_image_html', 10, 3 );

Conditional statements

$num_posts = ( is_front_page() ) ? 4 : -1;

$args = array (
    'post_type' => 'portfolio',
    'post_per_page' => $num_posts
);

Conditional tags

Create own post type

//Add custom page post_type

if ( ! function_exists( 'structure_page_cp' ) ) {

// Опишем требуемый функционал
 function structure_page_cp() {

  $labels = array(
   'name'                => _x( 'Структура', 'Post Type General Name', 'structure_page' ),
   'singular_name'       => _x( 'Структура', 'Post Type Singular Name', 'structure_page' ),
   'menu_name'           => __( 'Структура', 'structure_page' ),
   'parent_item_colon'   => __( 'Родительский:', 'structure_page' ),
   'all_items'           => __( 'Все записи', 'structure_page' ),
   'view_item'           => __( 'Просмотреть', 'structure_page' ),
   'add_new_item'        => __( 'Добавить новую запись в Красную Книгу', 'structure_page' ),
   'add_new'             => __( 'Добавить новую', 'structure_page' ),
   'edit_item'           => __( 'Редактировать запись', 'structure_page' ),
   'update_item'         => __( 'Обновить запись', 'structure_page' ),
   'search_items'        => __( 'Найти запись', 'structure_page' ),
   'featured_image'      => __( 'Изображение', 'structure_page' ),
   'not_found'           => __( 'Не найдено', 'structure_page' ),
   'not_found_in_trash'  => __( 'Не найдено в корзине', 'structure_page' ),
  );
  $args = array(
   'labels'              => $labels,
   'supports'            => array( 'title', 'editor', 'excerpt', ),
   'taxonomies'          => array( 'structure_page_tax' ), // категории, которые мы создадим ниже
   'public'              => true,
   'menu_position'       => 5,
   'menu_icon'           => 'dashicons-book',
  );
  register_post_type( 'structure_page', $args );

 }

 add_action( 'init', 'structure_page_cp', 0 ); // инициализируем

 //добавить категории для post_type

 if ( ! function_exists( 'structure_page_tax' ) ) {

// Опишем требуемый функционал
  function structure_page_tax() {

   $labels = array(
    'name'                       => _x( 'Категории Структура', 'Taxonomy General Name', 'structure_page' ),
    'singular_name'              => _x( 'Категории Структура', 'Taxonomy Singular Name', 'structure_page' ),
    'menu_name'                  => __( 'Категории Структура', 'structure_page' ),
    'all_items'                  => __( 'Категории Структура', 'structure_page' ),
    'parent_item'                => __( 'Родительская категория Структура', 'structure_page' ),
    'parent_item_colon'          => __( 'Родительская категория Структура:', 'structure_page' ),
    'new_item_name'              => __( 'Новая категория', 'structure_page' ),
    'add_new_item'               => __( 'Добавить новую категорию', 'structure_page' ),
    'edit_item'                  => __( 'Редактировать категорию', 'structure_page' ),
    'update_item'                => __( 'Обновить категорию', 'structure_page' ),
    'search_items'               => __( 'Найти', 'structure_page' ),
    'add_or_remove_items'        => __( 'Добавить или удалить категорию', 'structure_page' ),
    'choose_from_most_used'      => __( 'Поиск среди популярных', 'structure_page' ),
    'not_found'                  => __( 'Не найдено', 'structure_page' ),
   );
   $args = array(
    'labels'                     => $labels,
    'hierarchical'               => true,
    'public'                     => true,
   );
   register_taxonomy( 'structure_page_tax', array( 'structure_page' ), $args );

  }

  add_action( 'init', 'structure_page_tax', 0 ); // инициализируем

 }
}

 Add custom meta boxes

//добавить новые поля для post_type - структура

function my_meta_box() {
 add_meta_box(
  'my_meta_box', // Идентификатор(id)
  'Дополнительные поля', // Заголовок области с мета-полями(title)
  'show_my_metabox', // Вызов(callback)
  'structure_page', // Где будет отображаться наше поле, в нашем случае в Записях
  'normal',
  'high');
}
add_action('add_meta_boxes', 'my_meta_box'); // Запускаем функцию

$meta_fields = array(

 array(
  'label' => 'Заголовок 1',
  'desc'  => ' ',
  'id'    => 'header1', // даем идентификатор.
  'type'  => 'text'  // Указываем тип поля.
 ),
 array(
  'label' => 'Текстовое поле 1',
  'desc'  => 'Описание для поля.',
  'id'    => 'text_area1',  // даем идентификатор.
  'type'  => 'textarea'  // Указываем тип поля.
 ),
 array(
  'label' => 'Чекбоксы (флажки)',
  'desc'  => 'Описание для поля.',
  'id'    => 'mycheckbox',  // даем идентификатор.
  'type'  => 'checkbox'  // Указываем тип поля.
 ),
 array(
  'label' => 'Всплывающий список',
  'desc'  => 'Описание для поля.',
  'id'    => 'myselect',
  'type'  => 'select',
  'options' => array (  // Параметры, всплывающие данные
   'one' => array (
    'label' => 'Вариант 1',  // Название поля
    'value' => '1'  // Значение
   ),
   'two' => array (
    'label' => 'Вариант 2',  // Название поля
    'value' => '2'  // Значение
   ),
   'three' => array (
    'label' => 'Вариант 3',  // Название поля
    'value' => '3'  // Значение
   )
  )
 )
);

// Вызов метаполей
function show_my_metabox() {
 global $meta_fields; // Обозначим наш массив с полями глобальным
 global $post;  // Глобальный $post для получения id создаваемого/редактируемого поста
// Выводим скрытый input, для верификации. Безопасность прежде всего!
 echo '<input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';

 // Начинаем выводить таблицу с полями через цикл
 echo '<table class="form-table">';
 foreach ($meta_fields as $field) {
  // Получаем значение если оно есть для этого поля
  $meta = get_post_meta($post->ID, $field['id'], true);
  // Начинаем выводить таблицу
  echo '<tr>
                <th><label for="'.$field['id'].'">'.$field['label'].'</label></th>
                <td>';
  switch($field['type']) {
   case 'text':
    echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="'.$meta.'" size="30" />
        <br /><span class="description">'.$field['desc'].'</span>';
    break;
   case 'textarea':
    echo '<textarea name="'.$field['id'].'" id="'.$field['id'].'" cols="60" rows="4">'.$meta.'</textarea>
        <br /><span class="description">'.$field['desc'].'</span>';
    break;
   case 'checkbox':
    echo '<input type="checkbox" name="'.$field['id'].'" id="'.$field['id'].'" ',$meta ? ' checked="checked"' : '','/>
        <label for="'.$field['id'].'">'.$field['desc'].'</label>';
    break;
// Всплывающий список
   case 'select':
    echo '<select name="'.$field['id'].'" id="'.$field['id'].'">';
    foreach ($field['options'] as $option) {
     echo '<option', $meta == $option['value'] ? ' selected="selected"' : '', ' value="'.$option['value'].'">'.$option['label'].'</option>';
    }
    echo '</select><br /><span class="description">'.$field['desc'].'</span>';
    break;
  }
  echo '</td></tr>';
 }
 echo '</table>';
}

// Пишем функцию для сохранения
function save_my_meta_fields($post_id) {
 global $meta_fields;  // Массив с нашими полями

 // проверяем наш проверочный код
 if (!wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__)))
  return $post_id;
 // Проверяем авто-сохранение
 if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
  return $post_id;
 // Проверяем права доступа
 if ('page' == $_POST['post_type']) {
  if (!current_user_can('edit_page', $post_id))
   return $post_id;
 } elseif (!current_user_can('edit_post', $post_id)) {
  return $post_id;
 }

 // Если все отлично, прогоняем массив через foreach
 foreach ($meta_fields as $field) {
  $old = get_post_meta($post_id, $field['id'], true); // Получаем старые данные (если они есть), для сверки
  $new = $_POST[$field['id']];
  if ($new && $new != $old) {  // Если данные новые
   update_post_meta($post_id, $field['id'], $new); // Обновляем данные
  } elseif ('' == $new && $old) {
   delete_post_meta($post_id, $field['id'], $old); // Если данных нету, удаляем мету.
  }
 } // end foreach
}
add_action('save_post', 'save_my_meta_fields'); // Запускаем функцию сохранения

 

 

WordPress Meta Boxes: a Comprehensive Developer’s Guide

 

Testing theme

Codex Reference

Plugin Reference