Problem:
How to count posts a certain user has created, and unhallow the user to create more then one of the given Posts?
Solution:
1. Create a CRED Form with which you let the user create your post.
2. Display the Link to that CRED somewhere on your site
3. Create a Custom PHP function to evaluate the amount of Posts created by the currently logged in user.
/** *Count posts of given type, so each user can create post only once */ function u_post_count() { $user_post_count = count( get_posts( array( 'post_type' => 'your_post_type_slug', 'author' => get_current_user_id(), //this will count the posts of the current logged in user ) ) ); return $user_post_count;//this returns a numerical value of Posts created by that user }
4. Register this function in Views > Settings > Compatibility > 3rd Party Functions
5. Use it in a wpv-conditional as elaborated here:
https://toolset.com/documentation/user-guides/conditional-html-output-in-views/ > Using Custom Functions Or Class Methods
6. Wrap the CRED Form / link with above conditional
Optional:
You can access also the Parent of the Current Post by querying the meta_key "_wpcf_belongs_your-parent-post-type-slug_id" and meta_value "Post ID" (the ID of the parent Post)
So your code can look like this:
/** *Count posts of given type, so each user can create post only once */ function u_post_count() { $post_id = $post->ID; //get current post ID $user_post_count = count( get_posts( array( 'post_type' => 'your_post_type_slug', //child post type 'meta_key' => '_wpcf_belongs_your-parent-post-type-slug_id', 'meta_value' => $post_id, 'author' => get_current_user_id(), //this will count the posts of the current logged in user ) ) ); return $user_post_count;//this returns a numerical value of Posts created by that user }
Relevant Documentation:
https://codex.wordpress.org/Template_Tags/get_posts
https://codex.wordpress.org/Template_Tags/get_posts
https://codex.wordpress.org/Function_Reference/get_current_user_id
http://php.net/manual/en/function.count.php
https://toolset.com/documentation/user-guides/creating-cred-forms/
This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.
Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
- | - | 14:00 – 20:00 | 14:00 – 20:00 | 14:00 – 20:00 | 14:00 – 20:00 | 14:00 – 20:00 |
- | - | - | - | - | - | - |
Supporter timezone: Asia/Ho_Chi_Minh (GMT+07:00)
This topic contains 7 replies, has 2 voices.
Last updated by justinB-5 8 years, 1 month ago.
Assisted by: Beda.