目录
1.wordpress新建自定义页面
1.1 新建自定义页面的php文件,文件放在themes/主题名/templates/下,文件头部加段注释,标识模板名称
1.2.新建页面
1.3.选择模板,
2.wordpress引用jQuery
在themes/主题名/下找到header.php,加入以下代码,即可使用jQuery.
3.wordpress调用自定义js,css文件
get_template_directory_uri():指向当前的主题文件夹
示例:http://localhost/mywp/wp-content/themes/twentytwenty
4.隐藏前台站点头部管理栏
-
隐藏前台站点头部管理栏
4.1.下载Role User Editor用户权限插件(php版本需要是7.3及以上)
4.2.进入设置,选择用户角色编辑时管理员也可编辑
4.3.进入用户-》用户角色编辑-》改变管理者权限
第二种方法
//将下面代码放到当前使用主题下的function.php中
show_admin_bar(false);
5. 显示文章列表下文章的分类
<?php
$categories = get_the_category();
$separator = ", "; $output = '';
if($categories){
foreach($categories as $category){
$output .= '<a href="'.get_category_link($category->term_id).'">'.
$category->cat_name.'</a>'.$separator;
}
}
echo trim($output, $separator);
?>
//文章页调用分类名称
<?php foreach((get_the_category()) as $category){echo $category->cat_name;} ?>
//调用分类别名:
<?php $cat = get_category($cid);echo $cat->slug;?>
//文章页调用分类链接
<?php
$category = get_the_category();
if($category[0]){
echo ''.get_category_link($category[0]->term_id ).'';
}
?>
6.显示文章列表(get_posts())
//案例:获取页面上那篇文章的分类,然后显示这个分类下最新的5篇文章,获取到文章的篇数以及确定该文章所属的分类
<?php/*single page?show current category articles*/?>
<?phpif ( is_single() ) :global $post;
$categories = get_the_category();
foreach ($categories as $category) : ?>
<li class="widget widget_recent_entries" id="<?php $category->term_id;?>-posts">
<h2 class="widgettitle"><?php echo $category->name; ?></h2>
<ul>
<?php $posts = get_posts('numberposts=5&category='. $category->term_id);
foreach($posts as $post) : ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </li>
<?php endforeach; ?> </ul> </li>
<?phpendforeach; endif ; ?>
<?php/*end show current category articles*/?>
get_posts()函数详解
<?php
$args = array(
'numberposts' => 5,
'offset' => 0,
'category' => ,
'orderby' => 'post_date',
'order' => 'DESC',
'include' => ,
'exclude' => ,
'meta_key' => ,
'meta_value' => ,
'post_type' => 'post',
'post_mime_type' => ,
'post_parent' => ,
'post_status' => 'publish' );
$posts_array = get_posts( $args );
?>
// $args是函数必要的变量,这个函数将返回数组型的变量
<?php
$args = array(
//需要提取的文章数
'numberposts' => 10,
//以第几篇文章为起始位置
'offset' => 0,
//分类的ID,多个用逗号将分类编号隔开,或传递编号数组,可指定多个分类编号。
//大部分 CMS 使用该函数的重点。
'category' => ,
//排序规则(注1)
'orderby' => 'post_date',
//升序、降序 'ASC' —— 升序 (低到高) 'DESC' —— 降序 (高到底)
'order' => 'DESC',
//要显示文章的ID
'include' => ,
//要排除文章的ID
'exclude' => ,
//自定义字段名称
'meta_key' => ,
//自定义字段的值,配合上一个参数,来选择显示符合自定义字段数值的文章。
'meta_value' => ,
//post(日志)——默认,page(页面),
//attachment(附件),any —— (所有)
'post_type' => 'post',
//文章的 mime 类型
'post_mime_type' => ,
//要显示文章的父级 ID
'post_parent' => ,
//文章状态
'post_status' => 'publish' );
?>
其中最主要的orderby参数有以下值
‘author’ —— 按作者数值编号排序
‘category’ —— 按类别数值编号排序
‘content’ —— 按内容排序
‘date’ —— 按创建日期排序
‘ID’ —— 按文章编号排序
‘menu_order’ —— 按菜单顺序排序。仅页面可用。
‘mime_type’ —— 按MIME类型排序。仅附件可用。
‘modified’ —— 按最后修改时间排序。
‘name’ —— 按存根排序。
‘parent’ —— 按父级ID排序
‘password’ —— 按密码排序
‘rand’ —— 任意排序结果
‘status’ —— 按状态排序
‘title’ —— 按标题排序
‘type’ —— 按类型排序
7.获取前一篇文章和后一篇文章
//获取前一篇文章
get_previous_post($in_same_term, $excluded_categories, $taxonomy)
//获取后一篇文章
get_next_post($in_same_term, $excluded_categories, $taxonomy)
参数1:$in_same_term (布尔类型)(可选)
含义:指定文章是否在同一分类目录或标签下
默认:false
参数2:$excluded_terms (数组或字符串)(可选)
含义:指定文章不要在这些目录id下查询(id用数组传递或者用逗号分隔开的字符串)
默认:''
参数3:$taxonomy (字符串)(可选)
分类法,如果 $in_same_term 设置为 true,可设置此项。WordPress 3.8 版本加入此项。
默认: 'category'。 也可以设为分类类型为标签。
函数返回值
若成功则返回 Post 对象;
如果全局变量 $post 没有被设置,则返回Null;
如果没有找到任何文档,则返回一个空的字符串 。
//代码示例
<?php //前一篇文章和后一篇文章
$prev_post = get_previous_post(true);
$pre_url = get_permalink( $prev_post->ID );
$prev_title = $prev_post->post_title;
$next_post = get_next_post(true);
$next_url = get_permalink( $next_post->ID );
$next_title = $next_post->post_title;
?>
8.获取文章的相关内容
//文章链接
<?php the_permalink() ?>
//判断是否有缩略图
has_post_thumbnail()
//缩略图
<?php the_post_thumbnail(); ?>
//文章标题
<?php the_title(); ?>
//文章摘要
<?php the_excerpt();?>
//文章发布时间
<?php the_time('Y-m-d'); ?>
//作者姓名
<?php the_author(); ?>
//文章内容
<?php the_content(); ?>
9.wordpress时区不正常
1.后台直接修改
首先,后台-设置-常规,检查一下WordPress时区设置是否正确,一般为上海或者UTC+8,才能正确显示东八区时间。
2.根目录配置文件修改
大部分人发现即使这样修改后,时区仍然错误,那就要直接修改WordPress根目录的wp-settings.php。
将"date_default_timezone_set( ‘UTC’ );“修改为"date_default_timezone_set( ‘Asia/Shanghai’ );”
10.自定义前台api接口
1.在主题函数文件里functions.php里添加hook钩子函数
///themes/主题名/functions.php
//留言提交
function submit_contact(){
global $wpdb; //这里需要引入数据库对象全局变量,不然操作不了数据库
$name = $_POST['name'];
$phone = $_POST['phone'];
$message = $_POST['comment'];
$insert_data = array(
'name' => $name,
'phone' => $phone,
'message' => $message,
'create_time'=> date('Y-m-d H:i:s')
);
$rs = $wpdb->insert('wp_contact_record', $insert_data);
if ($rs) {
$arr = array(
'data' => $rs,
'msg' => '提交成功',
'code' => '1'
);
echo json_encode($arr);
exit; //注意这个必须要有
} else {
$arr = array(
'data' => '',
'msg' => '提交失败',
'code' => '0'
);
echo json_encode($arr);
exit; //注意这个必须要有
}
}
//add_action('action名称','回调函数')
add_action('wp_ajax_submit_contact','submit_contact'); //针对登录用户
add_action('wp_ajax_nopriv_submit_contact', 'submit_contact');//针对非登录用户
2.前端请求
<?php $admin_url=admin_url( 'admin-ajax.php' );?>//必须使用这个url,指向admin-ajax.php
formObject.action = 'submit_contact';
$.ajax({
type: "post",
url: "<?php echo $admin_url;?>",
data: formObject,
dataType: 'json',
success: function (res) {
var code = res.code;
if (code==1){
$('.success_div').css('display','block');
setTimeout(function (){
$('.success_div').css('display','none');
//window.location.href = location.href;
},2000)
}else{
//alert('提交失败');
}
}
})
}
11.后台表格列表实现
1.自定义一个表格数据操作类
<?php
class Contact_Record_Table extends WP_List_Table
{
function __construct()
{
global $status, $page;
//构造函数
//Set parent defaults
parent::__construct(array(
'singular' => 'contact_record', //singular name of the listed records
'plural' => 'contact_record', //plural name of the listed records
'ajax' => false //does this table support ajax?
));
}
//列标题设置
function get_columns()
{
$columns = array(
//'cb' => '<input type="checkbox" />', //选择框
'name' => '姓名',
'phone' => '联系方式',
'message'=>'留言',
'create_time'=>'提交时间'
);
return $columns;
}
//列是否允许排序
function get_sortable_columns()
{
$sortable_columns = array(
'name' => array('name', false),
'phone' => array('phone', false),
'message' => array('message', false),
'create_time' => array('create_time', false),
);
return $sortable_columns;
}
//动作数组关联
function get_bulk_actions()
{
$actions = array(
// 'delete' => 'Delete'
);
return $actions;
}
//动作处理函数
function process_bulk_action()
{
//Detect when a bulk action is being triggered...
//当前操作为删除
if ('delete' === $this->current_action()) {
//wp_die('Items deleted (or they would be if we had items to delete)!');
$delete_id = ( is_array( $_REQUEST['register_class'] ) ) ? $_REQUEST['register_class'] : array( $_REQUEST['register_class']);
global $wpdb;
foreach($delete_id as $id) {
$id = absint( $id );
$wpdb->query( "DELETE FROM `wp_class_register` WHERE ID = $id" );
}
}
}
//多选处理
function column_cb($item)
{
return sprintf(
'<input type="checkbox" name="%1$s[]" value="%2$s" />',
/*$1%s*/ $this->_args['singular'], //Let's simply repurpose the table's singular label ("movie")
/*$2%s*/ $item['ID'] //The value of the checkbox should be the record's id
);
}
//默认列内容处理
function column_default($item, $column_name)
{
switch ($column_name) {
case 'name':
case 'phone':
case 'create_time':
return $item[$column_name];
case 'message':
return $this->show_message_length($item['message']);
default:
return print_r($item, true); //Show the whole array for troubleshooting purposes
}
}
function show_message_length($message){
$new_message=$message;
if(strlen($message) > 20){
$new_message = substr($message,0,20);
}
return $new_message;
}
//自定义列内容处理
function column_name($item)
{
//Build row actions
$actions['see'] = sprintf('<a href="%s?action=%s&id=%s">查看留言', admin_url().'release-class.php', 'see', $item['ID']);
$message = $item['message'];
$actions['see'] ='<a href="javascript:;" οnclick="read(\''.$message.'\')">查看留言</a>';
//Return the title contents
return sprintf('%1$s%2$s',
/*$1%s*/ $item['name'],
/*$2%s*/ $this->row_actions($actions)
);
}
function prepare_items()
{
global $wpdb; //This is used only if making any database queries
$this->process_bulk_action();
$name = $_REQUEST['name'];
$phone = $_REQUEST['phone'];
$per_page = 10;
$start = 0;
$fields = '*';
$querystr = "SELECT $fields FROM `wp_contact_record` ";
$querystr .= " order by create_time DESC";
if ($_GET['paged']) {
$start = ((int)$_GET['paged'] - 1) * $per_page;
}
$querystr .= " limit " . $start . "," . $per_page;
$results=null;
$total_items=0;
/*查询*/
if( !empty($name) || !empty($phone)){
$where = ' 1=1 ';
if (!empty($name)){
$where.=" and name LIKE '%$name%'";
}
if (!empty($phone)){
$where.=" and phone LIKE '%$phone%'";
}
$querystr = "SELECT $fields FROM `wp_contact_record` WHERE $where";
$querystr .= " order by create_time DESC";
$sql="SELECT COUNT(*) as numbers FROM `wp_contact_record` WHERE $where";
$result_count = $wpdb->get_results($sql);
$total_items =(int)$result_count[0]->numbers;
$all_pages = ceil($total_items / $per_page);
if ($_GET['paged']&&(int)$_GET['paged']<=$all_pages) {
$start = ((int)$_GET['paged'] - 1) * $per_page;
}else{
$start = ($all_pages- 1) * $per_page;
}
$querystr .= " limit " . $start . "," . $per_page;
$results = $wpdb->get_results($querystr, 'ARRAY_A');
}else{
$results = $wpdb->get_results($querystr, ARRAY_A);
$sql="SELECT COUNT(*) as numbers FROM `wp_contact_record`";
$result_count = $wpdb->get_results($sql);
$total_items =(int)$result_count[0]->numbers;
}
$data = $results;
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
$this->_column_headers = array($columns, $hidden, $sortable);
$current_page = $this->get_pagenum();
$this->items = $data;
$this->set_pagination_args(array(
'total_items' => $total_items,
'per_page' => $per_page,
'total_pages' => ceil($total_items / $per_page)
));
}
public function search_box( $text, $input_id ) {
if ( empty( $_REQUEST['s'] ) && ! $this->has_items() ) {
return;
}
$input_id = $input_id . '-search-input';
?>
<p class="search-box" style="float: left;margin-top: 30px;margin-bottom: 20px;">
<label class="" for="name">姓名:</label>
<input type="search" id=name" name="name" value="<?php _admin_search_query(); ?>" />
</p>
<p class="search-box" style="float: left;margin-top: 30px;margin-bottom: 20px;">
<label class="" for="phone">联系方式:</label>
<input type="search" id=phone" name="phone" value="<?php _admin_search_query(); ?>" />
<?php submit_button( $text, '', '', false, array( 'id' => 'search-submit' ) ); ?>
</p>
<?php
}
}
后台页面展示
<?php
require_once __DIR__ . '/admin.php';
//用于查询时界面重定向
if( ! empty( $_GET['_wp_http_referer'] ) ) {
wp_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
exit;
}
require_once ABSPATH . 'wp-admin/admin-header.php';
include(ABSPATH . '/wp-admin/tableclass/Contact_Record_Table.php');
?>
<?php
$ListTable = new Contact_Record_Table();
$ListTable->prepare_items();
?>
<div class="wrap">
<h1 class="wp-heading-inline"></h1><form id="movies-filter" method="get">
<?php $ListTable->search_box('Search', 'contact_record');?>
<?php $ListTable->display() ?>
</form>
</div>
<?php
require_once ABSPATH . 'wp-admin/admin-footer.php';
12.wordpress使用自带的clipboard.js一键复制
//1.在header.php中引入clipboard.js 需要放在jquery后
<?php wp_enqueue_script("jquery");?>
<?php wp_enqueue_script( 'clipboard');?>
//2.页面中使用
<a class="share_icons copy_icon copy_btn" href="javascript:;" data-clipboard-text="<?php the_permalink(); ?>"></a>
<script>
jQuery( function( $ ) {
new ClipboardJS(".copy_btn");
})
</script>
13.wordpress防止xss攻击,过滤输入字符串中的html
//允许使用的html标签
$allowed_html = array();
$name = wp_kses($_POST['name'],$allowed_html);
$phone = wp_kses($_POST['phone'],$allowed_html);
$message = wp_kses($_POST['comment'],$allowed_html);
//介绍
<?php wp_kses($string, $allowed_html, $allowed_protocols); ?>
参数
$string
(string) (required) 将通过 kses 过滤的内容
Default: None
$allowed_html
(array) (required) 允许的 HTML 标签列表
Default: None
$allowed_protocols
(array) (optional) $string 中的链接允许的协议
Default: 默认的协议是:http, https, ftp, mailto, news, irc, gopher, nntp, feed, 和 telnet。 这个基本覆盖了大部分的链接协议,除了 javascript,它不允许被一些不受信任用户使用。
返回值
(string)
过滤了不合法 HTML 代码之后的字符串。
注解
下面是一个创建允许的HTML标签和属性的实例:
array(
'a' => array(
'href' => array(),
'title' => array()
),
'br' => array(),
'em' => array(),
'strong' => array()
);
源文件
wp-includes/kses.php