6

I have part search function in my WordPress website which uses dynamic dependent select box.

However, now I have the following problem:

If only select the first one box, or select the first two boxes, and click the Search button, it successfully jumps to the result page.

However, if continuously select the third box, it jumps to a page with the same URL as the result page but the content of the homepage.

I check the Chrome Console and see this error:

Failed to load resource: the server responded with a status of 404 (Not Found)

I have all the relative code below.

1. font-end part of the select boxes:

<form class="select-boxes" action="<?php echo site_url("/part-search-result/"); ?>" method="POST" target="_blank">
    <?php include(__DIR__.'/inc/part-search.php'); ?>
</form>

2. part-search.php

<?php
    include( __DIR__.'/db-config.php' );
    $query = $db->query("SELECT * FROM ps_manufact WHERE status = 1 ORDER BY manufact_name ASC");
    $rowCount = $query->num_rows;
?>

<select name="manufacturer" id="manufact" onchange="manufactText(this)">
    <option value="">Select Manufacturer</option>
    <?php
        if($rowCount > 0){
            while($row = $query->fetch_assoc()){
                echo '<option value="'.$row['manufact_id'].'">'.$row['manufact_name'].'</option>';
            }
        }else{
            echo '<option value="">Manufacturer Not Available</option>';
        }
    ?>
</select>
<input id="manufacturer_text" type="hidden" name="manufacturer_text" value=""/>
<script type="text/javascript">
    function manufactText(ddl) {
        document.getElementById('manufacturer_text').value = ddl.options[ddl.selectedIndex].text;
    }
</script>

<select name="type" id="type" onchange="typeText(this)">
    <option value="">Select Manufacturer First</option>
</select>
<input id="type_text" type="hidden" name="type_text" value=""/>
<script type="text/javascript">
    function typeText(ddl) {
        document.getElementById('type_text').value = ddl.options[ddl.selectedIndex].text;
    }
</script>

<select name="year" id="year" onchange="yearText(this)">
    <option value="">Select Type First</option>
</select>
<input id="year_text" type="hidden" name="year_text" value=""/>
<script type="text/javascript">
    function yearText(ddl) {
        document.getElementById('year_text').value = ddl.options[ddl.selectedIndex].text;
    }
</script>

<select name="model" id="model" onchange="modelText(this)">
    <option value="">Select Year First</option>
</select>
<input id="model_text" type="hidden" name="model_text" value=""/>
<script type="text/javascript">
    function modelText(ddl) {
        document.getElementById('model_text').value = ddl.options[ddl.selectedIndex].text;
    }
</script>

<input type="submit" name="search" id="search" value="Search">


<script type="text/javascript">
    jQuery(function($) {
        $('#manufact').on('change',function(){
            var manufactID = $(this).val();
            if(manufactID){
                $.ajax({
                    type:'POST',
                    url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
                    data:'manufact_id='+manufactID,
                    success:function(html){
                        $('#type').html(html);
                        $('#year').html('<option value="">Select Type First</option>');
                    }
                });
            }else{
                $('#type').html('<option value="">Select Manufact First</option>');
                $('#year').html('<option value="">Select Type First</option>');
            }
        });

        $('#type').on('change',function(){
            var typeID = $(this).val();
            if(typeID){
                $.ajax({
                    type:'POST',
                    url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
                    data:'type_id='+typeID,
                    success:function(html){
                        $('#year').html(html);
                        $('#model').html('<option value="">Select Year First</option>');
                    }
                });
            }else{
                $('#year').html('<option value="">Select Type First</option>');
                $('#model').html('<option value="">Select Year First</option>');
            }
        });

        $('#year').on('change',function(){
            var yearID = $(this).val();
            if(yearID){
                $.ajax({
                    type:'POST',
                    url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
                    data:'year_id='+yearID,
                    success:function(html){
                        $('#model').html(html);
                    }
                });
            }else{
                $('#model').html('<option value="">Select Year First</option>');
            }
        });
    });
