3

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?

2
  • 6
    global wpdb belongs inside the function. Commented Jul 8, 2013 at 12:20
  • Oh my god... never thought of that, you saved my day! :) Commented Jul 8, 2013 at 12:24

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.