Last active
December 11, 2021 18:32
-
-
Save gabrielmerovingi/9597303 to your computer and use it in GitHub Desktop.
A simple example of how to adjust the myCRED Lottery add-on to add an option to set a maximum lottery entries before the lottery is closed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Step 1 - Add new ticket preference | |
* In this example we will insert this under "Participation" section | |
* of the lottery edit screen. | |
* @version 1.0 | |
*/ | |
add_action( 'mycred_edit_lotto_participation', 'add_max_lottery_entries_settings' ); | |
function add_max_lottery_entries_settings( $lottery ) { | |
$tickets = get_post_meta( $lottery->id, '_tickets', true ); ?> | |
<h2>Tickets</h2> | |
<table class="table table-bordered" style="margin-bottom: 0;"> | |
<tr> | |
<th style="width: 25%;"><label for="mycred-lottery-tickets">Max</label></th> | |
<td><input type="text" name="mycred_lottery_tickets" id="mycred-lottery-tickets" value="<?php echo $tickets; ?>" class="short" /><br /><span class="description">Max number of tickets available before this lottery closes. Leave empty to disable.</span></td> | |
</tr> | |
</table> | |
<?php | |
} | |
/** | |
* Step 2 - Save new ticket preference | |
* @version 1.0 | |
*/ | |
add_action( 'save_post', 'save_max_lottery_entries_settings', 1 ); | |
function save_max_lottery_entries_settings( $post_id ) { | |
if ( ! current_user_can( 'edit_posts' ) || ! isset( $_POST['mycred_lottery_tickets'] ) ) return; | |
$max = sanitize_text_field( $_POST['mycred_lottery_tickets'] ); | |
update_post_meta( $post_id, '_tickets', absint( $max ) ); | |
} | |
/** | |
* Step 3 - Hook into myCRED | |
* Hook in and close the lottery when entires reach this | |
* new max. | |
* @version 1.0 | |
*/ | |
add_filter( 'mycred_lotto_after_play', 'limit_max_lottery_entries', 10, 2 ); | |
function limit_max_lottery_entries( $reply, $lottery ) { | |
// If the entry failed, leave now | |
if ( $reply['status'] != 'done' ) return $reply; | |
// Count lottery entries | |
$count = $lottery->get_total_entries(); | |
// Limit | |
$limit = get_post_meta( $lottery->id, '_tickets', true ); | |
// Do not use if not set | |
if ( $limit == '' ) return $reply; | |
// If we are over the limit, close the lottery preventing more entries. | |
if ( $count >= $limit ) | |
mycred_lottery_do_close( $lottery->id ); | |
// Always return something or we brake everything | |
return $reply; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment