BBP_Default::ajax_subscription()
AJAX handler to Subscribe/Unsubscribe a user from a topic
Description Description
Source Source
File: templates/default/bbpress-functions.php
public function ajax_subscription() {
// Bail if subscriptions are not active
if ( ! bbp_is_subscriptions_active() ) {
bbp_ajax_response( false, esc_html__( 'Subscriptions are no longer active.', 'bbpress' ), 300 );
}
// Bail if user is not logged in
if ( ! is_user_logged_in() ) {
bbp_ajax_response( false, esc_html__( 'Please login to subscribe.', 'bbpress' ), 301 );
}
// Get user and topic data
$user_id = bbp_get_current_user_id();
$id = ! empty( $_POST['id'] ) ? intval( $_POST['id'] ) : 0;
$type = ! empty( $_POST['type'] ) ? sanitize_key( $_POST['type'] ) : 'post';
// Bail if user cannot add favorites for this user
if ( ! current_user_can( 'edit_user', $user_id ) ) {
bbp_ajax_response( false, esc_html__( 'You do not have permission to do this.', 'bbpress' ), 302 );
}
// Get the object
if ( 'post' === $type ) {
$object = get_post( $id );
}
// Bail if topic cannot be found
if ( empty( $object ) ) {
bbp_ajax_response( false, esc_html__( 'Subscription failed.', 'bbpress' ), 303 );
}
// Bail if user did not take this action
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'toggle-subscription_' . $object->ID ) ) {
bbp_ajax_response( false, esc_html__( 'Are you sure you meant to do that?', 'bbpress' ), 304 );
}
// Take action
$status = bbp_is_user_subscribed( $user_id, $object->ID )
? bbp_remove_user_subscription( $user_id, $object->ID )
: bbp_add_user_subscription( $user_id, $object->ID );
// Bail if action failed
if ( empty( $status ) ) {
bbp_ajax_response( false, esc_html__( 'The request was unsuccessful. Please try again.', 'bbpress' ), 305 );
}
// Put subscription attributes in convenient array
$attrs = array(
'object_id' => $object->ID,
'object_type' => $type,
'user_id' => $user_id
);
// Add separator to topic if favorites is active
if ( ( 'post' === $type ) && ( bbp_get_topic_post_type() === get_post_type( $object ) ) && bbp_is_favorites_active() ) {
$attrs['before'] = ' | ';
}
// Action succeeded
bbp_ajax_response( true, bbp_get_user_subscribe_link( $attrs, $user_id, false ), 200 );
}
Changelog Changelog
| Version | Description |
|---|---|
| 2.1.0 | Introduced. |