Wordpress 自定义插件从数据库 table 调用总行数并使用简码显示在站点中

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

我有一个 wordpress 网站,其中包含一个自定义 table,其中包含承诺支持某项事业的人们的数据。我需要创建一个插件,允许我将简码放到任何页面上以显示活跃认捐者的总数。

数据库查询很简单:

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);

我可以像这样创建一个简单的插件:

<?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
*/
?>

我现在正在努力如何包括通过短代码输出 $count_pledgers 结果的能力,例如[pledgers_result].

好吧,您需要添加一个实际的短代码。这很简单。此处的文档:https://codex.wordpress.org/Shortcode_API

示例:

<?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");

只要激活插件,[pledgers_result] 简码就会输出 sc_pledgers_result() 函数的 return 值。