In the back end, it's a matter of using the hook save_post
, as topic
is a Custom Post Type.
If no Tags are filled, saving is cancelled and a link is presented so the user can go back to the editing screen.
But, there's one caveat: the title is not preserved, if it is a new topic it comes back blank and if it is an existing topic any changes are lost. The content and topic attributes are preserved.
I'm not quite sure there is a solution for this...
add_action( 'save_post', 'save_post_wpse_82956', 10, 2 );
/**
* Require Tags for new bbPress Topic
*/
function save_post_wpse_82956( $post_id, $post_object )
{
// Auto save or Ajax
if (
( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
|| ( defined('DOING_AJAX') && DOING_AJAX ) )
return;
// Correct post_type
if ( 'topic' != $post_object->post_type )
return;
// First instance of the post (right after clicking "New Topic")
if( 'auto-draft' == $post_object->post_status )
return;
if ( empty( $_POST['tax_input']['topic-tag'] ) )
wp_die( '<a href="javascript:history.go(-1)">' . __( '« « Please, add tags to the topic' ) . '</a>' );
}
And in the front end, a couple of bbPress action hooks and a simple check are enough (when posting multiple replies, a Javascript workaround is necessary, check comments):
add_action( 'bbp_new_topic_pre_extras', 'check_front_end_tags_wpse_82956' );
add_action( 'bbp_new_reply_pre_extras', 'check_front_end_tags_wpse_82956' );
function check_front_end_tags_wpse_82956()
{
if( empty( $_POST['bbp_topic_tags'] ) )
{
// WORKAROUND FOR LINKS WITH HASH TAG, e.g., topic/lorem-ipsum#post-91
// Necessary when posting multiple replies that generate hashed links
// OTHERWISE A SIMPLE href="javascript:history.go(-1) WOULD WORK
?><script>
function goBack() {
if (window.history && history.pushState) {
history.replaceState("", "", "?no-tags=true);
history.go(-1);
}
}
</script><?php
wp_die( '<a href="javascript:goBack()">' . __( '« « Please, add tags to the topic' ) . '</a>' );
}
}