0

I want access to an item details by WP_Query with page title

I tried this codes but failed:

<form method="GET" action="">
    <div>
        <input type="text" name="product">
    </div>
    <input type="submit" value="compare">
</form>
<?php  
if(isset($_GET['product']) && !empty($_GET['product'])) {

    $product_title = $_GET['product'];

    $prdocut_id = get_page_by_title($product_title);

    $args = array('page_id' => $product_id);
    $query = new WP_Query($args);

    if($query) :
        while ($query->have_posts()) :
            $query->the_post();
            the_title();
            the_content();
        endwhile;
    endif;
}
?>
  • Please explain how it fails. ps: you're missing a <?php. – birgire Nov 13 '14 at 9:24
  • 1
    sorry i didnt type <?php , now added . it just return hello world post id = 1 and that content – Cato Cato Nov 13 '14 at 9:26
1

There's a problem with your get_page_by_title() usage, since you assume it returns the page ID, but it returns an object/array or null. You also have to tell it about your custom post type.

I also assume your products are stored as custom post type cars.

Please try the following with a given product title (untested):

// DEBUG: Let's first try out an existing product title:
$product_title = 'Some product title'; #<-- Adjust this to your needs!

// User input:
// $product_title = filter_input( INPUT_GET, 'product', FILTER_SANITIZE_STRING );

// Search for pages with the above product title:
$product = get_page_by_title( $product_title, $output = OBJECT, $cpt = 'cars' );

// Product exists:
if( $product ) {
    $query = new WP_Query( array( 'p' => $product->ID ) );
    if( $query->have_posts() ) {
        while ($query->have_posts()) {
            $query->the_post();
            the_title();
            the_content();
        } 
    }
}

Hopefully this could be a starting point for some further debugging.

|improve this answer|||||
  • if custom post type is cars , i should change $cpt = 'cars' ? when i change it to cars it doesnt work – Cato Cato Nov 13 '14 at 10:05
  • Yes, so you're using a custom post type and not pages? – birgire Nov 13 '14 at 10:06
  • yeah using post type – Cato Cato Nov 13 '14 at 10:07
  • You should update your question with that extra information. I updated the answer. – birgire Nov 13 '14 at 10:10
  • you're welcome, best of luck with your project. – birgire Nov 13 '14 at 11:03

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.