在wordpress中搜索自定义表

时间:2016-09-13 14:22:51

标签: php mysql wordpress

我目前正在为客户建立一个网站,他们想要一个搜索功能来搜索他们提供的所有产品。

我在数据库中创建了一个名为sc_products的新表,然后在wordpress模板页面中尝试了以下代码,但我似乎无法到达任何地方。如果有人知道如何让这项工作变得非常棒!

<?php
/* 

Template Name: myTemp

*/

function search_it() {
if ( is_search() && isset($_GET['s'])) {

    global $wpdb;

    $address_table = $wpdb->prefix . "sc_products";
    $myrows = $wpdb->get_results( 'SELECT product FROM ' . $sc_products );
    foreach ( $myrows as $single_row ) {
         global $single_row;
    }
    $product = $single_row->product;
}
    return $product;
}
$city = search_it();
echo $city;

get_search_form();

?>    

1 个答案:

答案 0 :(得分:0)

这里有几件事情,让我们看看我们是否可以解决这些问题。

这是您修改过的函数,它应该执行搜索,并在整个过程中提供注释以帮助解释正在发生的事情。

注意:
1.您声明$address_table,然后使用$sc_products。这不正确,因为$sc_products未定义 2.此答案基于您在评论中提供的列名称 - 如果它们不完全匹配,则需要更新它们,包括匹配大小写。如果不是Application,而是application,则需要进行更改。

function search_it() {
// If this is a search, and the search variable is set
    if ( is_search() && isset( $_GET['s'] ) ) {
        // Global in $wpdb so we can run a query
        global $wpdb;
        // Build the table name - glue the table prefix onto the front of the table name of "sc_products"
        $address_table = $wpdb->prefix . "sc_products";
        // Get the search term into a variable for convenience
        $search = $_GET['s'];
        // To use "LIKE" with the wildcards (%), we have to do some funny business:
        $search = "%{$search}%";
        // Build the where clause using $wpdb->prepare to prevent SQL injection attacks
        // Searching ALL THREE of our columns: Product, Application, Sector 
        $where = $wpdb->prepare( 'WHERE Product LIKE %s OR Application LIKE %s OR Sector LIKE %s', $search, $search, $search );
        // Execute the query with our WHERE clause
        // NOTE: Your code originally used "$sc_products", but that variable was not defined - so have replaced to the proper $address_table here.
        $results = $wpdb->get_results( "SELECT product FROM {$address_table} {$where}" );
        // return the results.  No need to put into an array, it's already an array
        return $product;
    }

    // For consistency, return an empty array if not a search / no search term
    return array();
}

// USAGE:
// Run the query
$cities = search_it();
// You can't echo an array!
// echo $city;
// var_dump to see the whole array
var_dump( $cities );

// More useful USAGE:
$cities = search_it();
// If there's any results
if ( ! empty( $cities ) ) {
    // Output a title
    echo '<h1>Product Search Results:</h1>';
    // Loop over the results
    foreach( $cities AS $city ) {
        // $wpdb returns an array of objects, so output the object properties
        echo '<h2>' . $city->Product . '</h2>';
        echo '<p>' . $city->Application . '</p>';
        echo '<p>' . $city->Sector . '</p>';
    }
}

get_search_form();