简体   繁体   中英

Wordpress use results of an external query in functions.php

I have a custom php page outside of wordpress, this page is connecting also to a external database, and get resultat form a sql query on a variable

i use require('../wp-blog-header.php') and require('../wp-load.php') to integrate with wordpress.

now i need to use this variable on the functions.php of my wordpress theme.

i do on my external page :

<head>
<connect to my database>
<my query>
<get resulte on $variable>
<require('../wp-blog-header.php')>
<require('../wp-load.php')>

but when i use $variable on my functions.php it do not work ?

You need to include wp-load.php alone. It will load wp-include (and wpdb), plugins and your theme (functions.php). To use the database directly you would do this:

global $wpdb;
$wpdb->get_results('select ...');

If you need to access variable declared in functions.php, it's straight forward:

say.php

<?php
include 'var.php';
print_r( $moo );
?>

var.php

<?php
$moo= 'cow';
?>

output of say.php

$ php say.php 
cow

Loading (include or require) functions.php after wp-load.php will result in redeclaration of the functions defined within functions.php (it will be loaded twice), causing PHP to crash.

Unless you are using wordpress features in your external query there is no need to include wordpress files.

Your external.php could look something like

function handy_prefix_my_processing_function() 
{

    //connect to database...
    //Do something with data...

    $result = $results

    //return the result
    return $result;

}

then in functions.php

function handy_prefix_get_my_variable() 
{
    //Load the external file and make its functions available
    include_once( 'external.php' );

    //Get my result
    $result = handy_prefix_my_processing_function();

    //Do something with the result....

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM