WordPress 后台发布文章时提示用户选择分类

默认情况下,如果发布文章时没有选择分类,文章就会被自动归类到 后台 > 设置 > 撰写 设置的“默认文章分类目录”:

default-category-wpdaxue_com

很多用户在后台发布文章,常常会忘记选择分类,所以很有必要添加一个提醒功能,如果没有选择分类,点击发布时,就显示一个提示信息。要实现这个功能,只要将下面的代码添加到主题的 functions.php 即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
 * WordPress 发布文章前必须选择分类
 * https://www.wpdaxue.com/choose-a-category-before-publish.html
 */
add_action('admin_footer-post.php', 'choose_a_category_before_publish');
add_action('admin_footer-post-new.php', 'choose_a_category_before_publish');
function choose_a_category_before_publish(){
	global $post_type;
	if($post_type=='post'){
		echo "<script>
jQuery(function($){
	$('#publish, #save-post').click(function(e){
		if($('#taxonomy-category input:checked').length==0){
			alert('抱歉,发布文章前,请选择一个分类');
			e.stopImmediatePropagation();
			return false;
		}else{
			return true;
		}
	});
	var publish_click_events = $('#publish').data('events').click;
	if(publish_click_events){
		if(publish_click_events.length>1){
			publish_click_events.unshift(publish_click_events.pop());
		}
	}
	if($('#save-post').data('events') != null){
		var save_click_events = $('#save-post').data('events').click;
		if(save_click_events){
		  if(save_click_events.length>1){
			  save_click_events.unshift(save_click_events.pop());
		  }
		}
	}
});
</script>";
	}
}

/**
* WordPress 发布文章前必须选择分类
* https://www.wpdaxue.com/choose-a-category-before-publish.html
*/
add_action(‘admin_footer-post.php’, ‘choose_a_category_before_publish’);
add_action(‘admin_footer-post-new.php’, ‘choose_a_category_before_publish’);
function choose_a_category_before_publish(){
global $post_type;
if($post_type==’post’){
echo "<script>
jQuery(function($){
$(‘#publish, #save-post’).click(function(e){
if($(‘#taxonomy-category input:checked’).length==0){
alert(‘抱歉,发布文章前,请选择一个分类’);
e.stopImmediatePropagation();
return false;
}else{
return true;
}
});
var publish_click_events = $(‘#publish’).data(‘events’).click;
if(publish_click_events){
if(publish_click_events.length>1){
publish_click_events.unshift(publish_click_events.pop());
}
}
if($(‘#save-post’).data(‘events’) != null){
var save_click_events = $(‘#save-post’).data(‘events’).click;
if(save_click_events){
if(save_click_events.length>1){
save_click_events.unshift(save_click_events.pop());
}
}
}
});
</script>";
}
}

以上代码默认只支持文章(post),见第 9 行的  if($post_type==’post’) 就是判读。

本人擅长Ai、Fw、Fl、Br、Ae、Pr、Id、Ps等软件的安装与卸载,精通CSS、JavaScript、PHP、ASP、C、C++、C#、Java、Ruby、Perl、Lisp、Python、Objective-C、ActionScript、Pascal等单词的拼写,熟悉Windows、Linux、OS X、Android、iOS、WP8等系统的开关机。

通过下面的方式来联系我们:

电邮:138762189@qq.com

联系QQ:点击这里给我发消息

官方站:www.tadke.com

※ ※ 联系请加我的企鹅号 ※※

※ ※技术支持请微信联系站长 ※※

Copyright © 2023 Tadke.com. 琼ICP备20000547号