Skip to content

Instantly share code, notes, and snippets.

@ImmortalN
Created April 22, 2025 11:23
Show Gist options
  • Save ImmortalN/61c83b7e0393f59dd42c98ee227606f9 to your computer and use it in GitHub Desktop.
Save ImmortalN/61c83b7e0393f59dd42c98ee227606f9 to your computer and use it in GitHub Desktop.
Limit of posts for current user
<?php
add_shortcode( 'user_posts_limit', function( $atts ) {
// Parse shortcode attributes
$atts = shortcode_atts( array(
'post_type' => 'all',
), $atts );
// Check if JetEngine and Profile Builder module are active
if ( ! class_exists( '\Jet_Engine\Modules\Profile_Builder\Module' ) ) {
return 'JetEngine Profile Builder module is not active.';
}
// Get current user
$user_id = get_current_user_id();
if ( ! $user_id ) {
return 'Please log in to see your post limit.';
}
// Get Restrictions instance
$restrictions = \Jet_Engine\Modules\Profile_Builder\Module::instance()->get_restrictions_handler();
// Check restrictions settings
$settings = \Jet_Engine\Modules\Profile_Builder\Module::instance()->settings->get( 'posts_restrictions' );
if ( empty( $settings ) ) {
return 'No post restrictions set.';
}
// Get user roles
$user = wp_get_current_user();
$roles = ! is_user_logged_in() ? array( 'jet-engine-guest' ) : array_values( $user->roles );
// Find limit for user role and post type
$limit = 0;
foreach ( $settings as $restriction ) {
if ( empty( $restriction['role'] ) ) {
continue;
}
$intersect = array_intersect( $roles, $restriction['role'] );
if ( ! empty( $intersect ) ) {
$_post_type = ! empty( $restriction['post_type'] ) ? $restriction['post_type'] : 'all';
if ( is_array( $_post_type ) && in_array( $atts['post_type'], $_post_type ) || $_post_type === $atts['post_type'] || $_post_type === 'all' ) {
$limit = ! empty( $restriction['limit'] ) ? absint( $restriction['limit'] ) : 0;
break;
}
}
}
// Get post count
if ( $atts['post_type'] === 'all' ) {
// For 'all', use a custom query to count all post types
global $wpdb;
$posts_table = $wpdb->posts;
$query = $wpdb->prepare(
"SELECT COUNT(*) FROM $posts_table WHERE post_author = %d AND post_status IN ( 'publish', 'draft', 'pending', 'trash', 'future', 'private' )",
$user_id
);
$posts_count = absint( $wpdb->get_var( $query ) );
} else {
// For specific post type, use the original method
$posts_count = $restrictions->get_user_posts( $user_id, $atts['post_type'] );
}
// Generate output
if ( $limit == 0 ) {
return 'No post limit set for your role.';
}
return sprintf(
'You have created %d out of %d allowed posts.',
$posts_count,
$limit
);
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment