Структура WordPress шаблона — ее должен знать каждый.

This article will guide you through the process of creating a front-end page in WordPress that lists your authors. We’ll discuss why you would want to do this, we’ll introduce the WP_User_Query class, and then we’ll put it it all together

At its core, WordPress is a rock-solid publishing platform. With a beautiful and easy to use interface, and support for custom post types and post formats, publishers have the flexibility to do what they do best: write content .

Further Reading on SmashingMag:

However, WordPress is lacking in social interaction between content authors and readers. BuddyPress is trying to solve this, but I believe it’s going in the wrong direction by trying to be a full-fledged social network.

A big phrase in the publishing world is “user engagement.” This is about getting readers to spend more time on the website, actively searching for content and even generating their own. While one could write a few books on the subject, here are a few things a WordPress publisher can do:

  • Create a daily or weekly newsletter, with top stories from selected categories;
  • Provide an editorial-driven open forum in which editors propose themes, stories and questions and readers comment on them;
  • Continue the discussion of articles on social platforms;
  • Encourage users to submit articles and images for contests;
  • Highlight your authors.

Listing Authors, And Why It’s A Good Thing

If you’re a publisher, your authors are your biggest asset. They are the content creators. Their writing gets consumed by millions of people all over the world.

Showcasing them exposes them for what they really are: authorities. Your authors will thank you for acknowledging them, and readers will get to see the human face behind the technology.

Coding The Perfect Author Listing

Here are the things we want to achieve with our page:

  • Build it as a WordPress plugin so that we can reuse it more easily;
  • Display the name, biography, number of posts and latest published post of all authors;
  • Paginate the listing if we have many authors;
  • Make the listing searchable.

Introducing WP_User_Query And get_users

wp_list_authors("show_fullname=1&optioncount=1&orderby=post_count&order=DESC&number=3");

Creating A Plugin And Shortcode With A Bit More Functionality

A simple and straightforward way to build our user listing would be to create a shortcode that we could include on any page we like. Housing this type of functionality in a plugin is ideal, so that we don’t have to worry about migrating it when we change the theme.

Let’s keep it simple. Our entire plugin will consist of just one file: simple-user-listing.php .

- Create a simple shortcode to list our WordPress users. Author: Cristian Antohe Version: 0.1 Author URI: http://cozmoslabs.com */ function sul_user_listing($atts, $content = null) { global $post; extract(shortcode_atts(array("role" => ’, "number" => "10"), $atts)); $role = sanitize_text_field($role); $number = sanitize_text_field($number); // We"re outputting a lot of HTML, and the easiest way // to do it is with output buffering from PHP. ob_start(); // Get the Search Term $search = (isset($_GET["as"])) ? sanitize_text_field($_GET["as"]) : false ; // Get Query Var for pagination. This already exists in WordPress $page = (get_query_var("paged")) ? get_query_var("paged") : 1; // Calculate the offset (i.e. how many users we should skip) $offset = ($page - 1) * $number; if ($search){ // Generate the query based on search field $my_users = new WP_User_Query(array("role" => $role, "search" => "*" . $search . "*")); } else { // Generate the query $my_users = new WP_User_Query(array("role" => "author", "offset" => $offset , "number" => $number)); } // Get the total number of authors. Based on this, offset and number // per page, we"ll generate our pagination. $total_authors = $my_users->total_users; // Calculate the total number of pages for the pagination $total_pages = intval($total_authors / $number) + 1; // The authors object. $authors = $my_users->get_results(); ?>

    ID); ?>
  • ID, 90); ?>

    ID); ?>">display_name; ?> - ID); ?> posts

    description; ?>

    ID&post_count=1"); if (!empty($latest_post->post)){ ?>

    Latest Article: post->ID) ?>"> post->ID) ;?>

    ID); ?> ">Read display_name; ?> posts

No authors found

Breaking Down The Code

The top of our plugin’s main PHP file must contain the standard header of information. This header tells WordPress that our plugin exists, and it adds it to the plugin management screen so that it can be activated, loaded and run.

/* Plugin Name: Simple User Listing Plugin URI: http://cozmoslabs.com description: >- Create a simple shortcode to list our WordPress users. Author: Cristian Antohe Version: 0.1 Author URI: http://cozmoslabs.com */

Creating a Shortcode

Adding a new shortcode in WordPress is rather easy. We find the function that returns the desired output (in our case, sul_user_listing), and then we add it using the add_shortcode WordPress function.

