digital makreting

Poll and Survey Plugin for WordPress

A poll and survey plugin allows website owners to easily create interactive polls and surveys that engage visitors and collect valuable feedback. With the help of this plugin, you can display customizable polls and surveys on your pages or posts, enabling visitors to participate and submit their opinions directly on your site.

Key Features:

  • Create polls with multiple-choice questions
  • Display results in real-time
  • Set expiration dates for polls
  • Customizable poll styles to match the site’s design
  • Allow single or multiple votes per user
  • View and export poll results

In this article, we’ll walk through how to create a simple poll and survey plugin for WordPress, including the code examples and steps to set it up.

Step-by-Step Guide to Building the Plugin

Step 1: Create Plugin Files

First, create a new folder in the wp-content/plugins/ directory named wp-poll-plugin. Inside this folder, create the main plugin file called wp-poll-plugin.php.

<?php
/**
 * Plugin Name: WP Poll Plugin
 * Description: A plugin to create and display interactive polls and surveys on your WordPress site.
 * Version: 1.0
 * Author: Your Name
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

Step 2: Create Admin Menu for Polls

We need an admin menu where the site admin can add, edit, and delete polls.

// Add a custom menu for Poll Management
function wp_poll_add_admin_menu() {
    add_menu_page(
        'Poll Management',
        'Polls',
        'manage_options',
        'wp-poll-management',
        'wp_poll_admin_page',
        'dashicons-chart-bar'
    );
}
add_action('admin_menu', 'wp_poll_add_admin_menu');

// Admin page callback function
function wp_poll_admin_page() {
    ?>
    <div class="wrap">
        <h1>Create a New Poll</h1>
        <form method="post" action="options.php">
            <?php
            settings_fields('poll_options_group');
            do_settings_sections('wp-poll-management');
            submit_button();
            ?>
        </form>
    </div>
    <?php
}

Step 3: Add Poll Settings

We’ll use the WordPress Settings API to create and store poll questions and choices. This will allow users to input their questions and options for each poll.

// Register settings for polls
function wp_poll_register_settings() {
    register_setting('poll_options_group', 'wp_poll_data', 'wp_poll_sanitize_data');

    add_settings_section('poll_section', 'Polls', 'wp_poll_section_callback', 'wp-poll-management');
    add_settings_field('poll_question', 'Poll Question', 'wp_poll_question_callback', 'wp-poll-management', 'poll_section');
    add_settings_field('poll_choices', 'Poll Choices', 'wp_poll_choices_callback', 'wp-poll-management', 'poll_section');
}
add_action('admin_init', 'wp_poll_register_settings');

// Sanitize poll data
function wp_poll_sanitize_data($input) {
    $output = [];
    foreach ($input as $key => $value) {
        $output[$key] = sanitize_text_field($value);
    }
    return $output;
}

// Section callback
function wp_poll_section_callback() {
    echo 'Create a new poll by filling out the following fields.';
}

// Poll question callback
function wp_poll_question_callback() {
    $poll_data = get_option('wp_poll_data');
    ?>
    <input type="text" name="wp_poll_data[question]" value="<?php echo esc_attr($poll_data['question'] ?? ''); ?>" class="regular-text">
    <?php
}

// Poll choices callback
function wp_poll_choices_callback() {
    $poll_data = get_option('wp_poll_data');
    ?>
    <textarea name="wp_poll_data[choices]" rows="5" cols="50" class="large-text"><?php echo esc_textarea($poll_data['choices'] ?? ''); ?></textarea>
    <p>Enter poll choices, separated by a new line.</p>
    <?php
}

Step 4: Display Poll on the Frontend

We’ll create a function to display the poll on the frontend and handle user voting. We’ll also add a shortcode for easily embedding polls in posts or pages.

// Display poll on frontend
function wp_poll_display_poll() {
    $poll_data = get_option('wp_poll_data');
    if ($poll_data) {
        echo '<form method="post" action="">';
        echo '<p>' . esc_html($poll_data['question']) . '</p>';
        $choices = explode("\n", $poll_data['choices']);
        foreach ($choices as $choice) {
            echo '<label><input type="radio" name="wp_poll_choice" value="' . esc_attr(trim($choice)) . '"> ' . esc_html(trim($choice)) . '</label><br>';
        }
        echo '<input type="submit" name="wp_poll_vote" value="Vote">';
        echo '</form>';
    }
}
add_shortcode('poll', 'wp_poll_display_poll');

// Handle poll votes
function wp_poll_handle_votes() {
    if (isset($_POST['wp_poll_vote']) && !empty($_POST['wp_poll_choice'])) {
        $selected_choice = sanitize_text_field($_POST['wp_poll_choice']);
        $votes = get_option('wp_poll_votes', []);
        if (isset($votes[$selected_choice])) {
            $votes[$selected_choice]++;
        } else {
            $votes[$selected_choice] = 1;
        }
        update_option('wp_poll_votes', $votes);
    }
}
add_action('init', 'wp_poll_handle_votes');

Step 5: Display Poll Results

Once the users have voted, they can see the results in real-time. We will create a function to display the poll results after voting.

// Display poll results
function wp_poll_display_results() {
    $votes = get_option('wp_poll_votes', []);
    if ($votes) {
        $total_votes = array_sum($votes);
        echo '<h3>Poll Results</h3>';
        foreach ($votes as $choice => $count) {
            $percentage = ($count / $total_votes) * 100;
            echo '<p>' . esc_html($choice) . ': ' . round($percentage, 2) . '% (' . $count . ' votes)</p>';
        }
    }
}
add_shortcode('poll_results', 'wp_poll_display_results');

Now, users can vote in the poll and immediately see the results after submitting their vote. You can use the [poll] shortcode to display the poll and [poll_results] to show the results.

Step 6: Style the Poll

To improve the poll’s appearance, add custom styles. You can either enqueue a CSS file or add styles directly to your theme’s style.css.

.poll-form {
    margin: 20px 0;
    padding: 10px;
    border: 1px solid #ddd;
    background-color: #f9f9f9;
}

.poll-form p {
    font-size: 18px;
    font-weight: bold;
}

.poll-form label {
    display: block;
    margin: 5px 0;
}

Step 7: Activate and Use the Plugin

Activate the plugin from the WordPress dashboard. After activation, create a poll by navigating to the Polls menu, and use the [poll] and [poll_results] shortcodes to display the poll and its results on any page or post.

Conclusion

This poll and survey plugin is an excellent way to engage your audience and gather useful feedback. The ability to customize questions, collect votes, and display real-time results makes it a powerful tool for site owners looking to interact with their users. You can further extend the functionality by adding features like multiple-choice questions or integrating with other analytics plugins.

Leave a Reply

Your email address will not be published. Required fields are marked *