• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

RESOLVED snippet within snippet - passing variable not possible ?

Messages
4
Likes
0
Points
1
#1
I have 2 snippets

----------
Snippet 'A' is an SQL query with following content:

function generalQuery {
global $wpdb;
$sql_query = "SELECT * from my_table1";
}
-----------
Snippet 'B' includes the content of Snippet A using 'do_shortcode' and writes out data from the database with following content:

do_shortcode('[wbcr_php_snippet id="id_of_A"]');
generalQuery();
$result = $wpdb->get_results($sql_query);
foreach($result as $row)
{
echo $row->db_item;
}

----------
This does not work, because I think the variable $sql_query from Snippet A is not passed to Snippet B.
---------
If I put all together in 1 snippet

$sql_query = "SELECT * from my_table1";
$result = $wpdb->get_results($sql_query);
foreach($result as $row)
{
echo $row->db_item;
}

It works.

While I want to use the same sql query in different codes, it would be nice to have it separated from the other snippets for reasons of redundance.

Thank you.
 

Temyk

Support team
Staff member
Messages
315
Likes
20
Points
18
#2
Hello! Try this code

Snippet A:
PHP:
function generalQuery() {
    return "SELECT * from my_table1";
}
global $sql_query;
$sql_query = generalQuery();
Snippet B:
PHP:
do_shortcode('[wbcr_php_snippet id="id_of_A"]');
global $sql_query;
global $wpdb;

$result = $wpdb->get_results($sql_query);
foreach($result as $row)
{
    echo $row->db_item;
}
The fact is that the PHP snippet code is executed in an isolated zone of visibility. This means that the functions declared in the snippet will not be available outside the snippet. But you can use global variables or constants