【问题标题】:Returning Results From A Function从函数返回结果
【发布时间】:2012-12-19 12:03:01
【问题描述】:

我在我的主题 functions.php 文件中的 wordpress 中创建了以下函数。我想在我的主题模板中调用此函数,并在我的主题模板中回显 foreach 部分的部分。我该怎么做呢?我想我必须从函数中返回一些东西,但我不知道如何设置它。非常感谢您的帮助。

    function geography_navigation($type, $field1, $field2, $field3, $field4, $field5) {

    global $wpdb;

    $results = $wpdb->get_results("SELECT DISTINCT wp_eva_geography.$field1, wp_eva_geography.$field2 
    FROM wp_eva_geography
    WHERE wp_eva_geography.$field3='$type' AND wp_eva_geography.$field4='$geo_no_dash';");

    echo "<ul>";

    foreach($results as $geography){

        echo "<li> <a href='/$type/$field5/{$geography->$field2}/'>{$geography->$field1}</a></li>";

    }
    echo "</ul>";


    }

【问题讨论】:

    标签: php wordpress function for-loop echo


    【解决方案1】:

    将输出设置为变量并像这样返回:

    function geography_navigation($type, $field1, $field2, $field3, $field4, $field5) 
    {
        global $wpdb;
    
        $results = $wpdb->get_results("SELECT DISTINCT wp_eva_geography.$field1, wp_eva_geography.$field2
        FROM wp_eva_geography
        WHERE wp_eva_geography.$field3='$type' AND wp_eva_geography.$field4='$geo_no_dash';");
    
        $output = '<ul>';
    
        foreach($results as $geography)
        {
            $output .= "<li> <a href='/$type/$field5/{$geography->$field2}/'>{$geography->$field1}</a></li>";
        }
    
        return $output . '</ul>';
    }
    

    请注意,我已经对此进行了注释测试,但相信它应该可以工作...让我知道!

    【讨论】:

    • 很好,但是你不知道这个字段是从哪里来的。请将$wpdb-&gt;prepare() 添加到答案中,这样这段代码就不会作为 SQL 注入的向量在互联网中徘徊。
    • 哦,好像也有网址进来了,like_escape 可能有用。
    • @brasofilo ...像这样吗? $wpdb-&gt;get_results($wpdb-&gt;prepare("SELECT DISTINCT wp_eva_geography.$field1, wp_eva_geography.$field2 FROM wp_eva_geography WHERE wp_eva_geography.$field3='$type' AND wp_eva_geography.$field4='$geo_no_dash';"));
    • 喜欢here,在函数get_attachment中。
    • @cryptic 我使用了您的示例,但在我的页面模板上没有得到任何结果。基本上我可以从 page.php 调用这样的函数 geography_navigation("Dealers", "county_short", "county_slug", "type", "state_name", "3"); 来构建我的导航.但是当我进行更改时,它解决了我的 page.php 上没有显示任何链接。我需要在 page.php 上做些什么吗?
    猜你喜欢
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 2013-01-05
    • 2018-02-21
    相关资源
    最近更新 更多