</script>

3. ajax-data.php

<?php

include( __DIR__.'/db-config.php' );

if(isset($_POST["manufact_id"]) && !empty($_POST["manufact_id"])){
    $query = $db->query("SELECT * FROM ps_type WHERE manufact_id = ".$_POST['manufact_id']." AND status = 1 ORDER BY type_name ASC");

    $rowCount = $query->num_rows;

    if($rowCount > 0){
        echo '<option value="">Select Type</option>';
        while($row = $query->fetch_assoc()){
            echo '<option value="'.$row['type_id'].'">'.$row['type_name'].'</option>';
        }
    }else{
        echo '<option value="">Type Not Available</option>';
    }
}

if(isset($_POST["type_id"]) && !empty($_POST["type_id"])){
    $query = $db->query("SELECT * FROM ps_year WHERE type_id = ".$_POST['type_id']." AND status = 1 ORDER BY year_name ASC");

    $rowCount = $query->num_rows;

    if($rowCount > 0){
        echo '<option value="">Select Year</option>';
        while($row = $query->fetch_assoc()){
            echo '<option value="'.$row['year_id'].'">'.$row['year_name'].'</option>';
        }
    }else{
        echo '<option value="">Year Not Available</option>';
    }
}

if(isset($_POST["year_id"]) && !empty($_POST["year_id"])){
    $query = $db->query("SELECT * FROM ps_model WHERE year_id = ".$_POST['year_id']." AND status = 1 ORDER BY model_name ASC");

    $rowCount = $query->num_rows;

    if($rowCount > 0){
        echo '<option value="">Select Model</option>';
        while($row = $query->fetch_assoc()){
            echo '<option value="'.$row['model_id'].'">'.$row['model_name'].'</option>';
        }
    }else{
        echo '<option value="">Model Not Available</option>';
    }
}

?>

4. part-search-result.php

<?php

if (isset($_POST['search'])) {
    $clauses = array();
    if (isset($_POST['manufacturer_text']) && !empty($_POST['manufacturer_text'])) {
        $clauses[] = "`manufacturer` = '{$_POST['manufacturer_text']}'";
    }
    if (isset($_POST['type_text']) && !empty($_POST['type_text'])) {
        $clauses[] = "`type` = '{$_POST['type_text']}'";
    }
    if (isset($_POST['year_text']) && !empty($_POST['year_text'])) {
        $clauses[] = "`year` = '{$_POST['year_text']}'";
    }
    if (isset($_POST['model_text']) && !empty($_POST['model_text'])) {
        $clauses[] = "`model` = '{$_POST['model_text']}'";
    }
    $where = !empty( $clauses ) ? ' where '.implode(' and ',$clauses ) : '';
    $sql = "SELECT * FROM `wp_products` ". $where;
    $result = filterTable($sql);
} else {
    $sql = "SELECT * FROM `wp_products` WHERE `manufacturer`=''";
    $result = filterTable($sql);
}

function filterTable($sql) {
    $con = mysqli_connect("localhost", "root", "root", "i2235990_wp2");
    if (!$con) {
        die('Could not connect: ' . mysqli_error($con));
    }
    $filter_Result = mysqli_query($con, $sql);
    return $filter_Result;
}

?>

    <?php get_header(); ?>

    <div class="container">
        <div id="products" class="row list-group">
        <?php while ( $rows = mysqli_fetch_array($result) ): ?>
            <div class="item col-xs-12 col-sm-4 col-md-4 col-lg-4">
                <div class="thumbnail">
                    <?php
                        echo '<img name="product-image" class="group list-group-image hvr-bob" src=' . $rows['image_url'] . ' width="400px" height="250px" alt="" />';
                    ?>
                    <div class="caption">
                        <h4 class="group inner list-group-item-heading">
                        <?php
                            echo "Manufacturer:\t".$rows['manufacturer'].'<br>';
                            echo "Type:\t".$rows['type'].'<br>';
                            echo "Year:\t".$rows['year'].'<br>';
                            echo "Model:\t".$rows['model'].'<br>';
                            echo '<br>';
                            echo "Description:\t".$rows['description'].'<br>';
                        ?>
                        </h4>                           
                    </div>
                </div>
            </div>
        <?php endwhile; ?>
        </div>
    </div>

    <?php get_footer(); ?>

