Как создать тему WordPress. Урок 1. Создание и наполнение Index.php и style.css

Как создать тему WordPress? Тем кто впервые сталкивается с подобной задачей будет не просто, но изучив материал данного и последующих руководств вы научитесь создавать шаблоны для CMS WordPress. В данной публикации мы начнем наполнять файлы index.php и style.css что позволит нам перейти от теории к практике и уже видеть первые результаты на экранах монитора.


В предыдущем уроке, где мы рассматривали некоторые понятия, на которые стоит обратить внимание перед началом разработки шаблона WordPress, мы создали целый ряд файлов. Основным и главным файлом любой темы считается index.php, в помощь которому приходит style.css, отвечающий за настройку внешнего вида сайта.

Именно этих два файла мы и рассмотрим поподробнее. Для начала проверим их наличие, если оба файла существуют, идем дальше и откроем первый из них в редакторе NodePad++.

Наполняем index.php темы WordPress

Хочу заметить что наполнять все файлы мы будем постепенно и если вы не увидите каких-то атрибутов или элементов, значит они будут добавлены в дальнейшем с подробным объяснением.

Итак, отрываем индексный файл и вписываем в него следующий код:

<!DOCTYPE html>
<html>
<head></head>
<body>
<div id=»header»>
<h1 class=»site-title»>Site Title</h1>
<div class=»nav-menu»></div>
</div>
<div id=»main»>
<div class=»post»></div>
</div>
<div id=»sidebar»>
<div class=»widget»></div>
</div>
<div id=»footer»></div>
</body>
</html>

1234567891011121314151617

<!DOCTYPE html><html> <head></head>  <body>   <div id=»header»>    <h1 class=»site-title»>Site Title</h1>    <div class=»nav-menu»></div>   </div>   <div id=»main»>    <div class=»post»></div>   </div>   <div id=»sidebar»>    <div class=»widget»></div>   </div>   <div id=»footer»></div> </body></html>

Как мы можем видеть мы поделили страницу на 4 основных части — header, main, sidebar и footer. Уже сейчас нашу тему можно активировать и посмотреть на белый экран с единственной надписью «Site Title».
Пока остановимся на этом и пойдем к style.css, шапку которого нужно оформить по некоторым правилам.

Файл style.css в WordPress, добавление базовой информации о теме

По правилам файл style.css в WordPress должен иметь следующий комментарий в начале:

/*Theme Name: My First Theme
Theme URI: http://yrokiwp.ru
Author: Alex Spivak
Author URI: http://yrokiwp.ru
Description: Описание темы
Version: 1.0*/

123456

/*Theme Name: My First ThemeTheme URI: http://yrokiwp.ruAuthor: Alex SpivakAuthor URI: http://yrokiwp.ruDescription: Описание темыVersion: 1.0*/

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

* {
margin:0; /*Обнуляем все отступы, в нужных местах добавим их*/
padding:0;
}
body {
font-family: Arial, Helvetica, sans-serif; /*задаем основной шрифт текста*/
display:block; /*Заставляем все элементы вести себя как блочные*/
}

12345678

* {margin:0; /*Обнуляем все отступы, в нужных местах добавим их*/padding:0;}body {font-family: Arial, Helvetica, sans-serif; /*задаем основной шрифт текста*/display:block; /*Заставляем все элементы вести себя как блочные*/}

Правила в файл стилей будем добавлять по мере рассмотрения каждого участка кода, по этому оставляем style.css и вернемся к нашему  index.php.

Разбиваем index.php на несколько файлов

В WordPress существует большое количество встроенных функций, которые ускоряют создание шаблона. В данном случае мы поговорим о get_header(), get_sidebar(), get_footer().

Итак, приступим к формированию структуры сайта, вынесем в отдельные файлы те части, которые будут повторяться на всех страницах сайта, это шапка, сайд бар и подвал.

Открываем файл header.php. Вырезаем с index.php следующий участок кода и вставляем его в header.php:

<!DOCTYPE html>
<html>
<head></head>
<body>
<div class=»header»>
<h1 class=»site-title»>Site Title</h1>
<div class=»nav-menu»></div>
</div>

12345678

<!DOCTYPE html><html> <head></head>  <body>   <div class=»header»>    <h1 class=»site-title»>Site Title</h1>    <div class=»nav-menu»></div>   </div>

