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’) 就是判讀。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *