【问题标题】:Custom query results generate code自定义查询结果生成代码
【发布时间】:2013-04-29 05:11:48
【问题描述】:

简单的问题。我有以下自定义查询。如何让它通过“echo”生成数组的 html 列表?

$q_result = $wpdb->get_col("SELECT DISTINCT {$wpdb->terms}.name FROM {$wpdb->terms}
        INNER JOIN {$wpdb->term_taxonomy} ON {$wpdb->term_taxonomy}.term_id = {$wpdb->terms}.term_id
        INNER JOIN {$wpdb->term_relationships} ON {$wpdb->term_taxonomy}.term_taxonomy_id = {$wpdb->term_relationships}.term_taxonomy_id
        WHERE {$wpdb->term_taxonomy}.taxonomy = 'series' AND {$wpdb->term_relationships}.object_id IN (
        SELECT object_id FROM {$wpdb->term_relationships}
        INNER JOIN {$wpdb->term_taxonomy} ON {$wpdb->term_taxonomy}.term_taxonomy_id = {$wpdb->term_relationships}.term_taxonomy_id
        WHERE {$wpdb->term_taxonomy}.taxonomy = 'media_type' AND {$wpdb->term_taxonomy}.term_id = '16'
        ORDER BY {$wpdb->terms}.term_order DESC
        ) ORDER BY {$wpdb->terms}.term_order ASC"); 

【问题讨论】:

    标签: html sql wordpress frontend


    【解决方案1】:

    您可以使用 foreach 遍历数组 -

    foreach( $q_result as $result ){
       echo "<a href='/series/".$result."/>".$result."</a>";
    }
    

    如果您希望它也显示 HTML,则必须回显正确的 HTML 标记。以上内容适用于该术语的链接 - 格式为 TAXONOMY/TERM_SLUG 但是您只返回名称,您需要使用 get_results() 获取名称和 slug 才能正确执行。

    使用表别名重新格式化示例,返回术语和 slug:

    $sql = <<<SQL
        SELECT DISTINCT t.name, t.slug 
        FROM {$wpdb->terms} t
        INNER JOIN {$wpdb->term_taxonomy} tt 
            ON tt.term_id = t.term_id and tt.taxonomy = 'series'
        INNER JOIN {$wpdb->term_relationships} tr 
            ON tt.term_taxonomy_id = tr.term_taxonomy_id
        WHERE tr.object_id IN (
            SELECT object_id 
            FROM {$wpdb->term_relationships} tr2
            INNER JOIN {$wpdb->term_taxonomy} tt2 
                ON tt2.term_taxonomy_id = tr2.term_taxonomy_id AND tt2.taxonomy = 'media_type' AND tt2.term_id = '16'
            ORDER BY {$wpdb->terms}.term_order DESC
        ) 
        ORDER BY {$wpdb->terms}.term_order ASC
    SQL;
    
    $terms = $wpdb->get_results( $sql );
    for ( $terms as $term ){
        echo "<a href='/series/{$term->slug}/'>{$term->name}</a><br/>";
    }
    

    【讨论】:

    • 谢谢!我将如何回显固定链接?
    • 假设该术语的永久链接...请参阅我的编辑,但它不会真正起作用,因为您得到的是名称而不是 slug。
    • 我需要做什么才能同时获取名称和 slug?
    • 我添加了一个示例,未经测试,但它应该是一个开始。回来为我工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 2015-11-24
    • 1970-01-01
    相关资源
    最近更新 更多