Аналогичную операцию проводим с sidebar.php участок кода следующий:

<div id=»sidebar»>
<div class=»widget»></div>
</div>

123

<div id=»sidebar»> <div class=»widget»></div></div>

Последний момент с footer.php:

<div id=»footer»></div>
</body>
</html>

123

  <div id=»footer»></div> </body></html>

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

<?php get_header(); ?>
<div class=»main»>
<div class=»post»></div>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

123456

<?php get_header(); ?> <div class=»main»>  <div class=»post»></div> </div><?php get_sidebar(); ?><?php get_footer(); ?>

Теперь немного добавим функций в индексный файл и выведем названия постов с ссылками на их страницы.

<?php get_header(); ?>
<div class=»main»>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class=»post»>
<h2><a href=»<?php the_permalink(); ?>»><?php the_title(); ?></a></h2>
</div>
<?php endwhile; else: ?>
<p><?php _e(‘Простите, но публикаций пока нет.’); ?></p>
<?php endif; ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

123456789101112

<?php get_header(); ?> <div class=»main»><?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>  <div class=»post»>   <h2><a href=»<?php the_permalink(); ?>»><?php the_title(); ?></a></h2>  </div><?php endwhile; else: ?>   <p><?php _e(‘Простите, но публикаций пока нет.’); ?></p><?php endif; ?> </div><?php get_sidebar(); ?><?php get_footer(); ?>

Можем сохранить настройки и посмотреть что у нас получилось. Зрелище не из приятных. Белый холст с ссылками при переходе по которым ничего не написано. Не переживайте это только основы, всему свое время, все приведем в порядок. Обсудим функции, которые мы применили.

Сначала мы запустили цикл WordPress, внутри него вывели несколько функций и в конце задали условие, в случае отсутствия постов.

Собственно обсуждать нам нужно только одну строчку, остальное сделайте так как написано:

<h2><a href=»<?php the_permalink(); ?>»><?php the_title(); ?></a></h2>

1

<h2><a href=»<?php the_permalink(); ?>»><?php the_title(); ?></a></h2>

Функция the_permalink() выводит URL поста, который в данный момент обрабатывается внутри цикла.

Следующая функция the_title() выведет заголовок поста, с этим думаю понятно.

Давайте подведем итог данного урока по созданию темы WordPress. Что же мы сделали сегодня:

  • Создали структуру страницы;
  • разбили индексный файл на несколько частей и поместили каждый из них в свой собственный файл;
  • подключили файлы шаблона к индексному;
  • запустили цикл WordPress;
  • вывели заголовки постов с ссылками на материал.

На сегодня все, основная задача данного урока выполнена, в следующий раз займемся шапкой сайта, мета тегами и навигационным меню, а так же продолжим наполнять файл style.css. Не пропустите следующий урок, подписывайтесь на рассылку и продолжайте вместе с нами делать шаблон для CMS WordPress.

Related Articles

