1 Star 0 Fork 0

闲闲 / scratch for wordpress

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
scratch-for-wordpress.php 37.15 KB
一键复制 编辑 原始数据 按行查看 历史
lsq 提交于 2021-06-26 13:23 . update scratch-for-wordpress.php.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
<?php
/*
Plugin Name: scratch for wordpress
Plugin URI: https://www.kccoding.cn/
Description: Declares a plugin that will create a custom post type displaying scratch.
Version: 1.0
Author: gary
Author URI: https://www.kccoding.cn/
*/
//加载页面
include_once(plugin_dir_path(__FILE__ )."add-page-template.php");
$pagetemplate=new PageTemplater();
$kcScratch = new KcScratch();
class KcScratch{
function __construct() {
add_action( 'init', array($this,'create_kc_scratch') );
//自定义文件上传类型
add_filter('upload_mimes',array($this,'custom_upload_mimes'),20,1);
//自定义分类
add_action( 'init', array($this,'create_kc_scratch_taxonomies'));
//后台编辑页面字段
add_action( 'admin_init', array($this,'kc_scratch_admin' ));
//保存自定义字段
add_action( 'save_post', array($this,'add_kc_scratch_fields'), 10, 2 );
//scratch显示模板
add_filter( 'template_include', array($this,'kc_scratch_template_function'), 1 );
//处理ajax,获取指定id附件的scratch
add_action( 'wp_ajax_scratch_url', array($this,'get_scratch_url' ));
add_action( 'wp_ajax_nopriv_scratch_url', array($this,'get_scratch_url' ));
add_action('wp_ajax_publish_scratch',array($this,'publish_scratch'));
add_action('wp_ajax_nopriv_publish_scratch',array($this,'publish_scratch'));
add_action('wp_ajax_update_post',array($this,'update_post'));
add_action('wp_ajax_publish_update',array($this,'publish_update'));
add_action('wp_ajax_nopriv_publish_update',array($this,'publish_update'));
//ajax获取作品信息
add_action( 'wp_ajax_kc_scratch_info', array($this,'kc_scratch_info'));
//ajax删除作品
add_action( 'wp_ajax_kc_delete_scratch', array($this,'kc_delete_scratch'));
//短代码 我的作品
add_shortcode('kc_my_scratch_list', array($this,'kc_my_scratch_list'));
add_shortcode('kc_scratch_list', array($this,'kc_scratch_list'));
//获取用户信息
add_action('wp_ajax_get_user_info', array($this,'get_user_info'));
add_action('wp_ajax_nopriv_get_user_info', array($this,'get_user_info'));
//登录
add_action('wp_ajax_kc_login',array($this,'kc_login'));
add_action('wp_ajax_nopriv_kc_login',array($this,'kc_login'));
//退出登录
add_action('wp_ajax_kc_logout',array($this,'kc_logout'));
add_action('wp_ajax_nopriv_kc_logout',array($this,'kc_logout'));
}
function custom_upload_mimes($existing_mimes=array()){
$existing_mimes['json']='json';
$existing_mimes['json']='text/json';
$existing_mimes['sb3']='sb3';
$existing_mimes['sb3']='application/sb3';
$existing_mimes['sprite3']='sprite3';
$existing_mimes['sprite3']='application/sprite3';
$existing_mimes['svg'] = 'image/svg+xml';
$existing_mimes['svg'] = 'svg';
return $existing_mimes;
}
//初始化插件
function create_kc_scratch() {
register_post_type( 'scratch',
array(
'labels' => array(
'name' => 'Scratch',
'singular_name' => '所有Scratch',
'add_new' => '新建',
'add_new_item' => '新建scratch',
'edit' => '编辑',
'edit_item' => '编辑scratch',
'new_item' => '新scratch',
'view' => '查看',
'view_item' => '查看scratch',
'search_items' => '搜索scratch',
'not_found' => '没有找到scratch',
'not_found_in_trash' => '回收站中没有scratch',
'parent' => '父级scratch'
),
'public' => true,
'menu_position' => 16,
'supports' => array( 'title', 'editor', 'comments', 'thumbnail'),
'taxonomies' => array( '' ),
'menu_icon' => plugins_url( 'asset/images/icon.png', __FILE__ ),
'has_archive' => true,
//添加权限
'capability_type'=>'scratch',
'capabilities' => array(
'edit_post' => 'edit_scratch',
'edit_posts' => 'edit_scratches',
'edit_others_posts' => 'edit_others_scratches',
'publish_posts' => 'publish_scratches',
'read_post' => 'read_scratch',
'read_private_posts' => 'read_private_scratches',
'delete_post' => 'delete_scratch'
)
)
);
//给管理员添加管理scratch的权限
$role = get_role( 'administrator' );
$role->add_cap( 'edit_scratch' );
$role->add_cap( 'edit_scratches' );
$role->add_cap( 'edit_others_scratches' );
$role->add_cap( 'publish_scratches' );
$role->add_cap( 'read_scratch' );
$role->add_cap( 'read_private_scratches' );
$role->add_cap( 'delete_scratch' );
//给订阅者添加scratch权限
$role = get_role( 'subscriber' );
$role->add_cap( 'edit_scratch' );
$role->add_cap( 'edit_scratches' );
$role->add_cap( 'publish_scratches' );
$role->add_cap( 'read_scratch' );
$role->add_cap( 'delete_scratch' );
}
function create_kc_scratch_taxonomies() {
register_taxonomy(
'scratch_genre',
'scratch',
array(
'labels' => array(
'name' => 'scratch分类',
'add_new_item' => '新建分类',
'new_item_name' => "新建分类"
),
'show_ui' => true,
'show_tagcloud' => false,
'hierarchical' => true
)
);
}
function kc_scratch_admin() {
add_meta_box( 'scratch_meta_box',
'scratch详情',
array($this,'display_kc_scratch_meta_box'),
'scratch', 'normal', 'high'
);
}
function display_kc_scratch_meta_box($scratch){
$scratch_operate = esc_html( get_post_meta( $scratch->ID, 'scratch_operate', true ) );
$cover = wp_get_attachment_url( get_post_meta( $scratch->ID, 'cover', true ) );
$scratch_json = esc_html( get_post_meta( $scratch->ID, 'scratch_json', true ) );
?>
<table>
<tr>
<td style="width: 20%">封面</td>
<td><img style="width:300px;" src='<?php echo $cover; ?>'>
</td>
</tr>
<tr>
<td style="width: 20%">操作说明</td>
<td>
<?php wp_editor( $scratch_operate, 'scratch_operate', $settings = array(
'quicktags'=>array(),
'tinymce'=>0,
'media_buttons'=>0,
'textarea_rows'=>4,
'editor_class'=>"textareastyle")); ?>
</td>
</tr>
<tr>
<td style="width: 20%">scratch附件</td>
<td><input type="text" size="40" name="scratch_json" value="<?php echo $scratch_json; ?>" />
<a href='#'>编辑</a>
</td>
</table>
<?php
}
function add_kc_scratch_fields( $scratch_id, $scratch ) {
// Check post type for scratch
if ( $scratch->post_type == 'scratch' ) {
// Store data in post meta table if present in post data
if ( isset( $_POST['scratch_operate'] ) && $_POST['scratch_operate'] != '' ) {
update_post_meta( $scratch_id, 'scratch_operate', $_POST['scratch_operate'] );
}
if ( isset( $_POST['cover'] ) && $_POST['cover'] != '' ) {
update_post_meta( $scratch_id, 'cover', $_POST['cover'] );
}
if ( isset( $_POST['scratch_file'] ) && $_POST['scratch_json'] != '' ) {
update_post_meta( $scratch_id, 'scratch_json', $_POST['scratch_json'] );
}
}
}
function kc_scratch_template_function( $template_path ) {
if ( get_post_type() == 'scratch' ) {
if ( is_single() ) {
// checks if the file exists in the theme first,
// otherwise serve the file from the plugin
$template_path=self::scratch_template('single-scratch.php');
}
if ( is_archive() ) {
$template_path=self::scratch_template('archive-scratch.php');
}
}
return $template_path;
}
function scratch_template($themes){
if ( $theme_file = locate_template( array ( $themes ) ) ) {
$template_path = $theme_file;
} else {
$template_path = plugin_dir_path( __FILE__ ) . $themes;
}
return $template_path;
}
// 获取scratch地址
function get_scratch_url(){
$id=isset($_GET['id']) ? $_GET['id'] : '';
if ($id!='') {
//如果存在scratch_file,优先加载scratch_file,sb3文件
$sid=get_post_meta($id,'scratch_json',true);
// if ($sid=='') {
// $sid=get_post_meta($id,'scratch_file',true);
// }
if(wp_get_attachment_url(trim($sid))){
$url=wp_get_attachment_url(trim($sid));
$url=str_replace('http://','//',$url);
// $url=str_replace('://www','://cdn',$url);
// echo $url;
header("Location:".$url);
}else{
header("Location: /scratch3/default.json");
}
}else{
header("Location: /scratch3/default.json");
}
exit;
}
//发布scratch
function publish_scratch(){
if (!is_user_logged_in()) { //判断是否登录
$result['success']="log_out";
echo json_encode($result);
exit;
}
if (!current_user_can('publish_scratches')) { //判断是否有权限
$result['success']="no_capability";
echo json_encode($result);
exit;
}
$current_user = wp_get_current_user();
$my_post = array(
'post_title' => $_POST['post_title'],
'post_author'=>$current_user->ID,
'post_type'=>'scratch',
);
//上传scratch封面信息
$upload_cover = array(
'name' => time().'.png',
'type' => 'png',
'tmp_name' => $_FILES['cover']['tmp_name'],
'error' => $_FILES['cover']['error'],
'size' => $_FILES['cover']['size']
); //项目json文件
$upload_json = array(
'name' => time().'.json',
'type' => 'json',
'tmp_name' => $_FILES['scratch_json']['tmp_name'],
'error' => $_FILES['scratch_json']['error'],
'size' => $_FILES['scratch_json']['size']
);
//上传文件
$post_id = wp_insert_post( $my_post );
header('Content-Type: text/html; charset=' . get_option('blog_charset'));
$upload_cover_result=self::handle_upload($upload_cover,$post_id);
$upload_json_result=self::handle_upload($upload_json,$post_id);
//上传scratch素材
$files = array();
for ($i=0 ; $i < $_POST["file_count"]; $i++ ) {
$files[$i]=$_FILES["file".$i];
}
self::kc_scratch_asset_handle_upload($files);
//上传成功后关联文章
if ($upload_cover_result['success'] && $upload_json_result['success']) {
update_post_meta($post_id,'scratch_json',$upload_json_result['attach_id']);
update_post_meta($post_id,'cover',$upload_cover_result['attach_id']);
$upload_result['post_id']=$post_id;
$upload_result['success']='true';
}else{
//如果上传失败则删除新建文章
print_r($upload_cover_result);
print_r($upload_json_result);
wp_delete_post($post_id, true);
$upload_result['success']="false";
}
echo json_encode($upload_result);
exit;
}
//更新作品信息
function update_post(){
$current_user = wp_get_current_user();
$post_id=$_POST['post_id'];
if ( is_user_logged_in() && ($current_user->ID==get_post($post_id)->post_author || current_user_can('edit_scratch') || current_user_can('edit_others_scratches'))){ //判断是否是作者或管理员
$data=explode(',',$_POST['post_cate']);
$post =array(
'ID'=>$post_id,
'post_title'=>$_POST['post_title'],
'post_content'=>$_POST['post_content'],
'post_status'=>'publish',
'tax_input' => array( //更改自定义文章分类
'scratch_genre'=>$data
),
'meta_input' => array( //更新自定义字段
'scratch_operate'=>$_POST['scratch_operate'],
)
);
wp_update_post( $post );
$result['success']=true;
echo json_encode($result);
}
exit;
}
//更新scratch
function publish_update(){
$id=isset($_POST['id']) ? $_POST['id'] :'';
$current_user = wp_get_current_user();
if(!is_user_logged_in()){
echo "log_out";
exit;
}
if ( is_user_logged_in() && $id!='' && count(get_post($id))!=0 && ($current_user->ID==get_post($id)->post_author || current_user_can('edit_scratch') || current_user_can('edit_others_scratches'))){
header('Content-Type: text/html; charset=' . get_option('blog_charset'));
//scratch封面信息
$upload_cover = array(
'name' => time().'.png',
'type' => 'png',
'tmp_name' => $_FILES['cover']['tmp_name'],
'error' => $_FILES['cover']['error'],
'size' => $_FILES['cover']['size']
);
//项目json文件
$upload_json = array(
'name' => time().'.json',
'type' => 'json',
'tmp_name' => $_FILES['scratch_json']['tmp_name'],
'error' => $_FILES['scratch_json']['error'],
'size' => $_FILES['scratch_json']['size']
);
$upload_cover_result=self::handle_upload($upload_cover,$id);
$upload_json_result=self::handle_upload($upload_json,$id);
//上传scratch素材
$files = array();
for ($i=0 ; $i < $_POST["file_count"]; $i++ ) {
$files[$i]=$_FILES["file".$i];
}
self::kc_scratch_asset_handle_upload($files);
//上传成功后关联文章
if ($upload_cover_result['success'] && $upload_json_result['success']) {
//删除旧文件
wp_delete_attachment(get_post_meta($id,"cover",true));
wp_delete_attachment(get_post_meta($id,"scratch_json",true));
//更新信息
update_post_meta($id,'scratch_json',$upload_json_result['attach_id']);
update_post_meta($id,'cover',$upload_cover_result['attach_id']);
}
// print_r($upload_dir['basedir']);
echo "success";
}else{
echo '权限错误!!';
}
exit;
}
//上传资源到wp-content/uploads/assets文件夹
function kc_scratch_asset_handle_upload($files){
//允许上传的文件类型
$allowed_type=array(
'mp3','wav','jpg','png','svg','jpeg'
);
$upload_dir=$_SERVER['DOCUMENT_ROOT']."/wp-content/uploads/asset/";
$re=true;
$result=true;
foreach ($files as $key => $file) {
$file_name_ex = explode('.',$file['name']);
$file_type = $file_name_ex[1];
if (!file_exists($upload_dir.$file['name'])) {
$re=move_uploaded_file($file['tmp_name'],$upload_dir.$file['name']);
}
if ($re==false) {
$result=false;
}
}
return $result;
}
/**
* Generic function to upload a file
*
* @param string $field_name file input field name
* @return bool|int attachment id on success, bool false instead
*/
function handle_upload( $upload_data ,$id) {
if ( is_user_logged_in() ){
$uploaded_file = wp_handle_upload( $upload_data, array('test_form' => false));
// print_r($uploaded_file);
// If the wp_handle_upload call returned a local path for the image
if ( isset( $uploaded_file['file'] ) ) {
$file_loc = $uploaded_file['file'];
$file_name = basename( $upload_data['name'] );
$file_type = wp_check_filetype( $file_name );
$attachment = array(
'post_mime_type' => $file_type['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $file_name ) ),
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => $id
);
$attach_id = wp_insert_attachment( $attachment, $file_loc );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file_loc );
wp_update_attachment_metadata( $attach_id, $attach_data );
return array('success' => true, 'attach_id' => $attach_id);
}
return array('success' => false, 'error' => $uploaded_file['error']);
}
}
function kc_scratch_info(){
$id=$_GET['id'];
$post=get_post($id,'ARRAY_A');
$post['scratch_operate']=get_post_meta($id,'scratch_operate',true);
$post['scratch_simulate']=get_post_meta($id,'scratch_simulate',true);
$post['homework_comment']=get_post_meta($id,'homework_comment',true);
$post['tuijian']=get_post_meta($id,'tuijian',true);
foreach (get_the_terms($id,'scratch_genre') as $key => $cat) {
$cate.=$cat->term_id.',';
}
$post['cate']=$cate;
echo json_encode($post);
exit;
}
function kc_delete_scratch(){
if (is_user_logged_in() && current_user_can('delete_scratch')) {
$current_user=wp_get_current_user();
$id=$_GET['id'];
$post=get_post($id);
// echo $post->ID;
if ($current_user->ID==$post->post_author) {
wp_delete_post($post->ID,true);
$results['success']=true;
}
echo json_encode($results);
}
exit;
}
function kc_my_scratch_list(){
//已发布文章
$args = array(
// 用于查询的参数或者参数集合
'author'=>wp_get_current_user()->ID,
'post_parent'=>0,
'post_type'=>'scratch',
'post_status'=>'publish'
);
// 自定义查询
$the_query = get_posts( $args );
// print_r($the_query);
$str='<div id="published-scratch" class=" scratch-list col-lg-12 col-md-12 d-flex" style="flex-wrap:wrap;"><h3 class="col-12">已发布</h3>';
foreach ($the_query as $key => $post) {
# code...
$permalink=get_the_permalink($post->ID);
$cover=wp_get_attachment_url(get_post_meta($post->ID, 'cover', true));
$title=get_the_title($post->ID);
$views=get_post_meta($post->ID,'views',true);
$avatvr=get_avatar($post->ID,15) ;
$author=get_the_author();
$str.= '<div class="scratch-content sc-'.$post->ID.' col-lg-4 col-md-4 col-sm-6 col-xs-6"><div class="excerpt-scratch">';
$str.='<a href="'.$permalink.'"><img src="'.$cover.'" alt=""></a>';
$str.='<h4>'.$title.'</h4>';
$str.= ' <div class="blogpost_meta">';
// $str.='<span><i class="iconfont icon-liulan"></i>'.$post->views.'</span>';
// $str.='<span><i class="iconfont icon-pinglun"></i>'.$post->comment_count.'</span>';
// $str.='<span><i class="iconfont icon-zan"></i></span>';
$str.='<span><a href="javascript:edit_scratch('.$post->ID.')">发布</a></span>';
$str.='<span><a href="/create#'.$post->ID.'" target="_blank">编辑</a></span>';
$str.='<span><a href="javascript:delete_scratch('.$post->ID.')">删除</a></span>';
$str.=' </div>';
// $str.=' <div class="blogpost_meta">'.$avatar.'<a href="https://www.kccoding.cn/author/kccoding/">'.$author.'</a></div>';
$str.='</div></div>';
}
$str.='</div>';
//草稿
$args = array(
// 用于查询的参数或者参数集合
'author'=>wp_get_current_user()->ID,
'post_parent'=>0,
'post_type'=>'scratch',
'post_status'=>'draft'
);
// 自定义查询
$the_query = get_posts( $args );
// print_r($the_query);
$str.='<div id="draft-scratch" class="scratch-list col-lg-12 col-md-12"><h4>未发布</h4>';
foreach ($the_query as $key => $post) {
# code...
$permalink=get_the_permalink($post->ID);
$cover=wp_get_attachment_url(get_post_meta($post->ID, 'cover', true));
$title=get_the_title($post->ID);
$views=get_post_meta($post->ID,'views',true);
$avatvr=get_avatar($post->ID,15) ;
$author=get_the_author();
$str.= '<div class="scratch-content col-lg-4 col-md-4 col-sm-6 col-xs-6"><div class="excerpt-scratch">';
$str.='<a href="'.$permalink.'"><img src="'.$cover.'" alt=""></a>';
$str.='<h4>'.$title.'</h4>';
$str.= ' <div class="blogpost_meta">';
// $str.='<span><i class="iconfont icon-liulan"></i>'.$post->views.'</span>';
// $str.='<span><i class="iconfont icon-pinglun"></i>'.$post->comment_count.'</span>';
// $str.='<span><i class="iconfont icon-zan"></i></span>';$str.='<span><i class="iconfont icon-liulan"></i>发布</span>';
$str.='<span><a href="javascript:edit_scratch('.$post->ID.')">发布</a></span>';
$str.='<span><a href="/create#'.$post->ID.'" target="_blank">编辑</a></span>';
$str.='<span><a href="javascript:delete_scratch('.$post->ID.')">删除</a></span>';
$str.=' </div>';
// $str.=' <div class="blogpost_meta">'.$avatar.'<a href="https://www.kccoding.cn/author/kccoding/">'.$author.'</a></div>';
$str.='</div></div>';
}
$str.='</div>';
// 重置请求数据
wp_reset_postdata();
?>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">
作品信息
</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
&times;
</button>
</div>
<div class="modal-body">
<div class="col-sm-12">
<label>作品名称:<br><input type='input' id='post_title' ></label><br>
<label>作品分类:</label>
<?php $cate=get_categories( array('type'=>'post','taxonomy'=>'scratch_genre','hide_empty'=>'0'));
foreach ($cate as $key => $value) {
echo '<label><input name="post_cate" type="checkbox" value="'.$value->term_id.'" />'.$value->name.'</label>';
}
?>
<br>
<label>作品简介:<?php wp_editor( '', 'post_content', $settings = array(
'quicktags'=>array(),
'tinymce'=>0,
'media_buttons'=>0,
'textarea_rows'=>4,
'editor_class'=>"textareastyle")); ?></label><br>
<label>操作说明:<?php wp_editor( '', 'scratch_operate', $settings = array(
'quicktags'=>array(),
'tinymce'=>0,
'media_buttons'=>0,
'textarea_rows'=>4,
'editor_class'=>"textareastyle")); ?></label><br>
</div>
<div style="clear:both;"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭
</button>
<button type="button" class="btn btn-primary" id="update_post">
发布
</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
<script>
var post_id;
function edit_scratch (id){
post_id=id;
$('#myModal').modal();
//读取作品信息
$.get('/wp-admin/admin-ajax.php?action=kc_scratch_info','id='+id,
function(res){
var cat=res.cate;
$("input[name=post_cate").removeAttr('checked');
if (cat!=null) {
$("input[name=post_cate]").each(function(){
if (cat.indexOf($(this).val()) != -1) {
$(this).attr("checked",'checked');
}
});
}
$("#post_title").val(res.post_title);
$("#post_content").val(res.post_content);
$("#scratch_operate").val(res.scratch_operate);
if (res.scratch_simulate=="") {
res.scratch_simulate=1;
}
$("input[name=scratch_simulate]:eq("+(res.scratch_simulate-1)+")").attr("checked",'checked');
},'json'
);
}
$('#update_post').click(function(){
var post_cate=new Array();
$('input[name="post_cate"]:checked').each(function(){
post_cate.push($(this).val());//向数组中添加元素
});
var formData = new FormData();
formData.append('post_id',post_id);
formData.append('post_title', $('#post_title').val());
formData.append('post_cate', post_cate);
formData.append('post_content', $('#post_content').val());
formData.append('scratch_operate', $('#scratch_operate').val());
formData.append('scratch_simulate', $('input[name="scratch_simulate"]:checked').val());
$.ajax({
url: '/wp-admin/admin-ajax.php?action=update_post',
type: 'post',
processData: false,
cache: false,
encType: 'multipart/form-data',
contentType: false,
data: formData,
success: function(res){
res=$.parseJSON(res);
if (res.success) {
$('#myModal').modal('hide');
$("#modalSuccess").modal('show');
window.location.reload();
}
}
});
});
function delete_scratch(id){
var del=confirm('你确定要删除此作品吗?');
if (del==true) {
$.get('/wp-admin/admin-ajax.php?action=kc_delete_scratch','id='+id,function(res){
if (res.success) {
window.location.reload();
}
},'json');
}
}
</script>
<?php
return $str;
}
//scratch 列表短代码
function kc_scratch_list($atts){
extract ( shortcode_atts ( array (
'cat' => 0 ,
'num' => 3,
'title' =>'作品列表',
'orderby'=>''
) , $atts ) ) ;
$order_meta_value='';
//按自定义字段排序,views,love,comment_count
if ($orderby=='views' || $orderby=='love') {
$orderkey='meta_value_num';
$order_meta_value=$orderby;
}else{
$orderkey=$orderby;
}
$args = array(
'post_type'=>'scratch',
'posts_per_page'=>$num,
'tax_query' => ($cat !=0) ? array( //(array) - use taxonomy parameters (available with Version 3.1).
'relation' => 'AND', //(string) - Possible values are 'AND' or 'OR' and is the equivalent of running a JOIN for each taxonomy
array(
'taxonomy' => 'scratch_genre', //(string) - Taxonomy.
'field' => 'slug', //(string) - Select taxonomy term by ('id' or 'slug')
'terms' => $cat, //(int/string/array) - Taxonomy term(s).
'include_children' => true, //(bool) - Whether or not to include children for hierarchical taxonomies. Defaults to true.
'operator' => 'IN' //(string) - Operator to test. Possible values are 'IN', 'NOT IN', 'AND'.
)
) : '',
'meta_key' => $order_meta_value,
'orderby' => $orderkey,
'order' => 'DESC'
);
// 自定义查询
$the_query = new WP_Query($args);
// 判断查询的结果,检查是否有文章
$return ='<header class="post-list container animated fadeInUp"><h3 class="title text-center m-4">'.$title.'</h3></header>';
$return .= '<div class="k-main" style="background: rgb(245, 245, 245); transform: none;">
<div class="container" style="transform: none;">
<div class="row" style="transform: none;">
<div class="col-12 d-flex board">';
if ($the_query->have_posts()) :
// 通过查询的结果,开始主循环
while ($the_query->have_posts()) :
$the_query->the_post(); //获取到特定的文章
$return.='<div class="article-panel col-lg-3 col-sm-6 col-xs-6">
<div class="article-panel-content">
<span class="a-card d-none d-md-block d-lg-block">';
$article_comment = kckda_option('g_article_comment', '20');
$article_love = kckda_option('g_article_love', '200');if (is_sticky()) {
$return .= '<i class="kicon i-card-top"></i>';
} elseif (findSinglecomments(get_the_ID()) >= $article_comment || get_post_meta(get_the_ID(), 'love', true) >= $article_love) {
$return .= ' <i class="kicon i-card-hot"></i>';
}
$return .= '</span>';
if (kckda_option('g_thumbnail', true)) {
$return .= ' <div class="a-thumb">';
$return .= '<a href="' . get_permalink() . '">';
$return .= '<img src="' . wp_get_attachment_url(get_post_meta(get_the_ID(), 'cover', true)). '"></a>
</div>';
}
$return .= '<div class="a-post ';
if (!kckda_option('g_thumbnail', true)) {
$return .= 'a-none';
}
$return .= '"><div class="header">';
// $category = get_the_category();
// if ($category) {
// $return .= '<a class="label" href="' . get_category_link($category[0]->term_id) . '">' . $category[0]->cat_name . '<i class="label-arrow"></i></a>';
// } else {
// $return .= '<span class="label">' . __('页面', 'kckda') . '<i class="label-arrow"></i></span>';
// }
$return .= '<h3 class="title" style="font-size:16px;"><a class=" d-block" href="' . get_permalink() . '">' . get_the_title() . '</a></h3>
</div>';
// $return.='<div class="content">
// <p>';
// $return .= wp_trim_words(get_the_excerpt(), 260) . '</p></div>';
$return.='</div>';
$return.='<div class="a-meta">
<span class="float-left d-none d-md-block">
<span class="mr-2"><i class="kicon i-comments"></i>' . get_comments_number('0', '1', '%') . '</span>
</span>
<span class="float-left d-block">
<span class="mr-2"><i class="kicon i-hot"></i>' . get_post_views() . '</span>
<span class="mr-2"><i class="kicon i-good"></i>';
if (get_post_meta(get_the_ID(), 'love', true)) {
$return .= get_post_meta(get_the_ID(), 'love', true);
} else {
$return .= '0';
}
$return .= '
</span>
<span class="mr-2"><i class="kicon i-author"></i>' . get_the_author_meta('display_name') . '</span>
</span>
</div>';
$return.=' </div></div>';
endwhile;
endif;
// 重置请求数据
$return.='</div>
</div></div></div>';
return $return;
}
function get_user_info(){
if (is_user_logged_in()) {
$current_user=wp_get_current_user();
$userinfo=array(
'session'=>array(
'user'=>array(
'username'=>$current_user->display_name,
'thumbnailUrl'=>get_avatar_url($current_user->ID)
)
)
);
}else{
$userinfo=array(
'session'=>array(
'user'=>array(
'username'=>"",
'thumbnailUrl'=>''
)
)
);
}
echo(json_encode($userinfo));
exit;
}
function kc_login(){
$data=json_decode(file_get_contents('php://input'));
// print_r($data);
$creds=array(
'user_login'=>$data->account,
'user_password'=>$data->password
);
$user = wp_signon( $creds, false );
if( is_wp_error($user) ){
echo json_encode(str_replace("<a","<a target='_blank' ", $user->get_error_message()));
}else{
$user_info=array(
'session'=>array(
'user'=>array(
'username'=>$user->display_name,
'id'=>$user->ID,
'thumbnailUrl'=>get_avatar_url($user->ID)
)
));
echo(json_encode($user_info));
}
exit;
}
function kc_logout(){
// header("Access-Control-Allow-Origin: 0.0.0.0:8601");
// header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
// header('Access-Control-Allow-Headers:x-requested-with,content-type');
wp_logout();
echo json_encode("'logout':'logout'");
exit;
}
}
PHP
1
https://gitee.com/poqiu/scratch-for-wordpress.git
git@gitee.com:poqiu/scratch-for-wordpress.git
poqiu
scratch-for-wordpress
scratch for wordpress
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891