Display % correct of quiz score from all entries

By: stephanie Nye | Asked: 02/16/2023
ForumsCategory: General questionsDisplay % correct of quiz score from all entries
stephanie Nye asked 2 years ago
Hello, I have a daily quiz that has one multiple choice question. I'm using the scored quiz action. I'm looking to display the % correct from the previous days quiz.
Is there a way to get the percentage of all entries that got the answer correct?

I'm already using a graph that shows all of the entries, but I'd like to show just how many got a question right. Thanks in advance for any suggestions.  
1 Answers
Walter JonesWalter Jones answered 2 years ago
I did something similar for a client but they wanted a shortcode to enable to put the percentage anywhere on their page.   Keep in mind this displays the percentage correct for all users, if you need it show for individual users you will need to modify the code reflect current_user.  The code is below:
function all_users_previous_day_percentage_shortcode() {
    // Retrieve the entries for all users from the previous day
    $args = array(
        'form_id' => 'YOUR_FORM_ID', // Replace with the ID of your form
        'date_query' => array(
            array(
                'after' => '1 day ago',
                'before' => 'today',
            ),
        ),
    );

    $entries = FrmEntry::get( $args );

    // Calculate the percentage correct for all entries from the previous day
    $total_questions = 0;
    $total_correct = 0;

    foreach ( $entries as $entry ) {
        // Get the quiz score field value for this entry
        $quiz_score = FrmProEntriesController::get_field_value_shortcode( array(
            'field_id' => 'YOUR_SCORE_FIELD_ID', // Replace with the ID of your quiz score field
            'entry' => $entry,
        ) );

        // Get the total number of questions and number of correct answers
        $quiz_data = json_decode( $quiz_score, true );
        $total_questions += $quiz_data['total'];
        $total_correct += $quiz_data['correct'];
    }

    $percent_correct = $total_questions > 0 ? round( $total_correct / $total_questions * 100 ) : 0;

    // Output the percentage correct
    return 'Percentage correct for all users from the previous day: ' . $percent_correct . '%';
}
add_shortcode( 'all_users_previous_day_percentage', 'all_users_previous_day_percentage_shortcode' );
Use the shortcode [all_users_previous_day_percentage] to show the percentage in a view or on a page.  

The code will need to be placed in a code snippet or functions.php in your install. Hope this helps you. 
stephanie Nye replied 2 years ago

Thanks, I'll give this a try.

Making the Best WordPress Plugin even better - Together

Take on bigger projects with confidence knowing you have access to an entire community of Formidable Experts and Professionals who have your back when the going gets tough. You got this!
Join the community
crossarrow-right