Wishlist


Source

File: classes/Wishlist.php

class Wishlist {

	public function __construct() {
		add_filter( 'dozent_course_lead_meta_items', [ $this, 'add_wishlist_meta_item' ], 10, 2 );

		add_filter( 'wp_ajax_dozent_wishlist', [ $this, 'dozent_wishlist' ] );
		add_filter( 'wp_ajax_nopriv_dozent_wishlist', [ $this, 'dozent_wishlist' ] );
	}

	public function add_wishlist_meta_item( $items, $course_id ) {

		$btn_text = sprintf( __( ' %s Add to Wishlist', 'dozent' ), '<i class="dicon-heart-o"></i>' );

		if ( is_user_logged_in() ) {
			$user_id = get_current_user_id();

			$in_wishlist = $this->has_in_wishlist( $course_id, $user_id );
			if ( $in_wishlist ) {
				$btn_text = sprintf( __( ' %s Remove from Wishlist', 'dozent' ), '<i class="dicon-heart"></i>' );
			}
		}

		$output
			= "<a href='javascript:;' class='dozent-wishlist-toggle-btn' data-course-id='{$course_id}' > {$btn_text} </a>";

		$items['wishlist'] = $output;

		return $items;
	}


	public function dozent_wishlist() {
		$course_id = (int) dozent_input_text( 'course_id' );
		if ( ! is_user_logged_in() ) {
			$redirect_url = wp_login_url( get_the_permalink( $course_id ) );

			wp_send_json_error( [ 'status' => 'login_require', 'redirect_to' => $redirect_url ] );
		}

		$user_id = get_current_user_id();

		$is_added = $this->has_in_wishlist( $course_id, $user_id );

		$btn_text = sprintf( __( ' %s Removed from Wishlist', 'dozent' ), '<i class="dicon-heart"></i>' );

		if ( $is_added ) {
			$btn_text = sprintf( __( ' %s Add to Wishlist', 'dozent' ), '<i class="dicon-heart-o"></i>' );
			delete_user_meta( $user_id, '_dozent_course_wishlist', $course_id );

			wp_send_json_success( [
				'status'   => 'removed',
				'msg'      => __( 'Course removed from wish list', 'dozent' ),
				'btn_text' => $btn_text,
			] );
		} else {
			add_user_meta( $user_id, '_dozent_course_wishlist', $course_id );
			wp_send_json_success( [
				'status'   => 'added',
				'msg'      => __( 'Course added to wish list', 'dozent' ),
				'btn_text' => $btn_text,
			] );
		}

	}

	public function has_in_wishlist( $course_id = 0, $user_id = 0 ) {
		if ( ! $course_id || ! $user_id ) {
			return false;
		}

		$courses_in_wishlist = (array) get_user_meta( $user_id, '_dozent_course_wishlist' );

		return in_array( $course_id, $courses_in_wishlist );
	}

}

Methods