目录

  • 1.wordpress新建自定义页面
  • 2.wordpress引用jQuery
  • 3.wordpress调用自定义js,css文件
  • 4.隐藏前台站点头部管理栏
  • 5. 显示文章列表下文章的分类
  • 6.显示文章列表(get_posts())
  • 7.获取前一篇文章和后一篇文章
  • 8.获取文章的相关内容
  • 9.wordpress时区不正常
  • 10.自定义前台api接口
  • 11.后台表格列表实现
  • 12.wordpress使用自带的clipboard.js一键复制
  • 13.wordpress防止xss攻击,过滤输入字符串中的html

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.隐藏前台站点头部管理栏

  1. 隐藏前台站点头部管理栏
    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.phpformObject.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.自定义一个表格数据操作类

<?phpclass Contact_Record_Table extends WP_List_Table
{function __construct(){global $status, $page;//构造函数//Set parent defaultsparent::__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 contentsreturn 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

wordpress使用相关推荐

  1. wordpress主题

    1.创建wordpress主题:在themes文件下建立新主题black文件夹 2.在black文件夹中放入index.php和style.css文件, 其中index对style.css文件的引用 ...

  2. WordPress数据库优化技巧

    各位站长都知道wordpress用久了就会越来越慢.今天就给大家介绍如何给自己的wordpress提速,分两种方法: 1.插件 属性wordpress的都知道其插件是相当的多,只要你能想得到的基本都有 ...

  3. 35个必备的wordpress插件

    博客一开始是自己写的小程序,但自己写程序实在太麻烦了,不想写,于是转成了bo-blog,用了几周,感觉还是不太理想,就又转换成了wordpress,这个博客程序也不是什么省油的灯,用起来也不是很方便, ...

  4. wps解析json数据_通过WordPress HTTP API 获取json内容并解析

    WordPress 4.0的一个亮点就是JSON API的加入,今天我们提前来看看怎么获取JSON的内容并显示出来.过程就是用PHP获取远程JSON的内容,然后把获取到的JSON转化为PHP对象,然后 ...

  5. wordpress php教程 pdf,wordpress二次开发全能教程.pdf

    wordpress 二次开发全能教程 1. 根据分类来制定导航条 A. 修改页面 header.php! <?php wp_list_categories('title_li='); ?> ...

  6. wordpress自适应表格_给WordPress添加自适应表格 让表格自适应屏幕

    wordpress自带的表格不能自适应屏幕宽带,每次新建了表格,电脑上显示正常的,结果换到手机上就超出屏幕宽度了,很麻烦,更重要的是很不美观,本次我就问为大家带来一个添加自适应表格的教程. 案列分析 ...

  7. [总结]博客聚合-cnblogs,wordpress,live writer,word2010

    一.url地址: cnblogs: http://BusyAnt.cnblogs.com/services/metaweblog.aspx wordpress: http://blog.busyant ...

  8. wordpress本地mysql_如何在本地搭建和运行wordpress

    现在大家都喜欢在空间.博客写点自己的东西,发表一点自己的博文什么的,今天呢就给大家介绍一款免费的开源博客平台wordpress,非常强大,可以自己修改代码,强大的插件支持,按照自己的意愿搭建属于自己个 ...

  9. wordpress怎么修改html,WordPress后台编辑器HTML模式界面中添加修改删除按钮

    在WordPress编辑器HTML模式界面中添加 按钮一文中,我大致介绍了怎么在后台添加一些自定义的按钮,本文则更为详细全面的对wordpress后台编辑器HTML模式下的按钮自定义进行详解,以让开发 ...

  10. wordpress短代码转php,WordPress中的shortcode短代码功能使用详解

    WordPress 从 2.5 的版本开始,增加了一个 shortcode (短代码) API ,类似于 BBS 上的 BBCode , shortcode 也可以很方便的为文章或页面增加功能,并且 ...

最新文章

  1. 吴军信息论40讲_吴军信息论40讲笔记
  2. zoj How Many Shortest Path
  3. Android之TabLayout+ViewPager2+FragmentStateAdapter实现带数字变化的TAB选项
  4. 在同一窗口和同一选项卡中打开URL
  5. ios旧版本app网站_这两款app已解锁永久订阅版!
  6. SpringCloud实战(四)Sentinel自定义降级异常实战
  7. matlab 图像分割_数字图像处理第三版中_冈萨雷斯【MATLAB】(推书活动第十七期)...
  8. 出栈顺序判断问题——划线法
  9. Vivado2018【编辑器设置黑色背景】
  10. 【洛谷 P4180】【模板】严格次小生成树[BJWC2010](倍增)
  11. java lazy_Spring注解之@Lazy注解使用解析
  12. 原创超简单代码(1.19.80)
  13. mysql将没有员工的部门都删除_Mysql 用sql语句实现删除与CLARK同部门的员工信息...
  14. es6知识总结 模块 承诺加载
  15. ABBYY OCR客开demo
  16. element控制input输入为数字
  17. Netfilx Eureka
  18. android 开源库osmdroid绘制点线面(比例尺,缩小放大,导航图标等)
  19. ICE简介及C++程序例子
  20. 想看看18001年以后的金山词霸吗?金山词霸之未来版

热门文章

  1. 论文评审最大流_2018年论文评审流程
  2. [234] 回文链表
  3. C++程序员学习用C#写网站(四)
  4. 读《轻断食》的一些体会
  5. htc incredible s手机无限重启
  6. 精美个人主页引导工作室官网源码分享
  7. moments音标_法语助手|法汉-汉法词典 moment是什么意思_moment的中文解释和发音_moment的翻译_moment怎么读...
  8. Android画中画
  9. 7-99 含有2个运算符的算数表达式(选作)
  10. 发现vjudge用搜狗浏览器无法登陆