Adam Fletcher Adam Fletcher - 4 months ago 7
PHP Question

Wordpress custom plugin to call total rows from database table and present in site using a shortcode

I have a wordpress site that includes a custom table with data for people who've pledged to support a cause. I need to create a plugin that will allow me to drop a shortcode onto any page to present the total number of active pledgers.

The database query is simple:

global $wpdb;
$pledgers = $wpdb->get_results("SELECT `business_name` FROM wp_x_pledgers WHERE business_name != '' AND active = '1' ORDER BY business_name;");
$count_pledgers = count($pledgers);


I can create a simple plugin like this:

<?php
/*
Plugin Name: Pledge Counter Plugin
Plugin URI: http://www.example.org/
Description: A plugin that tallies up active pledgers and presents the figure onscreen via a shortcode
Version: 1.0
Author: John Doe
Author URI: http://www.example.org/
License: GPL2
*/
?>


I am now struggling how to include the ability to output the $count_pledgers result via a shortcode e.g. [pledgers_result].

Answer

Well, you'll need to add an actual shortcode. It's pretty simple to do. Documenation here: https://codex.wordpress.org/Shortcode_API

Example:

<?php
/*
Plugin Name: Pledge Counter Plugin
Plugin URI: http://www.example.org/
Description: A plugin that tallies up active pledgers and presents the figure onscreen via a shortcode
Version: 1.0
Author: John Doe
Author URI: http://www.example.org/
License: GPL2
*/

// Shortcode render function
function sc_pledgers_result($atts) {
    global $wpdb;
    $pledgers = $wpdb->get_results("SELECT `business_name` FROM wp_x_pledgers WHERE business_name != '' AND active = '1' ORDER BY business_name;");
    $count_pledgers = count($pledgers);
    return "Pledgers count: $count_pledgers";
}

// Add shortcode to WordPress
add_shortcode("pledgers_result", "sc_pledgers_result");

As long as the plugin is activated the [pledgers_result] shortcode will output the return value of the sc_pledgers_result() function.

Comments