Function sul_user_listing($atts, $content = null) { // return our output } add_shortcode("userlisting", "sul_user_listing");

Extracting Our Shortcode Arguments

We want to be able to list users based on their roles and to control how many users are displayed on the page. We do this through shortcode arguments. We’ll add the shortcode to our theme in this way: . This will allow us to reuse the plugin to list our subscribers as well.

To do this, we need to use shortcode arguments:

Extract(shortcode_atts(array("role" => ’, "number" => "10"), $atts));

The extract function imports variables into our function from an array. The WordPress function shortcode_atts basically returns an array with our arguments; and we’ll set up some defaults in case none are found.

Note that the role default is an empty string , which would list all users regardless of their role.

Shortcodes Should Never Echo Stuff Out

The return value of a shortcode handler function gets inserted into the post content’s output in place of the shortcode. You should use return and not echo ; anything that is echoed will be outputted to the browser but will probably appear above everything else. You would also probably get “headers already sent” type of errors.

For simplicity, we’re buffering the output through ob_start() , so we put everything into an object and return it once we’re done.

Setting Up Our Variables

Now we can start building our listing of authors. First, we need to set up a few variables:

  • $search This takes the GET parameter as if it exists.
  • $page The get_query_var for the pagination. This already exists in WordPress.
  • $offset Calculate the offset (i.e. how many users to skip when paginating).
  • $total_authors Get the total number of authors.
  • $total_pages Calculate the total number of pages for the pagination.

The Query

We actually have two queries: the default listing and the search results.

If ($search){ // Generate the query based on search field $my_users = new WP_User_Query(array("role" => $role, "search" => "*" . $search . "*")); } else { // Generate the query $my_users = new WP_User_Query(array("role" => "author", "offset" => $offset , "number" => $number)); }

WP_User_Query->total_users and WP_User_Query->get_results

WP_User_Query provides us with two useful functions, among others:

  • total_users Returns the total number of authors. This, the offset and the number of users per page will generate our pagination.
  • get_results Returns an object with the authors alone. This is similar to what get_users() returns.

The Search Form

For the search, we’re using a simple form. There’s nothing complex here.

User Data and Listing the Authors

Looping through our results is fairly simple. However, getting information about users is a bit confusing in WordPress. You see, there are a lot of ways to get user data. We could get it directly from the returned query; we could use general functions such as get_userdata , get_user_meta , the_author_meta and get_the_author_meta ; or we could even use dedicated functions such as the_author_link and the_author_posts .

We’ll just use get_userdata plus two other functions: get_author_posts_url and get_avatar .

    ID); ?>
  • ID, 90); ?>

    ID); ?>">display_name; ?> - ID); ?> posts

    description; ?>

    ID&post_count=1"); if (!empty($latest_post->post)){ ?>

    Latest Article: post->ID) ?>"> post->ID) ;?>

    ID); ?> ">Read display_name; ?> posts

No authors found

Pagination

We need pagination because each listing will generate two extra queries. So, if we were listing 100 people, we would end up with 200 extra queries per page. That’s a bit much, so pagination is really needed. Otherwise, for websites with many authors, the load could get so heavy that it brings down the website.

Final Thoughts

We’ve discussed the code for an authors listing, but it has so many more uses:

  • List your company’s employees;
  • Showcase users who have won a competition (by listing users with the role of “winners”);
  • Present your company’s departments, each with its respective team (based on user roles).

If you allow users to register on your website, you could use more or less the same code to generate any listing of users based on your needs. If you require users to log in in order to comment (an effective way to stop automated spam), then listing users and their number of comments could increase engagement.

Have you used something similar for a project? If so, let us know in the comments!

Как появились ошибки

Странно, сайту каких-то две недельки и уже первые ошибки. Откуда? Подумал я. Захожу сегодня в Google инструменты, выбираю структурированные данные, дальше hentry (разметка: microformats) и вижу целых 19 ошибок!

Не пугайтесь, если у вас их 300 или 500, а может и еще больше - оказалось решить проблему, связанную со структурированными данными не так уж и сложно.

Как исправить ошибки структурированных данных author, entry-title и updated

— копируем на компьютер файлы, в которых будем делать изменения (в данном случае, скорее всего бок в: single.php, search.php, index.php, archive.php). Так у меня было ;

— делаем еще одну копию этих файлов (их мы будем изменять, и заливать через Filezilla после внесения изменений).

Для того, чтобы вы не запутались, я разделю свою пост на условные части, в каждой из которых расскажу как избавиться от трех проблем сразу. Начинаем?

Ошибка и решение проблемы entry-title. Нет сведений о заголовке статьи.

Теперь только начал понимать, что английский учить нужно было лучше. Здесь собственно все банально. Исправляется ошибка добавлением словосочетания entry-title.

Делается это следующим образом: ищем в редактируемом файле или файлах (у меня во всех четырех была конструкция, которая отвечает за вывод сведений о заголовке) часть кода: или похожую на нее (не по знакам вопроса, а по словосочетанию php the_title).

Внимание ваш код может отличаться, но есть большая вероятность, что он аналогичен или очень похож. После того когда нашли, нам понадобиться добавить entry-title. Собственно как было и стало у меня видно на картинке:

