如何在 Wordpress 中创建自己的模板

个人博客:wangxingyin.cn

有时候看起来很简单,但是做起来很麻烦。这个时候就需要这句话:Just do it! 通过这次定制读书名单和归档名单,自己对PHP,json,HTML 和 CSS 有了更深一些的认识。顺便对自己所掌握的Java语言进行了一下简单复习。下面先讲一下怎么在WordPress 主题中创建自己的模板,然后介绍怎么定制自己现在所用的读书名单网页。

如何在 Wordpress 中创建自己的模板

首先在自己所在的主题目录下,拷贝page.php 文件,然后重新命名一下,我这边命名的是 booklist05.php 。接下里就是新建页面,然后在页面属性中选取书单05(booklist05.php中的模板名称),最后发布就可以了。
主题目录的路径:
/data/wwwroot/wordpress/wp-content/themes/cenote
blob.jpg
如何在 Wordpress 中创建自己的模板_第1张图片
这个是booklist05.php 中的部分截图,红框里面的一定要写上,不然识别不出来这是一个模板。剩下的内容就是自己写PHP的内容了
如何在 Wordpress 中创建自己的模板_第2张图片

选择页面属性,如果页面属性中没有自己刚建的模板,试着把booklist05.php 中的 getsitebar() 注释掉。
如何在 Wordpress 中创建自己的模板_第3张图片
模板建好了,就可以动手写自己的书单模板,书单模板我是参考了暮光博客中的这个模板,但是在使用这个模板的时候,发现豆瓣提供的 API 设置了防盗连接,具体影响就是图片加载不出来。为了解决这个问题,我是使用 Java 写了一小段程序,然后把这些图片下载下来,重新传到自己的服务器上,然后图片地址直接从自己的服务器上面下载。

书单模板:


    /*
    Template Name: 书单05
    */
?>

/**
 * The template for displaying all pages
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site may use a
 * different template.
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/
 *
 * @package cenote
 */

get_header(); ?>


$tmp = '{
    "collections": [
        {
            "status": "reading",
            "book": {
                "image": "https://wangxingyin.cn/wp-content/uploads/2019/01/effectivejava.jpg",
                "title": "Effective java 中文版(第2版)"
            }
        }
    ]
}';
$res=json_decode($tmp,true);
$res = $res['collections'];
foreach($res as $v){
//已经读过的书
if($v['status']=="read"){
    $book_name=$v['book']['title'];
    $book_img = $v['book']['image'];
    $readlist[] = array("name"=>$book_name,"img"=>$book_img);
}elseif($v['status']=="reading"){
    //正在读的书
    $book_name=$v['book']['title'];
    $book_img = $v['book']['image'];
    $readinglist[] = array("name"=>$book_name,"img"=>$book_img);
}
}
?>
<div class="booklist">
    <div class="section">
        <h4>在读</h4>
        <ul class="clearfix">
             foreach($readinglist as $v):?>
            <li>
                <div class="photo"><img src="$v['img'];?>" width="98" height="151" /></div>
                <div class="rsp"></div>
                <div class="text"><h3> echo $v['name'];?></h3></div>
            </li>
             endforeach; ?>
         </ul>
    </div>
    <div class="section">
        <h4>已读</h4>
        <ul  class="clearfix">
             foreach($readlist as $v):?>
            <li>
                <div class="photo"><img src="$v['img'];?>" width="98" height="151" /></div>
                <div class="rsp"></div>
                <div class="text"><h3> echo $v['name'];?></h3></div>
            </li>
             endforeach; ?>
        </ul>
    </div>
</div>

#get_sidebar();
get_footer();

CSS 样式:

