Limit the Number of User Can Post Each Day Without Using a Plugin – WordPress

Advertisement

In continuation on my previous post that count user post with custom post type, in this post I’d like to share another tutorial that limit the number of user can post each day, for now this is only available on shortcode, and unfortunately does the functionality too, this method can only use in form shortcode, but, so far most plugin that allow user to add post via front-end support shortcode, so it’s the best way to start with.

Without further ado lets get started.

Syntax


[rs_limit_post] FORM SHORTCODE [/rs_limit_post]

Parameters


{
'limit'		=> 5,		// default value 5
'post_type'	=> 'post'	// default value 'post'
}

Code


/**
 * Limit the Number of User Can Post Each Day
 *
 * @author	Ryan Sutana
 *
 */

//[rs_limit_post]
function rs_limit_post_shortcode( $atts, $content = null )
{
	ob_start();

	extract( shortcode_atts( array(
		'limit' 		=> 5,
		'post_type'	=> 'post'
	), $atts ) );

	$html = '';

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

		// get current user invoice listings
		$args = array(
			'post_type'	=> $post_type,
			'author' 	=> $user_ID
		);

		// The Query
		$the_query = new WP_Query( $args );
		$user_post_count = $the_query->found_posts;

		// set current timestamp option
		$current_timestamp_time = strtotime("now");
		add_option( 'tomorrow_timestamp_time', strtotime("+1 day") );

		// get timestamp option
		$tomorrow_timestamp_time = get_option( 'tomorrow_timestamp_time' );

		// 5 < = 6
		if( (int)$limit <= $user_post_count ) {
			// if today's time is same or greater than on the save yesterday's time then allow user to add new post
			// e.g. current time is Mar 29, 2014 03:00:00 PM, yesterday's save time is Mar 29, 2014 02:00:00 PM
			if( $current_timestamp_time >= $tomorrow_timestamp_time ) {
				// update tomorrow_timestamp_time to tomorrow's date again
				update_option( 'tomorrow_timestamp_time', strtotime("+1 day") );

				echo do_shortcode( $content );
			}
			else {
				_e( 'You have reach the limit of post you can add each day.', 'rys' );
			}
		}
		else {
			echo do_shortcode( $content );
		}

	}
	else {
		_e( 'Please login to add a new post.', 'rys' );
	}

	// Stop output buffering and capture debug HTML
	$html = ob_get_contents();
	ob_end_clean();

	return $html;
}
add_shortcode( 'rs_limit_post', 'rs_limit_post_shortcode' );

Happy Coding ^_^

Advertisement