I thought there might be problem with not using POST correctly in WordPress, I found a tutorial: Handling POST Requests the WordPress Way

However, I already used action to jump to the result page, I have no idea how to solve my problem.

  • 1
    Are you sure about db_config.php ? Why not use global $wpdb ? codex.wordpress.org/Class_Reference/wpdb . Are you sure about the link in the action, did you set the permalink to get part-search-result.php ? – Benoti Nov 28 '16 at 18:46
  • Technically you can achieve all of this without using MySQL queries and by using only WP queries – Netanel Perez Mar 21 '17 at 11:42
  • Since you're basically not writing using any of the built-in WordPress functionalities, I'm not sure this belongs in the WPSE.. Why not use what WP has already done for you – Jeffrey von Grumbkow Mar 21 '17 at 13:12
1

To create your own independent search functionality, follow these steps.

1- You need a form to send the data for you. This is a simple form that can do this for you:

<form method="post" name="car-select" action="<?php echo site_url('/my-page/'); ?>">
    <select name="make">
        <option value="benz">Benz</option>
        <option value="bmw">BMW</option>
        <option value="audi">Audi</option>
    </select>
    <select name="type">
        <option value="sedan">Sedan</option>
        <option value="coupe">Coupe</option>
    </select>
    <input type="submit" value="Find my dream car!"/>
</form>

Which /my-page/ is the slug for the page we are going to create later.

2- A function to handle the search results. Take a look at this basic function that searches the cars based on the entered values:

function my_custom_search() {
    $car_make = $_POST['make'];
    $car_type = $_POST['type'];
    $car_query = new WP_Query ( array (
        'post_type' => 'post',
        'tax_query' => array(
            'relation' => 'AND',
            array (
                'taxonomy' => 'car_make',
                'field' => 'slug',
                'terms' => $car_make,
            ),
            array (
                'taxonomy' => 'car_type',
                'field' => 'slug',
                'terms' => $car_type,
            ),
         ),
    ));
    if ($car_query->have_posts) {
        while($car_query->have_posts()){
            $car_query->the_post();
            get_template_part('WHATEVER TEMPLATE YOU WANT TO USE');
        }
    }
    // Pagination goes here
}

3- A page to show your search results. Remember the slug in the first requirement? Create a page in your template's directory and name it like page-my-search-template.php. Then include this function in your new page template, wherever you wish:

my_custom_search();

You should then create a page with my-page slug (the one in the form's action), using the template you just made.

Now, every submission of the form will trigger a search query and display the results in your very own search template!

WAIT !! I want my pagination !!

You can implement your own pagination in the search function, however i recommend using WP-PageNavi for those who don't have enough skill to write a pagination script. Install the plugin, and set the query like this:

wp_pagenavi(array( 'query' => $car_query ));

This way you have a pagination for your custom search page, nice and easy.

|improve this answer|||||
0

You don't need any mySQL queries. WordPress's default search is submitting "s" with the URL. You can accomplish it with a simple form with hidden inputs.

<form role="search" method="get" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
  <input type="hidden" name="action" value="careers_search">
  <input type="text" name="search-career" value="Search...">
  <input type="submit" class="form-submit" value="Submit">
</form>

This form will submit itself on the same URL. After submissions this is what supposed to happen-

<?php
  if( isset( $_GET['careers_search'] ) ) {
    // Your code goes here...
  }
?>
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.