.booklist .section h4{  padding: 3px 0 3px 15px;border-left: 5px solid #ddd;margin: 10px 0;font-weight:bold;}
.booklist .section{width:100%;margin:10px auto 0 auto;overflow:hidden;}
.booklist .section ul{width:100%;}
.booklist .section ul li{float:left;margin-right:6px;margin-bottom:10px;display:inline;width:98px;height:151px;overflow:hidden;position:relative;}
.booklist .section ul li .photo{width:98px;height:151px;overflow:hidden;}
.booklist .section .rsp{width:98px;height:151px;overflow:hidden;position: absolute;background:#000;top:0px;left:0px;}
.booklist .section .text{position:absolute;width:98px;height:151px;left:-300px;top:0px;overflow:hidden;}
.booklist .section .text h3{width:98px;margin-top:49px;height:50px;line-height:20px;text-align:center;color:#FFFFFF;font-size:14px;}
.booklist .section .text a{text-decoration:none}

JS代码:
在使用js代码的时候,可能会出现图片是黑的,这是因为jQuery包没有导入进来,在 www.jquery.com 官网中下载开发包,放入到主题目录下, 然后在header.php 文件中的 头文件中引入刚在下载 jQuery包,建议使用绝对路径。红框框中就是我使用的绝对路径,相对路径我也没有搞明白,PHP以前也没学过。
blob.jpg

<script type="text/javascript">
    $(document).ready(function(){
        $(".booklist .section ul li .rsp").hide();
        $(".booklist .section    ul li").hover(function(){
                $(this).find(".rsp").stop().fadeTo(500,0.5)
                $(this).find(".text").stop().animate({left:'0'}, {duration: 500})
            },
            function(){
                $(this).find(".rsp").stop().fadeTo(500,0)
                $(this).find(".text").stop().animate({left:'30'}, {duration: "fast"})
                $(this).find(".text").animate({left:'-300'}, {duration: 0})
            });
    });
</script>

下载豆瓣书单图片的Java代码

package com.wxy.download.bookinfo;

import org.json.JSONArray;
import org.json.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import static sun.net.www.protocol.http.HttpURLConnection.userAgent;

/**
 * Created by Kode on 2019/1/14.
 */
public class DownloadBookInfo {
    public static void main(String[] args){
        String userId = "***";// 你自己豆瓣账号ID
        String urll = "https://api.douban.com/v2/book/user/"+userId+"/collections?count=100; ";
        String httpsRequest = httpsRequest(urll, "GET", "null");
        JSONObject jsonObject1 = new JSONObject(httpsRequest);
       // JSONObject jsonObject = new JSONObject().getJSONObject(httpsRequest);
        JSONArray collecObj = (JSONArray)jsonObject1.get("collections");
        for (int i = 0; i < collecObj.length(); i++) {
        //    if (collecObj.get(i))
            JSONObject o = (JSONObject)collecObj.get(i);
            String status = o.getString("status");
            JSONObject book = (JSONObject) o.get("book");
            String title = book.getString("title");
            JSONObject images = (JSONObject)book.get("images");
            String imageUrl = images.getString("medium");
            String savePath = "C:\\Users\\Kode\\Desktop\\读书名单图片";
            //System.out.println("第"+ i + "本书");
            System.out.println("\t \t{");
            System.out.println("\t \t \t \t \"status\": " + "\"" + status + "\"");
            System.out.println("\t \t \t \t \"book\": {");
            System.out.println("\t \t \t \t \t \t \"image\": " + "\"" + imageUrl + "\"");
            try {
               // download(imageUrl,title+".jpg", savePath);
            } catch (Exception e) {
                e.printStackTrace();
            }
//            System.out.println("imageUrl: " + imageUrl);
            System.out.println("\t \t \t \t \t \t \"title\": " + "\"" + title + "\"");
//            System.out.println("title: " + title);
            System.out.println("\t \t \t \t }");
            System.out.println("\t \t},");
            System.out.println();
        }

    }
    public static String httpsRequest(String requestUrl,String requestMethod,String outputStr){
        StringBuffer buffer=null;
        try{
            //创建SSLContext
            SSLContext sslContext= SSLContext.getInstance("SSL");
            TrustManager[] tm={new MyX509TrustManager()};
            //初始化
            sslContext.init(null, tm, new java.security.SecureRandom());;
            //获取SSLSocketFactory对象
            SSLSocketFactory ssf=sslContext.getSocketFactory();
            URL url=new URL(requestUrl);
            HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(requestMethod);
            //设置当前实例使用的SSLSoctetFactory
            conn.setSSLSocketFactory(ssf);
            conn.connect();
            //往服务器端写内容
            if(null!=outputStr){
                OutputStream os=conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }

            //读取服务器端返回的内容
            InputStream is=conn.getInputStream();
            InputStreamReader isr=new InputStreamReader(is,"utf-8");
            BufferedReader br=new BufferedReader(isr);
            buffer=new StringBuffer();
            String line=null;
            while((line=br.readLine())!=null){
                buffer.append(line);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static void download(String urlString, String filename,String savePath) throws Exception {
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        //设置请求超时为5s
        con.setConnectTimeout(5*1000);
        // 输入流
        InputStream is = con.getInputStream();

        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        File sf=new File(savePath);
        if(!sf.exists()){
            sf.mkdirs();
        }
        OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // 完毕,关闭所有链接
        os.close();
        is.close();
    }
    public static String getURLContent(String urll, String a) throws Exception {
        String strURL = urll;
        URL url = new URL(strURL);
        HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
        String line;
        StringBuffer buffer = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        httpConn.disconnect();

        System.out.println(buffer.toString());
        return buffer.toString();
    }
    public static String getURLContent(String urlStr) {
        /** 网络的url地址 */
        URL url = null;
        /** http连接 */
        HttpURLConnection httpConn = null;
		/**//** 输入流 */
        BufferedReader in = null;
        StringBuffer sb = new StringBuffer();
        try {
            url = new URL(urlStr);
            in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
            String str = null;
            while ((str = in.readLine()) != null) {
                sb.append(str);
            }
        } catch (Exception ex) {

        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
            }
        }
        String result = sb.toString();

        return result;
    }
}

package com.wxy.download.bookinfo;

import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * Created by Kode on 2019/1/14.
 */
public class MyX509TrustManager implements X509TrustManager {


    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
        // TODO Auto-generated method stub

    }


    public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
        // TODO Auto-generated method stub

    }


    public X509Certificate[] getAcceptedIssuers() {
        // TODO Auto-generated method stub
        return null;
    }

}

通过上述的方法,阅读书单的APP就做出来了。完结。如果你有其他问题,可以一起商量商量。

你可能感兴趣的:(设计)