【问题标题】:Wordpress use results of an external query in functions.phpWordpress 在functions.php 中使用外部查询的结果
【发布时间】:2014-03-16 19:56:01
【问题描述】:

我在 wordpress 之外有一个自定义 php 页面,该页面还连接到外部数据库,并从变量的 sql 查询中获取结果

我使用require('../wp-blog-header.php')require('../wp-load.php') 与wordpress 集成。

现在我需要在我的 wordpress 主题的 functions.php 上使用这个变量。

我在我的外部页面上做:

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

但是当我在 functions.php 上使用 $variable 时它不起作用?

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    您需要单独包含 wp-load.php。它将加载 wp-include(和 wpdb)、插件和您的主题(functions.php)。要直接使用数据库,您可以这样做:

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

    如果你需要访问functions.php中声明的变量,很简单:

    say.php

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

    var.php

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

    say.php 的输出

    $ php say.php 
    cow
    

    在 wp-load.php 之后加载(include 或 require)functions.php 会导致 functions.php 中定义的函数重新声明(会被加载两次),导致 PHP 崩溃。

    【讨论】:

    • 谢谢,但我不需要在functions.php中声明的变量,我的变量和我的数据库是wordpress的外部。所以我需要在functions.php上使用一个外部变量,这个变量是查询外部数据库而不是wordpress数据库的结果
    • 我修改了您问题的标题以反映这一点。
    【解决方案2】:

    除非您在外部查询中使用 wordpress 功能,否则无需包含 wordpress 文件。

    您的 external.php 可能类似于

    function handy_prefix_my_processing_function() 
    {
    
        //connect to database...
        //Do something with data...
    
        $result = $results
    
        //return the result
        return $result;
    
    }
    

    然后在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....
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多