wordpress学习笔记

php是一种服务端语言,计算只发生在服务器,用户只看到结果

可以随时通过

<?php ?>

来进入php模式

使用$符号来创建变量,如

$myname='binbin';

使用echo来输出内容,如

<h1>我的名字是<?php echo $myname ?></h1>

创建新主题

  1. 在文件夹Local Sites\doraemeng\app\public\wp-content\themes下创建新文件夹,起名为自己的主题名
  2. 使用visual studio打开文件夹
  3. 用vs在文件夹下创建index.php和style.css
  4. style.css的开头要用注释的方式写下主题名等信息,如下:
/*

    Theme Name: 想要的主题名
    Author:作者名
    Version:版本号

*/
  1. 保存后就可以看到了
  2. 要添加预览图,需要在自己新建的主题文件夹下添加图片文件,命名为screenshot.png,分辨率最好是1200:900
  3. index.php就是点开网站会看到的页面

Function函数/方法

在index.php进入php模式 ,在php模式中定义函数,调用函数,如下:

<?php
 function greet($name,$color){
     echo "<p>Hello, my name is $name and my favorite color is $color.</p>";
 }

 myFirstFunction('wen','red');
 myFirstFunction('bin','black');
?>

<h1><?php blogInfo('name'); ?></h1>

<p><?php blogInfo('description'); ?></p>

数组

数组是多个值的组合

<?php 

    $names=array('wen','bin');
    $counts=0;
    while($counts<count($names){
        echo"<li>hi, my name is $names[$counts]</li>";
        $counts++;
    }

?>

文章的循环展示

在index.php写循环,通过have_posts()获取文章判断数量,用the_post获取单个文章,用the_title和the_content获取标题和内容并显示出来,通过在标题加入<a></a>来变成超链接,通过php模式下的the_permalink来获得对应文章链接,用<hr></hr>加横线分割:

<?php 

    while(have_posts()){
        the_post();?>
        <h2><a href="<?php the_permalink();?>"><?php the_title(); ?></a></h2>
        <?php the_content();?>
        <hr>
    <?php }

?>

为了让点进去后的文章标题不是链接的形式,新建single.php,将其内容设定为

<?php 

    while(have_posts()){
        the_post();?>
        <h2><?php the_title(); ?></h2>
        <?php the_content();?>
    <?php }

?>

发现单个文章内的标题不再是链接的样式
可知:

  • wordress对主页使用index.php
  • wordress对单篇文章(post)使用single.php
  • wordress对页面(page)使用page.php,沒的話就找index.php

页眉和页尾(header和footer)

  1. 建立header.php和footer.php,在里面用html写上内容
  2. 在需要的地方使用php模式下的get_header();和get_footer();

在前端加载css文件

  1. 在header.php文件编写以下代码:
<!DOCTYPE html>
<html>
    <head> //head部分本来一般是使用link标签加载css的地方
        <?php wp_head();?> //在word-4press使用这个就行
    </head>
    <body>
    <h1>Fictional University</h1>
    </body>
</html>
  1. 创建functions.php文件,编写以下代码,add_action表示让wordpress在参数1的时间点执行参数2的函数,university_files就是自己编的函数,在其中通过使用wp_enquene_style来让wordpress加载位于位置参数2的名称为参数1的css文件:
<?php 

function university_files(){
    wp_enqueue_style('university_main_styles',get_stylesheet_uri());//参数2可以自己指定位置,也可以像这样让wordpress函数代入默认的
}//如果想加载javascript文件,可以写wp_enqueue_script

add_action('wp_enqueue_scripts','university_files'); //add_function是很好用的一个wordpress函数

?>

让Wordpress的黑色管理栏出现在所有的地方

  1. 把header.php最下面的</body></html>转移到footer.php
  2. 在footer.php的</body>前面加上一段php(经验谈:在body即将结束的时候加载javascript文件比较好)
    变化之后的footer.php:
<p>Hello from footer.php</p>

<?php wp_footer();?>
</body>
</html>

把静态的HTML和CSS页面转换到WordPress页面

  1. 可以从这里下载案例文件
  2. 把案例文件的index.html中的<header>部分复制到自己的header.php部分,就可以看到变化了
  3. 把index.html中的<footer>部分复制到自己的footer.php部分
  4. 把university-static-master文件夹下的build、css、images和src四个文件夹复制到自己的主题文件夹下,和自己的index.php在同一层级就行
  5. 在functions.php文件中修改代码,让特定部分的css指向新的文件夹
    变化之后的functions.php:
 <?php 

function university_files(){
    wp_enqueue_style('university_main_styles',get_theme_file_uri('/build/style-index.css');
    wp_enqueue_style('university_extra_styles',get_theme_file_uri('/build/index.css'));
}

add_action('wp_enqueue_scripts','university_files');

?>
  1. 修改之后发现网页的页尾没有加载图标,可以在原来的index.html中的<head>部分发现一个指向font-awesome的链接,可以把它加在自己的index.php,但更好的办法还是加在functions.php中,这样可以更好地控制,修改过后的functions.php如下:
 <?php 

function university_files(){
    wp_enqueue_style('font-awesome','https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css'));//第二个参数直接写文本,可以加载网络上的外部文件
    wp_enqueue_style('university_main_styles',get_theme_file_uri('/build/style-index.css'));
    wp_enqueue_style('university_extra_styles',get_theme_file_uri('/build/index.css'));
}

add_action('wp_enqueue_scripts','university_files'); 

?>
  1. 更改网页文本使用的字体,同样更改functions.php:
 <?php 

function university_files(){
    wp_enqueue_style('custom-google-fonts','//fonts.googleapis.com/css?family=Roboto+Condensed:300,300i,400,400i,700,700i|Roboto:100,300,400,400i,700,700i');
    wp_enqueue_style('font-awesome','//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css');
    wp_enqueue_style('university_main_styles',get_theme_file_uri('/build/style-index.css'));
    wp_enqueue_style('university_extra_styles',get_theme_file_uri('/build/index.css'));
}

add_action('wp_enqueue_scripts','university_files'); 

?>
  1. 复制示例网页中的欢迎页、双列布局和幻灯片,在示例文件的index.html中,把<header><footer>之间的部分(也就是page banner部分)复制到index.php,复制前要让index.php中的get_header和get_footer都分别进入php模式,中间留出的区域来放置html内容,修改之后如下:
<?php     get_header(); ?>

<div class="page-banner">
      <div class="page-banner__bg-image" style="background-image: url(images/library-hero.jpg)"></div>
      <div class="page-banner__content container t-center c-white">
        <h1 class="headline headline--large">Welcome!</h1>
        <h2 class="headline headline--medium">We think you&rsquo;ll like it here.</h2>
        <h3 class="headline headline--small">Why don&rsquo;t you check out the <strong>major</strong> you&rsquo;re interested in?</h3>
        <a href="#" class="btn btn--large btn--blue">Find Your Major</a>
      </div>
    </div>

    <div class="full-width-split group">
      <div class="full-width-split__one">
        <div class="full-width-split__inner">
          <h2 class="headline headline--small-plus t-center">Upcoming Events</h2>

          <div class="event-summary">
            <a class="event-summary__date t-center" href="#">
              <span class="event-summary__month">Mar</span>
              <span class="event-summary__day">25</span>
            </a>
            <div class="event-summary__content">
              <h5 class="event-summary__title headline headline--tiny"><a href="#">Poetry in the 100</a></h5>
              <p>Bring poems you&rsquo;ve wrote to the 100 building this Tuesday for an open mic and snacks. <a href="#" class="nu gray">Learn more</a></p>
            </div>
          </div>
          <div class="event-summary">
            <a class="event-summary__date t-center" href="#">
              <span class="event-summary__month">Apr</span>
              <span class="event-summary__day">02</span>
            </a>
            <div class="event-summary__content">
              <h5 class="event-summary__title headline headline--tiny"><a href="#">Quad Picnic Party</a></h5>
              <p>Live music, a taco truck and more can found in our third annual quad picnic day. <a href="#" class="nu gray">Learn more</a></p>
            </div>
          </div>

          <p class="t-center no-margin"><a href="#" class="btn btn--blue">View All Events</a></p>
        </div>
      </div>
      <div class="full-width-split__two">
        <div class="full-width-split__inner">
          <h2 class="headline headline--small-plus t-center">From Our Blogs</h2>

          <div class="event-summary">
            <a class="event-summary__date event-summary__date--beige t-center" href="#">
              <span class="event-summary__month">Jan</span>
              <span class="event-summary__day">20</span>
            </a>
            <div class="event-summary__content">
              <h5 class="event-summary__title headline headline--tiny"><a href="#">We Were Voted Best School</a></h5>
              <p>For the 100th year in a row we are voted #1. <a href="#" class="nu gray">Read more</a></p>
            </div>
          </div>
          <div class="event-summary">
            <a class="event-summary__date event-summary__date--beige t-center" href="#">
              <span class="event-summary__month">Feb</span>
              <span class="event-summary__day">04</span>
            </a>
            <div class="event-summary__content">
              <h5 class="event-summary__title headline headline--tiny"><a href="#">Professors in the National Spotlight</a></h5>
              <p>Two of our professors have been in national news lately. <a href="#" class="nu gray">Read more</a></p>
            </div>
          </div>

          <p class="t-center no-margin"><a href="#" class="btn btn--yellow">View All Blog Posts</a></p>
        </div>
      </div>
    </div>

    <div class="hero-slider">
      <div data-glide-el="track" class="glide__track">
        <div class="glide__slides">
          <div class="hero-slider__slide" style="background-image: url(images/bus.jpg)">
            <div class="hero-slider__interior container">
              <div class="hero-slider__overlay">
                <h2 class="headline headline--medium t-center">Free Transportation</h2>
                <p class="t-center">All students have free unlimited bus fare.</p>
                <p class="t-center no-margin"><a href="#" class="btn btn--blue">Learn more</a></p>
              </div>
            </div>
          </div>
          <div class="hero-slider__slide" style="background-image: url(images/apples.jpg)">
            <div class="hero-slider__interior container">
              <div class="hero-slider__overlay">
                <h2 class="headline headline--medium t-center">An Apple a Day</h2>
                <p class="t-center">Our dentistry program recommends eating apples.</p>
                <p class="t-center no-margin"><a href="#" class="btn btn--blue">Learn more</a></p>
              </div>
            </div>
          </div>
          <div class="hero-slider__slide" style="background-image: url(images/bread.jpg)">
            <div class="hero-slider__interior container">
              <div class="hero-slider__overlay">
                <h2 class="headline headline--medium t-center">Free Food</h2>
                <p class="t-center">Fictional University offers lunch plans for those in need.</p>
                <p class="t-center no-margin"><a href="#" class="btn btn--blue">Learn more</a></p>
              </div>
            </div>
          </div>
        </div>
        <div class="slider__bullets glide__bullets" data-glide-el="controls[nav]"></div>
      </div>
    </div>

    <?php get_footer();
?>
  1. 发现网页发生变化,但缺失图片和PPT形式,通过在代码中对应到正确的图片位置来修复,比如原本是images/library-hero.jpg,现在文件的位置应该是wp-content/themes/fictional-university-theme/images/library-hero.jpg,但这样打太长了,所以可以使用一个php函数来代替,代码为<?php echo get_theme_file_uri('/images/library-hero.jpg')?>,这样括号之前的内容就会自动生成主题文件夹的路径,更改后的几个图片位置行如下:
     <div class="page-banner__bg-image" style="background-image: url(<?php echo get_theme_file_uri('/images/library-hero.jpg')?>);"></div>
     <div class="hero-slider__slide" style="background-image: url(<?php echo get_theme_file_uri('/images/bus.jpg')?>)">
      <div class="hero-slider__slide" style="background-image: url(<?php echo get_theme_file_uri('/images/apples.jpg')?>)">
      <div class="hero-slider__slide" style="background-image: url(<?php echo get_theme_file_uri('/images/bread.jpg')?>)">
  1. 现在图片可以显示了,但没有PPT滚动,在functions.php加载javascript文件来实现这一功能,修改后如下:
 <?php 

function university_files(){
    wp_enqueue_script('main-university-js',get_theme_file_uri('/build/index.js'), array('jquery'),'1.0',true);
    //参数1是名字,随便取;参数2是文件的路径和名字;参数3是此脚本是否对其他脚本有依赖,有就写没有就写NULL,一般都有;参数4是版本号随便写;参数5是问是否要在正文的body标签前加载,一般true比较好
    wp_enqueue_style('custom-google-fonts','//fonts.googleapis.com/css?family=Roboto+Condensed:300,300i,400,400i,700,700i|Roboto:100,300,400,400i,700,700i');
    wp_enqueue_style('font-awesome','//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css');
    wp_enqueue_style('university_main_styles',get_theme_file_uri('/build/style-index.css'));
    wp_enqueue_style('university_extra_styles',get_theme_file_uri('/build/index.css'));
}

add_action('wp_enqueue_scripts','university_files'); 

?>

内部页面模板

  1. 从interior.html中复制page-banner部分,粘贴到自己的page.php里,粘贴前删除循环中的部分,结果如下:
<?php 
    get_header();
    while(have_posts()){
        the_post();?>
        <div class="page-banner">
      <div class="page-banner__bg-image" style="background-image: url(images/ocean.jpg)"></div>
      <div class="page-banner__content container container--narrow">
        <h1 class="page-banner__title">Our History</h1>
        <div class="page-banner__intro">
          <p>Learn how the school of your dreams got started.</p>
        </div>
      </div>
    </div>

    <div class="container container--narrow page-section">
      <div class="metabox metabox--position-up metabox--with-home-link">
        <p>
          <a class="metabox__blog-home-link" href="#"><i class="fa fa-home" aria-hidden="true"></i> Back to About Us</a> <span class="metabox__main">Our History</span>
        </p>
      </div>

      <div class="page-links">
        <h2 class="page-links__title"><a href="#">About Us</a></h2>
        <ul class="min-list">
          <li class="current_page_item"><a href="#">Our History</a></li>
          <li><a href="#">Our Goals</a></li>
        </ul>
      </div>

      <div class="generic-content">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officia voluptates vero vel temporibus aliquid possimus, facere accusamus modi. Fugit saepe et autem, laboriosam earum reprehenderit illum odit nobis, consectetur dicta. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos molestiae, tempora alias atque vero officiis sit commodi ipsa vitae impedit odio repellendus doloremque quibusdam quo, ea veniam, ad quod sed.</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officia voluptates vero vel temporibus aliquid possimus, facere accusamus modi. Fugit saepe et autem, laboriosam earum reprehenderit illum odit nobis, consectetur dicta. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos molestiae, tempora alias atque vero officiis sit commodi ipsa vitae impedit odio repellendus doloremque quibusdam quo, ea veniam, ad quod sed.</p>
      </div>
    </div>
    <?php }
    get_footer();
?>
  1. 挖空原本的静态html界面,添加新的wordpress函数,比如删除原本的文本换为php模式下的函数,添加上页面对应的标题和内容,把静态的段落<p>改成php函数the_title();或者the_content();改动后如下:
<?php 
    get_header();
    while(have_posts()){
        the_post();?>
        <div class="page-banner">
      <div class="page-banner__bg-image" style="background-image: url(images/ocean.jpg)"></div>
      <div class="page-banner__content container container--narrow">
        <h1 class="page-banner__title"><?php the_title(); ?></h1>
        <div class="page-banner__intro">
          <p>Learn how the school of your dreams got started.</p>
        </div>
      </div>
    </div>

    <div class="container container--narrow page-section">
      <div class="metabox metabox--position-up metabox--with-home-link">
        <p>
          <a class="metabox__blog-home-link" href="#"><i class="fa fa-home" aria-hidden="true"></i> Back to About Us</a> <span class="metabox__main">Our History</span>
        </p>
      </div>

      <div class="page-links">
        <h2 class="page-links__title"><a href="#">About Us</a></h2>
        <ul class="min-list">
          <li class="current_page_item"><a href="#">Our History</a></li>
          <li><a href="#">Our Goals</a></li>
        </ul>
      </div>

      <div class="generic-content">
       <?php the_content(); ?>
      </div>
    </div>
    <?php }
    get_footer();
?>
  1. 为了先不让侧边栏显示,把那部分<page-links>注释掉,注释方法是在开头写<!--,在结尾写-->,被注释的部分如下:
      <!--
      <div class="page-links">
        <h2 class="page-links__title"><a href="#">About Us</a></h2>
        <ul class="min-list">
          <li class="current_page_item"><a href="#">Our History</a></li>
          <li><a href="#">Our Goals</a></li>
        </ul>
      </div>
      -->
  1. 稍微再调整一下,比如加载好图片、为之后需要进行的修改用占位文字进行提示等,修改结果如下:
<?php 
    get_header();
    while(have_posts()){
        the_post();?>
        <div class="page-banner">
      <div class="page-banner__bg-image" style="background-image: url(<?php echo get_theme_file_uri('images/ocean.jpg')?>;)"></div>
      <div class="page-banner__content container container--narrow">
        <h1 class="page-banner__title"><?php the_title(); ?></h1>
        <div class="page-banner__intro">
          <p>relace this with newly created field</p>
        </div>
      </div>
    </div>

    <div class="container container--narrow page-section">
      <div class="metabox metabox--position-up metabox--with-home-link">
        <p>
          <a class="metabox__blog-home-link" href="#"><i class="fa fa-home" aria-hidden="true"></i> Back to About Us</a> <span class="metabox__main">Our History</span>
        </p>
      </div>

      <!--
      <div class="page-links">
        <h2 class="page-links__title"><a href="#">About Us</a></h2>
        <ul class="min-list">
          <li class="current_page_item"><a href="#">Our History</a></li>
          <li><a href="#">Our Goals</a></li>
        </ul>
      </div>
      -->

      <div class="generic-content">
       <?php the_content(); ?>
      </div>
    </div>
    <?php }
    get_footer();
?>
  1. 更换网页标签的标题,可以在header.php的<head>部分添加<title>标题</title>,但在wordpress中更好的办法就是利用已经有的wp_head()函数,在functions.php中完成标题的自动匹配,添加代码如下:
function university_features(){
    add_theme_support('title-tag');//当想给主题添加特性时用add_theme_support函数
}

add_action('after_setup_theme','university_features' );
  1. 让网页中的按钮建立链接,之后会讲如何实现让wordpress的编辑器可以编辑到,现在直接在header.php和footer.php的 代码中手动添加,可以直接在<a href=''>中写'/about-us',但更好的办法是使用php函数‘echo site_url(‘about-us’)’,把privacy-policy或者about-us填进去就行,或者把括号空下来,就会指向网站主页,更改部分的语句如下:
header.php:
          <a href="<?php echo site_url() ?>"><strong>Fictional</strong> University</a>
          <li><a href="<?php echo site_url('/about-us')?>">about Us</a></li>
footer.php:
    <a href="<?php echo site_url()?>"><strong>Fictional</strong> University</a>
    <li><a href="<?php echo site_url('/about-us')?>">About Us</a></li>
    <li><a href="<?php echo site_url('/privacy-policy')?>">Privacy</a></li>

父子页面

  1. 先新建两个页面Our History和Our Goals备用,建立时在Page选单下的page attributes里选择parent page为about us
  2. 在网页的面包屑(类似目录的二级导航菜单)部分,可以看到子页面的内容是硬编码的,应该改成动态显示当前页的标题,在page.php中找到<div class='metabox'>的部分,把其中的固定内容our history改为`;
  3. 让面包屑只在子页面出现,可以使用if语句让面包屑只在没有父页面的页面出现,因为wordpress的每个页面都会有个postid,可以使用postid来实现这种判断,使用get_the_ID()来获取当前页面id,再把它放到wp_get_post_parent_id()里来获得当前页面的父页面ID,如果不存在就是0,而php中的if语句里写数字是0就是false,大于0就是true,所以可以修改代码如下:
<?php 
    if(wp_get_post_parent_id(get_the_id())){ ?>
        <div class="container container--narrow page-section">
      <div class="metabox metabox--position-up metabox--with-home-link">
        <p>
          <a class="metabox__blog-home-link" href="#"><i class="fa fa-home" aria-hidden="true"></i> Back to About Us</a> <span class="metabox__main"><?php the_title(); ?></span>
        </p>
      </div>
    <?php }
?>
  1. 让面包屑区域的about us部分也变成动态的,实现显示父页面,可以新建一个privacy policy的子页面cookie policy来测试,可以使用get_the_title()来通过输入页面的postid来获取标题名(与the_title()直接获取当前页面标题名不同),还有通过get_permalinnk()也是通过输入页面的postid来获取相应页面的链接,这些id都可以使用上一步里的wp_get_post_parent_id(get_post_id())来得到父页面的信息,为省事可以新建一个变量$theParent=wp_get_post_parent_id(get_post_id());把变量$theParent填进去使用,相应部分的代码如下:
    <?php 
        $theParent=wp_get_post_parent_id(get_the_id());
        if($theParent){ ?>
            <div class="container container--narrow page-section">
          <div class="metabox metabox--position-up metabox--with-home-link">
            <p>
              <a class="metabox__blog-home-link" href="<?php echo get_permalink($theParent); ?>"><i class="fa fa-home" aria-hidden="true"></i> Back to <?php echo get_the_title($theParent); ?></a> <span class="metabox__main"><?php the_title(); ?></span>
            </p>
          </div>
        <?php }
    ?>

创建子界面链接

  1. 首先恢复原先被注释掉的侧边栏部分,然后删掉其中静态的<ul class="min-list">内部的部分
  2. 在php模式下添加一个函数wp_list_pages(),在什么都不输入的情况下它会显示整个网站的页面目录结构,所以要通过参数控制,它的参数需要用到[[php语言注意事项#关联数组(associate array)|关联数组]],具体设置和解释如下:
    <?php
        if($theParent){
            $findChildrenOf=$theParent; //如果有父页面,让新变量id等于父页面id
        } else {
            $findChildrenOf=get_the_ID();//如果没有父页面(说明本身就是父页面),直接使用当前页的id
        }

        wp_list_pages(array(
        'title_li' =>NULL, //指不要显示列表的标题
        'child_of' =>$findChildrenOf

        ))

    ?>
  1. 把侧边栏的标题部分也动态化,让其指向父页面的地址,更改代码如下:
        <h2 class="page-links__title"><a href="<?php echo get_permalink($theParent); ?>"><?php echo get_the_title($theParent); ?></a></h2>
  1. 为一些既没有父页面也没有子页面的页面去掉侧边栏,加一个if判断当一个页面如果有父页面或者如果有子页面时才显示侧边栏,代码如下:
<?php 
$testArray=get_pages(array(
'child_of'=>get_the_ID()
));
if($theParent or $testArray){ ?>
//原本div class="page-links"的内容
<?php } ?>
?>
  1. 侧边栏中子页面的顺序默认按照字母顺序排列,可在wp_list_pages()的参数数组中添加'sort_column' => 'menu_order',之后就可以通过在wordpress的页面选项中编辑页面的page order中调整顺序,数字越小在越前面

让网站变成响应式的(根据设备变换尺寸)

  1. 可以在Chrome中右键检查,在窗口左上角第二个按钮更改视图为各种设备,很方便
  2. 在header.php的<head>部分添加一句代码,实现让网页跟随设备调整大小:
    <meta name="viewport" content="width=device-width,initial-scale=1">

3.实际调整方式由其他css代码和框架实现,这里只是相当于启用

让浏览器知道网站的自然语言

  1. 在header.php的第一个<html>中间添加内容,更改为:
<heml <?php language_attributes() ?>>
  1. 这样搜索引擎就会知道这个网站用的是什么语言了

让浏览器知道网站的字体

  1. 在header.php的第一个<html>部分添加内容:
<meta charset="<?php bloginfo('charset'); ``?>">

让网站获得当前页面的各种信息

  1. 在header.php的<body>中间添加内容,更改为以下内容,wordpress会增加一个class获取当前页面的各种信息,方便css和javascript调用:
<body <?php body_class(); ?>>

设置可在wordpress仪表盘控制的动态导航菜单

  1. 可以在header.php中的<body>下的<nav class>中逐个修改,这样也是种好的选择
  2. 也可以通过设置让wordpress的仪表盘中可以编辑
  3. 在functions.php的function university_features()里添加一行代码
register_nav_menu('headerMenuLocation', 'Header Menu Location');
  1. 现在wordpress的仪表盘中点击外观就可以看到菜单menu选项了,其中可以新设立菜单,菜单的名字不重要,在设置时的menu settings下就可以看到刚才写下的Header Menu Location了
  2. 设置好后需要让菜单显示出来,在header.php中的<nav class>下替换掉原来部分,改为以下内容即可成功:
            <?php 
            wp_nav_menu(array(
                'theme_location'=>'headerMenuLocation'
            ));
            ?>
  1. 如果要把导航菜单放到页脚,可以注册一个新的菜单位置,在functions.php的function university_features()里添加一行代码
register_nav_menu('footerLocationOne', 'footer Location One');
register_nav_menu('footerLocationTwo', 'footer Location Two');

7.在footer.php中找到<nav class>,替换掉原来部分,改为以下内容(本教程最后还是用静态的,所以把原来的注释掉就行):

            <?php 
            wp_nav_menu(array(
                'theme_location'=>'footerLocationOne'
            ));
            ?>

8.在另一处<nav class>如法炮制:

            <?php 
            wp_nav_menu(array(
                'theme_location'=>'footerLocationTwo'
            ));
            ?>
  1. 在仪表盘新建两个菜单到特定位置即可
  2. 上面这些只是教学演示用,实际要把这些东西都删掉换成原本静态的,动态的好处是可以生成很多信息,可供css进行更多自定义,比如现在当前页面的选项就会有不同的显示
  3. 添加当前页的菜单选项显示不同的功能,在<nav class="main-navigation">下把原本的关于about的list改为以下代码,其中is_page()表示判断当前页是否为参数slug的页面,slug就是网址中.com/背后的东西,wp_get_post_parent_id()中填写0就表示当前页,后面的ID号可以在wordpress的页面中点开确认:
 <li <?php if(is_page('about-us') or wp_get_post_parent_id(0)==14) echo 'class="current-menu-item"' ?>><a href="<?php echo site_url('/about-us')?>">about Us</a></li>

建设博客部分

  1. 原本wordpress默认情况下的主页会是一个博客的列表展示,但在此项目使用的素材fictional university中首页已经是别的内容,这里要实现在网址背后加/blog进入博客列表展示的功能
  2. 添加两个页面,第一个叫Home,第二个叫Blog,内容都是空的
  3. 在wordpress的仪表盘中选择设置-reading,把主页显示选为静态页面,把homepage选为home,posts page选为blog,可以看到主页现在变成了空的,而blog页变成了之前主页的样子,之后来进行修正
  4. 在主题文件夹下新建一个文件front-page.php文件,把index.php里的语句全部复制给它,现在主页home的内容就会变得像之前的主页一样了
  5. 现在可以把index.php用来显示posts page的博客页面
  6. 建立分页,wordpress默认会显示10篇最近的博文,当有更多博文时需要翻页的链接,在wordpress的仪表盘可以在设置-reading中调节每页显示的博文数量,添加链接只需在index.php的页脚前最后的<div>前的php模式中加上一句函数echo paginate_links();
  7. 开始建立博客单页的样式,修改single.php,single.php和page.php非常相似,single用于单个博客,page用于单个页面,所以single可以从page借一些代码来用,通过引入while循环、page-banner、面包屑等元素完成搭建,single.php完成后的代码如下:
<?php 
    get_header();
    while(have_posts()){
        the_post();?>
    <div class="page-banner">
      <div class="page-banner__bg-image" style="background-image: url(<?php echo get_theme_file_uri('images/ocean.jpg')?>;)"></div>
      <div class="page-banner__content container container--narrow">
        <h1 class="page-banner__title"><?php the_title(); ?></h1>
        <div class="page-banner__intro">
          <p>relace this with newly created field</p>
        </div>
      </div>
    </div>

        <div class="container container--narrow page-section">
         <div class="metabox metabox--position-up metabox--with-home-link">
            <p>
              <a class="metabox__blog-home-link" href="<?php echo site_url('/blog'); ?>"><i class="fa fa-home" aria-hidden="true"></i> Blog Home </a> <span class="metabox__main">Posted by <?php the_author_posts_link(); ?> on <?php the_time('n.j.y'); ?> in <?php echo get_the_category_list(' , '); ?></span>
            </p>
          </div>

            <div class="generic-content"><?php the_content(); ?></div>
        </div>
    <?php }
    get_footer();

?>

博客档案

  1. 当用户点进文章的作者或分类时,会看到一个通用的欢迎语,这是因为这些界面现在还是由index.php控制,而index.php应该是其他文件都不顶用时候才派上用场的底线,所以应该新建一个文件来进行管理,在主题文件夹中新建archive.php
  2. 在page-banner_title下使用if语句判断,如果是分类就显示分类名,如果是作者就显示作者名,代码如下:
        <h1 class="page-banner__title">
        <?php 
        if(is_category()){
        single_cat_title();
        }
        if(is_author()){
        echo 'Posts by '; the_author();
        } ?>
        </h1>
  1. 同样的,也可以实现按照日期年月日来划分,不过很麻烦,这里可以使用wordpress的一个函数the_archive_title();代替之前的内容,也可以在这个函数的基础上使用上面的方式进行更细节的调整:
        <h1 class="page-banner__title"><?php the_archive_title(); ?> </h1>
  1. 引入介绍内容,在<page-banner_intro><p>中添加php模式函数the_archive_description();它在author界面会调用作者在wordpress设置的biography,在category界面会调用category的description,如果都没有就是空白,代码如下:
        <div class="page-banner__intro">
          <p><?php the_archive_description(); ?></p>
        </div>

自定义查询(custom query)

  1. 如果现在直接在front-page.php的<div class="full-width-spilt_two">中添加引入博客的while循环,可以发现只会出现在设置-reading中被设为homepage的home作为标题出现,代码如下:
 <h2 class="headline headline--small-plus t-center">From Our Blogs</h2>
          <?php 

            while(have_posts()){
                the_post();?>
                <li><?php the_title(); ?></li>
            <?php }

          ?>
  1. 现在开始建立自定义查询,建立查询时首先要建立一个新变量,建立一个WP_Query这个类的实例homepagePosts,之后再用这个新变量来调用have_posts()和the_post()函数,语句为$homepagePosts=new WP_Query(),其中要用[[php语言注意事项#关联数组(associate array)|关联数组]]提供信息,比如posts_per_page可以控制每页的博客数,category_name可以控制只显示某个类别的博客,post_type可以控制显示博客post还是页面page,这里只需要控制数量即可,代码如下:
          <?php 
            $homepagePosts =  new WP_Query(array(
                'posts_per_page'=>2
            ));

            while($homepagePosts->have_posts()){
                $homepagePosts->the_post();?>
                <li><?php the_title(); ?></li>
            <?php }

          ?>
  1. 把envent-summary的内容复制一个贴到while循环中,并对其标题、内容等形式进行调整,其中wp_trim_words()函数的第一个参数表示要显示的内容,第二个参数表示对内容的限制,这里写18代表只显示前18个单词,代码如下:
    while($homepagePosts->have_posts()){
        $homepagePosts->the_post();?>
     <div class="event-summary">
    <a class="event-summary__date event-summary__date--beige t-center" href="<?php the_permalink(); ?>">
      <span class="event-summary__month"><?php the_time('M');?></span>
      <span class="event-summary__day"><?php the_time('d');?></span>
    </a>
    <div class="event-summary__content">
      <h5 class="event-summary__title headline headline--tiny"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5>
      <p><?php echo wp_trim_words(get_the_content(),18)?> <a href="<?php the_permalink(); ?>" class="nu gray">Read more</a></p>
    </div>
  </div>
    <?php } wp_reset_postdata();

  ?>

小修小补

  1. 给上文中博客列表下的更多文章按钮添加有意义的链接,如下:
<p class="t-center no-margin"><a href="<?php echo site_url('/blog'); ?>" class="btn btn--yellow">View All Blog Posts</a></p>
  1. 让每页头部导航菜单中的blog都导向博客页,在header.php中修改代码,让它在属于博客相关页面时都能够以不同格式显示,如下:
<li <?php if(get_post_type()=='post') echo 'class="current-menu-item"'?>><a href="<?php echo site_url('/blog'); ?>">Blog</a></li>

自定义博客类型

  1. page也只是一种类型的post,我们可以建立自己想要的post类型
  2. 进入functions.php文件,建立新的函数,并通过add_action以init为起点调用,代码如下:
<?php 

function university_post_types(){
    register_post_type('event',array(
    'public'=>true, //让这种类型对网站的编辑者和查看者都可见
    'labels'=>array( //更改这一类型的标签
    'name'=>'Events' //名字标签可以改变该类型显示出来的名字
    ) ,
    'menu_icon'=>'dashicons-calendar' //更改显示在仪表盘的图标
    ));
    }

add_action('init','university_post_types');

?>

3.最好别放在functions.php,不然一换主题就用不了了,可以使用wordpress的必用插件(mustuse plugin)方式,在wordpress的wp-content文件夹中新建一个文件夹mu-plugins,在这个文件夹中的php文件都会被wordpress自动调用,在mu-plugins里新建文件university_post_types.php,把上一步的代码剪切进来。

  1. 在仪表盘新建event时,可以看到提示语还是add new post,要更改它需要添加一行参数’add_new_item’=>’Add New Event’,’edit_item’=>’Edit Event’,’all_items’=>’All Events’,’singular_name’=>’Event’,有很多参数可以自定义,这些是比较常用的,最终代码如下:
<?php 

function university_post_types(){
    register_post_type('event',array(
    'public'=>true, //让这种类型对网站的编辑者和查看者都可见
    'labels'=>array( //更改这一类型的标签
    'name'=>'Events', //名字标签可以改变该类型显示出来的名字
    'add_new_item'=>'Add New Event',
    'edit_item'=>'Edit Event',
    'all_items'=>'All Events',
    'singular_name'=>'Event'
    ) ,
    'menu_icon'=>'dashicons-calendar' //更改显示在仪表盘的图标
    ));
    }

add_action('init','university_post_types');

?>

显示自定义博客

目标:实现在网页首页显示两个Event预览

  1. 在front-page.php的写有Upcoming Events的<h2 class>下建立自定义查询和一个循环,实现在首页显示event的标题,代码如下:
<?php 
    $homepageEvents=new WP_Query(array(
        'posts_per_page'=>2,
        'post_type'=>'event'
    ));

    while($homepageEvents->have_posts()){
        $homepageEvents->the_post(); ?>
        <li><?php the_title(); ?></li>
    <?php }

?>
  1. 把案例中的美美html剪切过来替换掉上文中<li></li>的部分,再把里面静态的一些部分替换成php语句,实现标题的显示和跳转,阅读更多的跳转等等,代码如下:
<h2 class="headline headline--small-plus t-center">Upcoming Events</h2>

          <?php 

            $homepageEvents=new WP_Query(array(
                'posts_per_page'=>2,
                'post_type'=>'event'
            ));

            while($homepageEvents->have_posts()){
                $homepageEvents->the_post(); ?>
            <div class="event-summary">
            <a class="event-summary__date t-center" href="#">
              <span class="event-summary__month">Mar</span>
              <span class="event-summary__day">25</span>
            </a>
            <div class="event-summary__content">
              <h5 class="event-summary__title headline headline--tiny"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5>
              <p><?php echo wp_trim_words(get_the_content(),18); ?> <a href="#" class="nu gray">Learn more</a></p>
            </div>
          </div>
            <?php }

          ?>
  1. 完成后点开链接却只能看到欢迎页,这是因为需要在wordpress的设置-permalink中选择一下save settings,把event作为permalink来存进wordpress中,这样就可以点进去了。
  2. 在上一步之后点进去发现页面还是按照post的格式,由single.php控制,最好用单独的新文件来控制新的post格式,在主题文件夹新建一个single-event.php文件,wordpress会自动识别single-??.php形式的文件作为专门的post格式文件,可以先把single.php的内容复制过来再进行自定义
  3. 自定义面包屑里的内容,让右边的黄色部分显示当前event标题,左边的蓝色部分能够进入event主页,如果直接在地址栏里进入/event,会发现还是出现page not found,是因为wordpress还不知道该post类型支持archive,需要在university-post-types.php中添加参数’has_archive’=>true即可正常显示
  4. 为了让网页的slug更有意义,比如让/event显示为/events,可以在university-post-types.php中添加参数'rewrite'=>array('slug'=>'events'),实现自定义slug名,这时university-post-types.php的代码如下:
<?php 

function university_post_types(){
    register_post_type('event',array(
    'rewrite'=>array('slug'=>'events'),//更改slug名
    'has_archive'=> true, //让这一类型支持存档,wordpress就可以进行汇总显示
    'public'=>true, //让这种类型对网站的编辑者和查看者都可见
    'labels'=>array( //更改这一类型的标签
    'name'=>'Events', //名字标签可以改变该类型显示出来的名字
    'add_new_item'=>'Add New Event',
    'edit_item'=>'Edit Event',
    'all_items'=>'All Events',
    'singular_name'=>'Event'
    ) ,
    'menu_icon'=>'dashicons-calendar' //更改显示在仪表盘的图标
    ));
    }

add_action('init','university_post_types');

?>
  1. 发现events的汇总格式和posts一样,因为这使用的是archive.php,如果要使用专门的汇总存档文件,可以在主题文件夹新建文件archive-event.php,这里-号后面的名字也必须和自定义的post类型一致,先把archive.php的内容拿来备用修改
  2. 把主页front-page.php关于event的html内容拿来替换掉archive-event.php的相关内容,把面包屑部分的返回主页链接改为<?php echo get_post_type_archive_link(); ?>,来实现不管slug怎么变化,都能跳转到这一post类型的archive页面

在预览页面显示自定义的摘要

目的:在首页的博文节选预览中显示出自定义的摘要,而不是之前设定的前十几个字

  1. 在wordpress的仪表盘中写新的post,在document选项中有excerpt一栏,可以自定义摘要
  2. 在front-page.php中可以找到显示摘要的部分,把原来的trim语句改成the_excerpt();即可,这样有自定义摘要的就会显示摘要,没有的默认就会显示前50个词,虽然可以改变这一默认设定,但它会产生全局影响,不如单独进行调节,比如将the_excerpt和之前的trim结合起来,直接the_excerpt()自动输出会有些奇怪的分割,用echo输出get_the_excerpt()会恢复正常,代码如下:
  <div class="event-summary__content">
              <h5 class="event-summary__title headline headline--tiny"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5>
              <p><?php if(heve_excerpt()){
                           echo get_the_excerpt();
                       } else{
                           echo wp_trim_words(get_the_content(),18);  
                       }?> <a href="<?php the_permalink(); ?>" class="nu gray">Read more</a></p>
            </div>
          </div>
  1. 发现自己定义的post类型event中没有excerpt选项,需要手动添加,在mu-plugins文件夹的university-post-types.php中,添加参数'support'=>array('title','editor','excerpt'),参数的数组中title和editor都是默认就有的,其他的要自己添加,这样在event的编辑器页面应该就能看到excerpt了,如果看不到是因为自定义页面使用的是wordpress的老版编辑器,在右上角的screen options就可以调节excerpt栏的显示
  2. 如果要让自定义页面也显示wordpress新的区块编辑器,需要在university_post_types.php中添加一行参数'show_in_rest'=>true,因为wordpress的新编辑器几乎完全依赖于JavaScript,所以通过让自定义post类型可以在rest API使用才可以使用新编辑器,现在只需知道rest API让raw wordpress数据可以被JavaScript获取,另外如果在写了rest的情况下写了support而在supports中没有明确列出editor,同样会导致变回老编辑器,如果不写supports的话反而会是新编辑器
  3. 为阅读更多和header的event添加正确链接还有在对应页面时变成黄色的功能

自定义字段

目的:添加自定义字段

  1. 可以在mu-plugins.php的supports中添加’custom-fields’,保存后在event编辑器的右上角设置中找到custom fields,点击enable&reload后就可以在编辑器的下方添加
  2. 自己添加的效率很低,不如使用[[wordpress插件#自定义字段|关于自定义字段的插件]],在安装插件前不用添加’custom-fields’,如果写了就删掉,插件会自己搞定的
  3. 在wordpress插件市场安装Advanced Custom Fields并激活,在侧边栏中打开custom fields
  4. 添加field group,命名为Event Date,在其中点add field,field type可以选date picker,field label是给人读的名字,就写Event Date,field Name是给计算机读的,就写event_date,各种内容都可以自由写,但return format最好选择Ymd格式,这样能够与之后要写的php形成很好的配合,最后在settings部分选好post type is equal to event就可以保存了
  5. 让自定义字段内容显示在网站上,要进入front-page.php,找到<span class="event-summary_month">,在内容中写<?php the_field('event_date')?>,这样就会得到一个完整的日期
  6. 要把日期转换成合适的格式,比如把月份换为JUN之类的缩写,需要一些php语句,比如$eventDate=new DateTime();从datetime类建立了新的实例,datetime是php的内容,与wordpress无关,之后可通过echo $eventDate->format('M')来输出月份,在datetime中如果没有参数输入,就会默认为浏览者当前时间,在括号中填入参数get_field('event_date'),最终代码如下:
 <span class="event-summary__month"><?php 
                $eventDate = new DateTime(get_field('event_date'));
                echo $eventDate->format('M')
                                                 ?></span>
              <span class="event-summary__day"><?php echo $eventDate->format('d')?></span>

根据自定义字段值决定自定义查询的顺序

目标:实现按照自定义的event日期来对event post的显示进行排序

  1. 在front-page.php中找到第一个wp_query,添加参数'orderby',默认的参数是'post_date',发布的日期,可以改为'title',按照字母顺序排序,为了看看效果,可以把上面post_per_page的参数改为-1,这种情况下wordpress会把所有符合条件的内容都显示出来,可以看到event是按照字母倒序排列的,正序倒序的排列可以通过参数'order'的值设置为'DESC'倒序或者'ASC'正序排列,如果想要随机排序,可以把'orderby'的值设置为'rand'
  2. 想实现用自定义字段值排序,需要将'orderby'的值设置为'meta_value',meta在wordpress中表示与post相关的各种额外数据,当使用meta_value时,还需要在上方添加另一行参数'meta_key'=>'event_date',meta_value在这里让wordpress读取meta_key的值,而meta_value一般更适合表示文本,要表示文本,可以把meta_value改为meta_value_num,这样就可以实现按照自定义日期排序了
  3. 让已经超过期限的日期不再显示,需要使用再添加一个参数'meta_query'=>array(),在这个array内部通过添加新的array来限制条件,每个内部的array限制一个条件,这里只需要限制只显示超过今天的日期,在新的array中通过设置'key'=>'event_date','compare'=>'>=','value'=>date('Ymd')来实现只显示大于今天的日期,可以在WP_Query之前新建一个变量$today=date('Ymd')来在array中使用,方便理解,现在这样已经可以实现功能了,但还可以在array中加一句'type'=>'numeric'告诉wordpress比较的数据类型是数字,这一部分的代码如下:
    $today=date('Ymd');
    $homepageEvents=new WP_Query(array(
        'posts_per_page'=>2,
        'post_type'=>'event',
        'meta_key'=>'event_date',
        'orderby'=>'meta_value_num',
        'order'=>'ASC',
        'meta_query'=>array(
            array(
                'key'=>'event_date',
                'compare'=>'>=',
                'value'=>$today,
                'type'=>'numeric'
            )
        )
    ));

编辑默认的或已有的查询

目的:点击首页的全部事件按钮后,让全部事件中不显示过期事件,同时让显示的日期时间都正常

  1. 让存档页面静态的日期变成动态的日期,把front-page.php中的内容替换到archive-event.php的对应内容即可
  2. 让event按照设定时间排序,并且不显示过期event,这里不一定需要建立自定义查询,那样太复杂,只需要改一改原本的默认查询就行,这样可以避免写更多的代码,也让分页变得不那么麻烦
  3. 更改默认查询不需要对archive-event.php进行修改,在functions.php中添加代码add_action('pre_get_posts','university_adjust_queries'),表示在加载post的query前执行函数
  4. 定义函数university_adjust_queries,这里试验一下,输入参数$query,内部方法为$query->set('posts_per_page','1');即可实现让页面只显示一条博文,但这样写会影响到整个wordpress的各种内容,甚至在仪表盘界面也只显示一条
  5. 添加if语句让这种调整只对event起效,在if中限定条件!is_admin把范围限制在仪表盘外,保存后可以看到仪表盘已经正常,而blog存档页面还受到限制,在if条件中添加AND is post_type_archive('event')(AND的大小写无所谓),就可以实现只在event的存档页面限制每页的博文数
  6. 安全起见,在if的条件后再加一条and $query->is_main_query(),这样就只会调整默认查询,不会修改自定义查询
  7. 现在条件设置已经完备,可以删掉之前试验的内容,把限制条件写为让博文按照事件时间排序,并隐藏过期事件,可以参考front-page.php中WP_Query的代码,编写限制代码后如下:
function university_adjust_queries($query){
    if(!is_admin() and is_post_type_archive('event')){
        $today=date('Ymd');
        $query->set('meta_key','event_date'); //获取事件日期
        $query->set('orderby','meta_value_num'); //用获取到的数字排序
        $query->set('order','ASC'); //升序排列
        $query->set('meta_quary',array(
            array(
                'key'=>'event_date',
                'compare'=>'>=',
                'value'=>$today, //要使用这个变量,要在函数内建立该变量的定义
                'type'=>'numeric'
            )
        ));
    }
}

建立一个新的只显示过期事件的页面

目的:如题

  1. 在wordpress仪表盘中建立一个新page命名为Past Events
  2. 要新建一个专门的模板文件,在主题文件夹下新建文件page-past-events.php,文件的名称必须为page-页面的slug名
  3. 可以把archive.php中的内容复制过来作为模板使用
  4. 在原列表循环的上方新建自定义查询$pastEvents,代码如下:
    $pastEvents = new WP_Query(array(
        'post_type'=>'event'    
    ));
  1. 并且把下文中的各种查询函数归属到自定义查询下,在函数前加上$pastEvents->,这样保存后就能看到新页面显示了全部event
  2. 要只显示过期event需要参数,可以从front-page.php复制过来再进行修改,除了一开始的变量名外把’meta_query’中的’compare’值改为'<‘即可
  3. 接下来的难点是实现分页,为了方便观察效果可以在自定义查询中加一条'posts_per_page'=>1,保存后只显示一条,却不显示分页,因为wordpress的分页只在默认的查询中自动出现,之前events存档可以分页是因为用的还是默认查询,这里复杂一些
  4. 在page-past-events.php中的paginate_links()中添加参数array(),添加自定义查询的信息,代码如下:
    echo paginate_links(array(
        'total'=>$pastEvents->max_num_pages, //告诉wordpress会有多少个分页

        ));
  1. 然而虽然出现了分页,但分页的结果不会变化,这是因为在自定义查询中没有添加参数使其获取分页的结果来显示帖子,添加参数’paged’,并在其后使用函数get_query_var()获取自定义查询的信息,该函数中的参数一'page'表示获取url中最后的分页数字,参数二1表示在没有分页数字的情况下默认显示第一页的内容,代码如下:
$today=date('Ymd');
    $pastEvents=new WP_Query(array(
        'paged'=> get_query_var('paged',1),
        'post_type'=>'event',
        'meta_key'=>'event_date',
        'orderby'=>'meta_value_num',
        'order'=>'ASC',
        'meta_query'=>array(
            array(
                'key'=>'event_date',
                'compare'=>'<',
                'value'=>$today,
                'type'=>'numeric'
            )
        )
    ));
  1. 在events页面底部创建一个导向past-events页面的链接,并在上方加一条分割线,代码如下:
 <hr class="section-break">

    <p>want to see our past events? <a href="<?php echo site_url('/past-events')?>">Click here</a></p>
  1. 改变header.php中的判断条件,让顶部的event文字在past-event页面也变成黄色,代码如下:
if(get_post_type()=='event' or is_page('past-events')) echo 'class="current-menu-item"'?>><a href="<?php echo get_post_type_archive_link('event');?>">Events</a></li>

创建不同类型posts之间的关系

目的:创建不同类型的post,并在其中建立关联

创建新post类型’Program’

  1. 直接在mu-plugins文件夹中的university-post-types.php中复制新建event时的函数,修改其中的对应参数即可,代码如下:
register_post_type('program',array(
    'show_in_rest'=>true,
    'supports'=>array('title','editor'),
    'rewrite'=>array('slug'=>'programss'),//更改slug名
    'has_archive'=> true, //让这一类型支持存档,wordpress就可以进行汇总显示
    'public'=>true, //让这种类型对网站的编辑者和查看者都可见
    'labels'=>array( //更改这一类型的标签
    'name'=>'Programs', //名字标签可以改变该类型显示出来的名字
    'add_new_item'=>'Add New Progran',
    'edit_item'=>'Edit Program',
    'all_items'=>'All Programss',
    'singular_name'=>'Program'
    ) ,
    'menu_icon'=>'dashicons-awards' //更改显示在仪表盘的图标
    ));
  1. 不要忘记要在仪表盘的设置中把permalink点一下save changes,才能正常显示
  2. 这里支持单个program页面内容的还是single.php,需要在主题文件夹中新建一个single-program.php,把single-event.php里的内容贴过来使用,把metabox里的event home改成all programs
  3. 新建一个archive-programs.php文件管理program的存档页面,把archive-event.php里的内容复制过来
  4. 删去post循环中的内容,只展示单个program的标题,代码如下:
    <?php
    while(have_posts()){
        the_post(); ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php }
  1. 在循环体的上下添加<ul>标签,让它成为无序表,再在<ul>中添加class,利用css让它变得美观点,代码如下:
<ul class="link-list min-list">
  1. 删除关于分页的内容,并将university的post-per-page修改为-1,这样就不会分页,直接展示全部的program了
  2. 如果不需要自定义查询,可以在functions.php直接编辑默认查询,将program改为按字母顺序升序排列,代码如下:
    if(!is_admin() and is_post_type_archive('program') and is_main_query()){
        $query->set('orderby','title');
        $query->set('order','ASC');
        $query->set('posts_per_page',-1);

    }

让program中的项目和event建立联系

目的:让某个event的内容中可以有相关学科的字段,能够让用户点进去看到学科内容

  1. 创建自定义字段,将field type设为relationship,field label设为Related Program(s),field name设为related_programs,在filter by post type中选择program,在filters中只选择Search,Return Format中选择Post Object,在location ruls中把规则设定为post type is equal to event
  2. 之后在event中选择该自定义字段值即可
  3. 要在网页中显示这一关联,可以在single-event.php中添加内容显示
  4. 建立变量$relatedProgram=get_field('related_programs'),如果想知道变量里面有什么东西,可以使用print_r($relatedPrograms)输出所有此变量中的信息看看
  5. 为了方便理解,在一个event中添加两个related Programs,
  6. 在single-event.php中添加关于relatedprograms的内容,让其能够显示出来,代码如下:
    <?php 

    $relatedPrograms =get_field('related_programs');


    foreach($relatedPrograms as $program){ ?>
        <li><a herf="<?php echo get_the_permalink($program); ?>"><?php echo get_the_title($program); ?></a></li>
    <?php }

    ?>
  1. 加一些css内容美化一下,添加后代码如下:
    <?php 

    $relatedPrograms =get_field('related_programs');

    echo '<ul class="link-list min-list">';
    foreach($relatedPrograms as $program){ ?>
        <li><a href="<?php echo get_the_permalink($program); ?>"><?php echo get_the_title($program); ?></a></li>
    <?php }
    echo '</ul>';
    ?>
  1. 添加if判断,让event在没有关联program得时候不显示上文的内容,代码如下:
    $relatedPrograms =get_field('related_programs');

    if($relatedPrograms){
        echo'<hr class="section-break">';
    echo'<h2 class="headline headline--medium">Related Program(s)</h2>';
    echo '<ul class="link-list min-list">';
    foreach($relatedPrograms as $program){ ?>
    <li>
        <a href="<?php echo get_the_permalink($program); ?>">
            <?php echo get_the_title($program); ?>
        </a>
    </li>
    <?php }
    echo '</ul>';
    ?>
    }

在program单个页面中添加与之相关联的events部分

目标:实现在program的单个页面中显示与之相关的events

  1. 把front-page.php中展示events列表部分的代码粘贴到single-program.php的尾部
  2. $homepageEvents这个自定义查询的meta_query中添加一个过滤器array,其中由于wordpress会把在key中得到的数组序列化,会产生多余的数字,而把网页id加上双引号,所以在通过value搜索时要在前后加上双引号,通过.来分隔,内容如下:
            array(
            'key'=>'related_programs',
            'compare'=>'LIKE',
             'value'=>'"'.get_the_ID().'"'
            )
  1. 小提示:如果怎么都不显示,看看是不是events的日期设置过了,现在只显示未来的日期

对single-program的小修小补

目标:改进样式,增加首页导航等

  1. 在header.php的导航页部分增加代码,如下:
<li <?php if(get_post_type()=='program') echo 'class="current-menu-item"'?>><a href="<?php echo get_post_type_archive_link('program')?>">Programs</a></li>
  1. 在front-page.php,添加代码如下:
<a href="<?php echo get_post_type_archive_link('program')?>" class="btn btn--large btn--blue">Find Your Major</a>

创建Professors post类型以及图像关联

  1. 在mu-plugins文件夹的university_post_types.php中添加professor的post type,从program那里复制内容,把其中的program都改为professor,把rewrite和has——archive都删除,换个图标即可
  2. 在wordpress的仪表盘中新建两个professor,把permalink保存一下让professor界面能够正常显示
  3. 在主题文件夹中新建single-professor.php,控制professor的界面,可以直接使用event的内容,删除其中的面包屑,之后就可以开始自定义了
  4. 首先建立教授professor和学科program之间的关系
  5. 可以在自定义字段中找到related program,在location中添加一个or post type is equal to professor
  6. 在教授界面找一个教授添加相关学科,在single-professor.php中把相关的文字Related Program(s)改写为Subject(s) Taught
  7. 在single-program.php中添加相关professor,把upcoming events中的代码复制过来,把其中的变量$homepageEvents改为relatedProfessor即可,还要删掉一些不用的查询和关于事件的div,代码如下:
<?php
    $relatedProfessors = new WP_Query(array(
     'posts_per_page' => -1,
     'post_type' => 'professor',
     'orderby' => 'title',
     'order' => 'ASC',
     'meta_query' => array(
           array(
             'key' => 'related_programs',
             'compare' => 'LIKE',
             'value' => '"' . get_the_ID() . '"'
           )
     )
   ));



    if ($relatedProfessors->have_posts()) {
        echo '<hr class="section-break">';
        echo '<h2 class="headline headline--medium">' . get_the_title() . ' Professors</h2>';

        while($relatedProfessors->have_posts()) {
            $relatedProfessors->the_post(); ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php }
    }
  1. 这时虽然显示了相关教授,但相关事件不显示了,这是因为自定义查询会改变默认的postid等数据,所以当一个页面有多个自定义查询时,最好在每个自定义查询中加一句函数将相关数据重置,代码如下:
    wp_reset_postdata();

为post添加featured image

  1. post默认不支持featured image
  2. 在functions.php的university_features()中,添加语句add_theme_support('post-thumbnails');这能够为默认的post类型启动featured image功能,但自定义的post类型哈需要更多步骤
  3. 在mu-plugins.php的university-posttypes.php中找到Professor部分,在'support'参数中添加thumbnail即可
  4. 要在教授页面显示featured image,要打开single-professor.php,在content前面加上featured image的内容,代码如下:
    <div class="generic-content">
        <?php the_post_thumbnail(); the_content(); ?>
    </div>
  1. 但这样只是直接把图片显示在文本上方,接下来要实现把图和文本分两列放置,图占左边三分之一,文字占右边三分之二,把上面的内容改为如下代码:
    <div class="generic-content">
        <div class="row group">

            <div class="one-third">
                <?php the_post_thumbnail(); ?>
            </div>

            <div class="two-third">
                <?php the_content(); ?>
            </div>

        </div>
    </div>
  1. 接下来改变program页面中显示教授的方式,以卡片的形式让教授出现在学科中,把其中显示相关教授的部分代码修改如下:
       echo '<ul class="professor-cards">';
        while($relatedProfessors->have_posts()) {
            $relatedProfessors->the_post(); ?>
        <li class="professor-card__list-item">
            <a class="professor-card" href="<?php the_permalink(); ?>">
                <img class="professor-card__image" src="<?php the_post_thumbnail_url(); ?>">
                <span class="professor-card__name"><?php the_title();?></span>
             </a>
        </li>
    <?php }
        echo '</ul>';
    }
  1. 控制图像的大小和长宽比,实现在学科中教授图片长比宽大,教授个人页中宽比长大。可以发现在wordpress文件夹的wp-content的uploads中,wordpress有自动将上传的图片生成几份不同的大小,最小的是150×150的方形,可以通过主题程序控制图片的大小生成,在functions.php中的uniersity_features添加代码add_image_size,参数1表示这种尺寸的名字,参数2表示宽度,参数3表示高度,参数4表示是否裁剪,如下:
function university_features(){
    add_theme_support('title-tag');//当想给主题添加特性时用add_theme_support函数
    add_theme_support('post-thumbnails');
    add_image_size('professrLandscape',400,260,true);
    add_image_size('professrPortrait',480,650,true);
}
  1. 上述代码只会影响后来添加的图片,要影响以前的图,安装插件 regenerate thumbnails,安装后在tools侧边栏中找到插件,点击regenerate即可。
  2. 在网页前端使用自定义尺寸的图片,直接在the_post_thumbnail()中添加参数尺寸名即可,代码如下:
在single-professor.php中,  <?php the_post_thumbnail('professrPortrait'); ?>

在single-program.php中,    <img class="professor-card__image" src="<?php the_post_thumbnail_url('professrLandscape'); ?>" />
  1. wordpress裁剪图片时默认是裁剪最中间,要改变裁剪方式,可以把add_image_size函数中第四个参数从true或false改为数组,但图片总会不同,所以这样修改不太好,最好使用插件manual image crop tomasz,启用后就可以在仪表盘页面使用到featured image的帖子内更方便地裁剪图片,如果没有改变,那应该是浏览器缓存问题,按住shift再点刷新就可以硬刷新,看见变化

banner动态图

目标:创建一个新自定义字段,实现可以上传图片

  1. 新建一个field group,建立字段组Page Banner,其中第一个字段为text类型,名称为Page Banner Subtitle,第二个字段为image类型,名称为Page Banner Background Image,在location设定中,为了让这个字段在所有类型的页面中都出现,可以把条件设置为Post Type is equal to Post or Post Type is not equal to Post
  2. 在functions.php中添加Banner使用的图片尺寸,代码如下:
add_image_size('pageBanner',1500,350,true);
  1. 首先在professor页面中显示,在single-professor.php中添加,代码如下:
<div class="page-banner">
    <div class="page-banner__bg-image" style="background-image: url(<?php $pageBannerImage=get_field('page_banner_background_image'); echo $pageBannerImage['sizes']['pageBanner'] ?>;)"></div>
    <div class="page-banner__content container container--narrow">
        <h1 class="page-banner__title">
            <?php the_title(); ?>
        </h1>
        <div class="page-banner__intro">
            <p><?php the_field('page_banner_subtitle')?></p>
        </div>
    </div>
</div>
  1. 要进一步裁剪图片,可以在wordpress中编辑,用插件裁剪即可

把pagebanner做成一个函数,方便直接调用

  1. 把上文内容剪切到functions.php中作为一个函数,代码如下:
 function pageBanner(){
     //php logic will live here
 ?>
    <div class="page-banner">
    <div class="page-banner__bg-image" style="background-image: url(<?php $pageBannerImage=get_field('page_banner_background_image'); echo $pageBannerImage['sizes']['pageBanner'] ?>;)"></div>
    <div class="page-banner__content container container--narrow">
        <h1 class="page-banner__title">
            <?php the_title(); ?>
        </h1>
        <div class="page-banner__intro">
            <p>
                <?php the_field('page_banner_subtitle')?>
            </p>
        </div>
    </div>
</div>
<?php  }
  1. 在原位置使用pageBanner()调用即可
  2. 让函数变得更灵活,让它可以接受参数,同时在未得到参数时也能够正常运作
 <?php

 function pageBanner($args = NULL){ //加上=NULL表示参数不是必需的
 if(!$args['title']){
     $args['title']=get_the_title();
 }
 if(!$args['subtitle']){
     $args['subtitle']=get_field('page_banner_subtitle');
 }
 if(!$args['photo']){
     if(get_field('page_banner_background_image')){
         $args['photo']=px_get_field('page_banner_background_image')['sizes']['pageBanner'];
     }else{
         $args['photo']=get_theme_file_uri('/images/ocean.jpg');
     }
 }
?>
    <div class="page-banner">
    <div class="page-banner__bg-image" style="background-image: url(<?php echo $atgs['photo'];  ?>;)"></div>
    <div class="page-banner__content container container--narrow">
        <h1 class="page-banner__title">
            <?php echo $args['title']; ?>
        </h1>
        <div class="page-banner__intro">
            <p>
                <?php echo $args['subtitle'];?>
            </p>
        </div>
    </div>
</div>
<?php  }

在所有的模板文件中使用banner函数

  1. 删除掉所有archive、single和index文件中的page banner<div>,并在上方的get_header()后添加PageBanner函数,看情况决定参数即可

减少重复代码:get_template_part()

目标:重复利用显示事件列表的代码

  1. 把front-page.php中事件列表的内容剪切到一个新的文件,文件放置在主题文件夹下新建的template-parts文件夹中,文件起名为event.php(这里文件夹和文件的名字都可以随便起,之后调用即可)
  2. 在原位置使用函数get_template_part()来调用,参数1是必须的,需要写文件的名字,在这里就要写'template-parts/event'(这里不写.php文件名。写slug名),参数2是可选的,写入后该函数会调用文件名为参数1-参数2.php的文件,这里参数2可以是直接的文字也可以是动态的php,可以实现一些厉害操作,在这里把参数1和参数2写为'template-parts/content','event'。再把之前的文件名也改名为content-event.php,把参数1写为template-parts/content-event,不写参数2也可以达成同样的效果
    问题:什么时候使用函数,什么时候使用template_part?
    答:如果想让代码具有灵活性,可以传递参数,就使用函数,如果变化不大就用template_part

配置javascript环境

  1. 建议使用wordpress官方的javascript工具包@wordpress/scripts
  2. 首先在nodejs.org安装nodejs
  3. 在控制台输入node --version可以看自己是否已经安装好nodejs
  4. 把之前university-static-master中的package.json复制到自己的主题文件夹里
  5. 在vs中的控制台使用npm install安装依赖项,如果不使用vs需要手动输入要安装地方的文件夹地址
  6. 现在已经安好了wordpress官方的js包,可以看到json文件中的scripts部分,在终端中输入npm run start,这会一直运行,直到输入停止,它会持续监视何时对文件作出了改变,我们需要编辑的javascript内容都在src文件夹中,这个命令会监视文件的改动,并把它重新编译到build文件夹中,build文件夹的内容是给浏览器加载用的,src是编程时读写的。要停止监视,在控制台中使用ctrl+c即可
  7. npm run build命令是进行一次打包,npm run start是一直在后台运行,通常使用start就行了

建立campus post type

目标:实现新增campus post类型,在前端显示地图以及校园位置的图钉等

  1. 在mu-plugins的university_post_types中复制event post类型部分,将其中的event改为campus,创建campus类型
  2. 创建Downtown East和Downtown West两个campus
  3. 添加自定义字段,在campus中增加谷歌地图类型
  4. 现在还不能直接使用,需要添加地图的API
    • 如果要使用谷歌地图,那么需要在console.cloud.google.com登陆
      1. 注册新的项目,可以命名为WordPress Theme Dev
      2. 启动API,添加Maps Javascript APIPlaces APIGeocoding API
      3. 回到项目的API首页,点击凭据(Credentials),添加凭据-API密钥
      4. 修改API密钥的限制,把应用设置改为HTTP引荐来源网址,网站限制中添加自己网站的域名,API限制中选择限制,并选定上述三个API,保存即可
      5. (为了不超过限额付费给google)在项目的API页面中,给各种api都添加配额(quota),设置低一些比如50
      6. 要让api能够工作,需要在google中增加账单信息
  5. 在主题文件夹的functions.php中,添加代码如下:
funnction universityMapKey($api){
    $api['key']='复制来的密钥值';
    return $api;
}

add_filter('acf/fields/google_map/api','universityMapKey');//高级自定义字段插件中的google_map中的api,把它放到自己定义的一个函数中
  1. 现在字段就可以正常运作了