Не пугайтесь, если entry-title надо будет прописать в немножко отдаленном месте от , хотя меня это, честно говоря смутило (боялся что не получиться), но, метод тыка) помог. Дальше будет легче.

Внимание, не забываем проделывать подобное во всех файлах, о которых я писал выше.

Решение проблемы updated - нет сведений о дате публикации статьи.

Здесь нам надо будет добавить к части кода php the_time или php the_date (у кого как) class=»updated» и заключить конструкцию в тег . Кто не знает - смотрим на картинку:

Избавиться от проблемы структурированных данных author. Ошибка - пропал автор 🙂 .

Конечно же, было бы не правильно не позаботиться об авторе, раз уже все сделали. Если вы были внимательны, то уже могли бы и без меня справиться и найти часть кода php the_author, чтобы проделать все как на картинке:

Кстати, порадовало то, что сразу можно проверить устранена ли проблема. Вбивать ненужные символы не буду, просто рекомендую посмотреть на картинки.

Всем привет! Сегодня мы с вами рассмотрим структуру любого шаблона WordPress сайта. Из каких базовых файлов и элементов она строится. Эти знания придадут вам уверенности в изменении и правке чужих шаблонов. А впоследствии, при наличии базовых знаний HTML, CSS, и PHP, создавать свои собственные темы. Но пока что мы так далеко заглядывать не будем, начнем с азов.

Основные файлы любого шаблона. Их назначение.

И так, любой шаблон по своей сути должен состоять из 10 базовых файлов. Так что давайте разбираться в них.

Пример структуры WordPress шаблона

style.css — файл таблицы стилей шаблона. Этот файл должен быть у любой темы, так как именно он отвечает за ее объявление, а так же может хранить дополнительную информацию: имя автора шаблона, версию шаблона, домашнюю страницу автора и т.д. Ну и, конечно же, прямое назначение — это все CSS стили.

index.php — файл отвечает за отображение главной страницы WordPress шаблона. При верстке своего макеты всегда помните, что главная страница может быть как статичной, так и динамичной.

single.php — файл, отвечающий за вывод каждого отдельного поста вашей темы. В качестве примера можно привести данную статью, которую вы читаете.

page.php — файл отвечает за формирование статичных страниц. Обычно это страницы: контакты, об авторе, о ресурсе и т.д.

header.php — формирует шапку сайта, и хранит в себе все важные метатеги для продвижения.

footer.php — файл отвечает за отображение подвала сайта.

sidebar.php — формирует отображение сайдбара или по-русски боковой колонки блога или сайта.

functions.php — файл, отвечающий за дополнительный функционал шаблона. Например: вывод последних комментаторов на моем блоге формируется именно в этом файле.

comments.php — файл отвечает за отображение комментариев у шаблона.

404.php — отвечает за отображение страницы с 404 ошибкой.

search.php — файл, отвечающий за отображение страницы поиска.

Необязательные файлы. Но об их существовании нужно знать.

category.php — файл отвечает за отображение анонсов в категориях (если файла нет, то формирование осуществляется за счет файла index.php)

tag.php — файл отвечает за отображение анонсов на странице тегов (если файла нет, то формирование осуществляется за счет файла index.php)

taxonomy.php — файл отвечает за отображение анонсов на страницах таксономии (если файла нет, то формирование осуществляется за счет файла index.php)

author.php — файл отвечает за отображение анонсов статей определенного автора (если файла нет, то формирование осуществляется за счет файла index.php)

attachment.php — отвечает за вывод прикрепленного файла.

searchform.php — отвечает за формирование формы поиска.

Если в вашем шаблоне присутствуют файлы из не обязательного списка, то вы должны знать, они всегда имеют приоритет выше, чем файл index.php. Это можно объяснить тем, что index.php — это общий случай, а допустим tag.php — это уже частный. Те более конкретный, следовательно, его и нужно воспринимать.

А что хранится в папках?

Папки обычно служат для хранилища определенного типа файлов. Например: папка(image, images, img и тд) хранит в себе файлы изображений, которые относятся к данной теме. Папка JS хранит файлы скриптов. Папка inc хранит php файлы, которые инклюдятся (включаются) в существующие файлы темы.

Такого рода папок может быть сколько угодно, и называться они могут по-разному. Суть их в том, чтобы устранить бардак в шаблоне, и привести все к какой-либо иерархии.

Screenshot.png — это что за зверь?

Обычно этот файл содержит скриншот шаблона, чтобы в админке, когда вы выбирали тему для сайта или блога, могли видеть ее в качестве миниатюры. Размер этого файлика должен быть 880x660px.

Визуальное представление структуры шаблона

Схематичное изображение wordpress шаблона

Как видите, структура, которая на рисунке, соответствует структуре моего блога. Несмотря на то, что шаблоны разных авторов выглядят по-разному, все они имеют в своей основе вышеперечисленные файлы.