Home » Wordpress » WordPress custom plugin shortcode wpdb unknown

WordPress custom plugin shortcode wpdb unknown

Posted by: admin November 30, 2017 Leave a comment

Questions:

I’m writing a custom plugin in wordpress and I’m using a shortcode for the first time.
Until now my shortcode works but now I want to execute a query in the function of that shortcode to get all the employees from a specific employee group id

   [employee_group_tag group_id=2]

This is the file that has my shortcode functionality:

    <?php
/*
Plugin Name: Employees
Plugin URI: xxx
Description: xxx
Version: 1.0
Author: xxx
Author URI: http://www.blabla.com
*/

   global $wpdb;

   function employee_shortcode_func( $atts ) {
    extract( shortcode_atts( array(
        'group_id' => '0',
    ), $atts ) );

    // Alle werknemers ophalen adhv van group_id
    $sql = 'SELECT * FROM wp_werknemers_employees WHERE employee_employee_group_id = ' . $group_id;
    $results = $wpdb->get_results($sql);

    return 'test';
}
add_shortcode( 'employee_group_tag', 'employee_shortcode_func' );

But when I run this it gets stuck on $wpdb->get_results($sql) because when I leave this out it displays my page correctly but when I want to fill it with employee details I only get the half of my page. So it “breaks”

I tried to do (which works in all my other files)

  require_once("../../../wp-config.php")

But it doesn’t work…

Is it possible that it’s not working because its in my “main” plugin file? Because in all my other files I can use wpdb when I use the require function…

any ideas?

Answers:

From the PHP Manual:

For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:

$a = 1;
include 'b.inc';

Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:

$a = 1; /* global scope */ 

function test()
{ 
    echo $a; /* reference to local scope variable */ 
} 

test();

The last example does not work, as $a is not defined inside the scope of the function.

Just like in your case, for it to work you have to use:

function employee_shortcode_func( $atts ) {
    global $wpdb;
    // etc
}