38 Comments

  1. Woah! I’m really digging the template/theme of this site.
    It’s simple, yet effective. A lot of times it’s tough
    to get that «perfect balance» between usability and visual appearance.

    I must say that you’ve done a fantastic job wiith this. In addition, the blog
    loads very quick ffor me on Opera. Exceptional Blog!

    Heree iss my web page; Venus

  2. You really make it seem so easy with your presentation but I find
    this topic to be actually something which I think I would never understand.
    It seems too complicated and extremely broad for me. I’m looking forward for
    your next post, I will try to gget the hang of it!

    My blog post — Double Headstones

  3. Заказать диплом ВУЗа. Покупка документа о высшем образовании через качественную и надежную фирму дарит много преимуществ для покупателя. Это решение дает возможность сберечь как личное время, так и значительные финансовые средства. promintern.listbb.ru/viewtopic.php?f=16&t=1628

  4. Guidelines for Selecting a Trustworthy Online Casino
    Choosing a High Trust Online Casino for Secure Play
    In a vast sea of virtual betting platforms, discerning which site to trust can be challenging.
    Many factors contribute to the credibility of these gaming sites, and understanding them can significantly
    enhance your experience. Prioritizing safety and fairness should be your foremost objective when engaging in online gaming.

    Before committing your funds, examine the licensing information. Reputable sites typically hold licenses from established regulatory bodies that ensure compliance with legal and
    fair gaming practices. Displaying this information prominently signals transparency and accountability, which are hallmarks of respectable establishments.

    Additionally, scrutinizing player reviews and
    testimonials can provide practical insights into others’ experiences.
    A solid reputation among users often reflects the site’s reliability.
    Moreover, pay attention to the variety and quality of games offered,
    as well as the fairness of the associated rules. Games should utilize Random
    Number Generators (RNGs) to guarantee an unbiased
    outcome, setting the stage for a level playing field.
    Lastly, explore the customer support options available.
    An efficient support system indicates that the platform values its players and is
    prepared to address concerns swiftly. A robust and responsive support feature can make a
    significant difference in your overall satisfaction with the
    service.
    Key Factors to Evaluate Casino Licensing and Regulation
    Understanding the licensing and regulatory framework of a gaming platform is paramount for users seeking a secure experience.
    Each jurisdiction has its requirements, so it’s crucial to research the governing authorities involved.
    Commonly respected regulators include the Malta Gaming Authority,
    UK Gambling Commission, and Gibraltar Regulatory Authority.
    These entities enforce standards that ensure player protection and fair play.

    Verify the license number displayed on the site; this can typically be cross-referenced with the regulator’s database.
    A valid license demonstrates that the operator has met specific criteria,
    including financial stability and operational integrity.

    Be cautious if a platform does not display this information clearly.

    Investigate what regulations the operator adheres to. Some jurisdictions mandate regular audits by independent firms to ensure fairness
    in games. A reputable platform showcases its commitment to transparency through certifications from
    organizations like eCOGRA or iTech Labs, which conduct these evaluations.

    Consider the legal frameworks concerning player rights. Regulations
    often outline how disputes can be resolved and provide guidelines on payment processing
    times. Familiarizing yourself with these can prevent
    potential conflicts. Look for clarity in withdrawal procedures and mechanisms for addressing
    grievances.
    Lastly, assess the reputation of the gaming operator within player
    communities. Player reviews and forums can provide insight into experiences associated with
    license compliance and regulatory issues. Check for any past violations reported by regulatory authorities that may raise concern about the operator’s reliability.

    How to Assess Casino Reputation through Player Reviews and Ratings
    Evaluating a gaming venue’s reputation is crucial before placing any bets.
    Player feedback serves as a valuable resource for potential customers.

    Here are some effective methods to gauge how a platform is perceived.

    1. Explore Multiple Review Platforms
    Instead of relying on a single source, check various sites
    dedicated to player experiences. Websites like Trustpilot, Reddit, and
    dedicated gambling forums often feature candid opinions.

    Look for trends in feedback, noting both positive
    and negative aspects highlighted by users.
    2. Focus on Recency
    Recent reviews provide a clearer picture of the current state
    of a gaming site. Platforms might change policies, software,
    or management over time. Pay attention to reviews from the last
    six months to ensure your insights reflect the latest user
    experience.
    3. Analyze the Ratings
    Most platforms offer a star rating system. A high overall score
    can be a good indicator, but dive deeper. Examine the distribution of scores.
    A mix of five-star and one-star reviews can indicate polarizing experiences, while a consistent middle ground could suggest mediocrity.

    4. Investigate Responses from the Platform
    Trustworthy venues often engage with their audience.

    Check if the management responds to feedback, both positive and negative.
    Constructive replies can demonstrate a commitment to customer satisfaction and transparency.

    5. Seek Out Specific Issues
    Common complaints may point to systemic problems.
    Look for patterns in feedback related to payout speed,
    customer support, or game variety. If multiple players report similar issues, take those concerns
    seriously.
    6. Balance Negative with Positive
    While negatives are important, balance them with positive notes.
    A few negative reviews among many satisfied customers can indicate the venue is
    generally reliable. Aim for a holistic understanding, rather than fixating on isolated
    incidents.
    7. Consider the Volume of Reviews
    A site with numerous reviews generally reflects more reliable
    opinions than one with only a handful. More reviews can lead to a
    better overall assessment, reducing the impact of outliers.

    In conclusion, a careful examination of player reviews and ratings forms an essential part of evaluating an establishment’s
    reliability. By conducting thorough research, potential
    players can make more informed decisions.

    My blog aviator demo

  5. Fantastic blog you have here but I was wanting
    to know if you knew of any community forums that
    cover the same topics discussed in this article? I’d really love
    to be a part of online community where I can get feedback from other knowledgeable individuals that share the same interest.
    If you have any recommendations, please let me know. Kudos!

  6. Heya i am for the first time here. I came across this
    board and I find It truly useful & it helped me out much.
    I hope to give something back and aid others like you
    aided me.

  7. I got this web page from my pal who told me about this website and at the moment this time I am browsing this website and reading very informative posts at
    this time.

  8. The Girl Behind the Digital Screen

    In a virtual space full of light,
    There is a girl dancing words and laughter,
    Greeting the world without pause,
    Through the screen, hope is built.

    Free tokens are like twilight rain,
    Dripping slowly on the fingertips,
    Every smile, every glance,
    Becoming a code, becoming a promise.

    Behind the spotlight and pixels,
    There is an unspoken longing,
    The girl is waiting, waiting for the wave,
    From those who are present without a name.

    Not just numbers on the screen,
    Not just tokens that flow,
    There is a story, there is a feeling,
    In every second that rolls.

    Long nights become witnesses,
    Live cam girls dance in silence,
    Weaving dreams, reaching for meaning,
    In a virtual world that is never quiet.

  9. Thank you for every other informative site. Where else could I
    get that kind of information written in such an ideal manner?
    I’ve a undertaking that I’m just now running on, and I
    have been at the look out for such info.

  10. Hello there, just became aware of your blog through Google, and
    found that it is really informative. I am going to
    watch out for brussels. I will be grateful if you continue this in future.
    A lot of people will be benefited from your writing.
    Cheers!

  11. Hi, Neat post. There’s an issue along with your website in web explorer, might check this?

    IE nonetheless is the market chief and a good part
    of people will pass over your excellent writing due to this problem.

  12. link porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno grafi link
    porno grafilink porno grafilink porno grafi link porno grafilink
    porno grafilink porno grafi link porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno grafi
    link porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno grafi
    link porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno
    grafi link porno grafilink porno grafilink porno grafi
    link porno grafilink porno grafilink porno grafi link
    porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno grafi
    link porno grafilink porno grafilink porno grafi
    link porno grafilink porno grafilink porno grafi link porno
    grafilink porno grafilink porno grafi link porno grafilink
    porno grafilink porno grafi link porno grafilink porno grafilink
    porno grafi link porno grafilink porno grafilink porno grafi link
    porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno grafi link porno grafilink porno
    grafilink porno grafi link porno grafilink porno grafilink porno grafi
    link porno grafilink porno grafilink porno grafi link
    porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno grafi link
    porno grafilink porno grafilink porno grafi
    link porno grafilink porno grafilink porno grafi link porno grafilink porno
    grafilink porno grafi link porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno grafi link
    porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink
    porno grafi link porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno grafi link porno grafilink porno
    grafilink porno grafi link porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno grafi link porno
    grafilink porno grafilink porno grafi link porno grafilink
    porno grafilink porno grafi link porno grafilink porno grafilink porno
    grafi link porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink
    porno grafi link porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno grafi link
    porno grafilink porno grafilink porno grafi link porno
    grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno grafi
    link porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink
    porno grafi link porno grafilink porno grafilink porno grafi link porno
    grafilink porno grafilink porno grafi link porno grafilink porno grafilink
    porno grafi link porno grafilink porno grafilink porno grafi link porno grafilink porno grafilink porno grafi
    link porno grafilink porno grafilink porno grafi link porno grafilink
    porno grafilink porno grafi

  13. Hmm it looks like your site ate my first comment (it was extremely long) so I guess I’ll just sum it
    up what I wrote and say, I’m thoroughly enjoying your
    blog. I too am an aspiring blog writer but I’m still new to the whole thing.
    Do you have any tips for first-time blog writers? I’d definitely appreciate
    it.

  14. Thanks on your marvelous posting! I certainly enjoyed reading
    it, you might be a great author. I will make sure to bookmark your blog and will come back
    later in life. I want to encourage that you continue your
    great posts, have a nice holiday weekend!

  15. Женский онлайн-портал https://sweaterok.com.ua это не просто сайт, а поддержка в повседневной жизни. Честные темы, важные вопросы, советы и тепло. От эмоций до материнства, от тела до мыслей.

Добавить комментарий для web site Отменить ответ

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Back to top button
Close