Wordpress自定义插件,用于调用数据库表中的总行数,并使用短代码显示在站点中

时间:2016-07-07 01:35:19

标签: php mysql wordpress shortcode

我有一个wordpress网站,其中包含一个自定义表格,其中包含已承诺支持某项事业的人员的数据。我需要创建一个插件,允许我将短代码放到任何页面上,以显示活动的pledgers总数。

数据库查询很简单:

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]。

1 个答案:

答案 0 :(得分:1)

好吧,你需要添加一个实际的短代码。这很简单。这里的文件记录: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()函数的返回值。