0

In my wordpress theme i m trying to print multiple custom fields of posts with ajax. First i get title of post with ajax live search correctly, now need to show post data after click on any post title.

After Click on any title in live search it show custom field for that post on same page??

HTML:

<h2><a href="#" name="metakey" id="metakey"><?php the_title();?></a></h2>
<div id="viewspec"> Meta key result here </div>

Funtion:

<?php
add_action('wp_ajax_data_fetchmeta' , 'data_fetchmeta');
add_action('wp_ajax_nopriv_data_fetchmeta','data_fetchmeta');
function data_fetchmeta(){

$the_query = new WP_Query( array( 's' => esc_attr( $_POST['metakey'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) :
    while( $the_query->have_posts() ): $the_query->the_post(); ?>       
<p>
    <?php echo get_post_meta( get_the_ID(), 'brand', true );?>
    <?php echo get_post_meta( get_the_ID(), 'price', true );?>
    <?php echo get_post_meta( get_the_ID(), 'cpu', true );?>
    <?php echo get_post_meta( get_the_ID(), 'ram', true );?>
</p>
  <?php endwhile;
  wp_reset_postdata();  
  endif;
  die();
}
?>

Script:

<script type="text/javascript">
function h2 a{

jQuery.ajax({
    url: '<?php echo admin_url('admin-ajax.php'); ?>',
    type: 'post',
    data: { action: 'data_fetchmeta', metakey: jQuery('#metakey').onclick() },
    success: function(data) {
        jQuery('#viewspec').html( data );
    }
});
}
</script>

AJAX live search: working

<input type="text" name="keyword" id="keyword" onkeyup="fetch()"></input>
<div id="datafetch">  Search result here  </div>

<?php
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
    url: '<?php echo admin_url('admin-ajax.php'); ?>',
    type: 'post',
    data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
    success: function(data) {
        jQuery('#datafetch').html( data );
    }
});
}
</script>
<?php
}

// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
if (  esc_attr( $_POST['keyword'] ) == null ) { die(); }
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr(     $_POST['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) :
    while( $the_query->have_posts() ): $the_query->the_post(); ?>

        <h2><a href="#" name="metakey" id="metakey"><?php the_title();?></a> </h2>

    <?php endwhile;
    wp_reset_postdata();  
    endif;
    die();
    }
  • 1
    Check out the JS console and look at inside <script>: function h2 a{... That needs to be fixed. – Dave Romsey Sep 28 '16 at 17:47
  • Please share your full code specially how you used your first Ajax call and query to init post title. – Mohammad Limon Sep 28 '16 at 18:01
  • @MohammadLimon i update my question with AJAX live search code.. – FRQ6692 Sep 28 '16 at 18:09
1

I'm not sure Why you used loop to display your post meta. and you code are all ok but you have to change little-bit.

Q. Why you used inline script ? On my opinion you should used external script file to do this.

anyway that's not the main issue here. In order to work with click function with ajax generate conten. You have to bind click function proper way otherwise it not will work.

Here is an example, but I'm useing external js file for this and so you just have to register.

/**
 * Add js file with Enqueues scripts.
 */
function wpse_scripts() {

    wp_enqueue_script( 'wpse-ajax-init', get_stylesheet_directory_uri() . '/js/wpse-ajax-init.js', array( 'jquery' ), '1.0', true );
    wp_localize_script( 'wpse-ajax-init', 'ajaxwpse', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' )
    ));

}
add_action( 'wp_enqueue_scripts', 'wpse_scripts' );

And now change you title markup that you fetch post title.

// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
if (  esc_attr( $_POST['keyword'] ) == null ) { die(); }
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr(     $_POST['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>

    <h2><a href="#" name="metakey" id="<?php the_ID(); ?>"><?php the_title();?></a> </h2>

<?php endwhile;
wp_reset_postdata();  
endif;
die();
}

I'm here just changed <h2><a href="#" name="metakey" id="metakey"><?php the_title();?></a> </h2> to <h2><a href="#" name="metakey" id="<?php the_ID(); ?>"><?php the_title();?></a> </h2> because you need to grab the ID of the title dynamically.

After doing that add below code on your wpse-ajax-init.js that you just register and hook with admin-ajax.php.

(function ($) {
    $("#datafetch").on('click', 'a', function(e) {
        e.preventDefault();

        $('#keyword').delay(100).attr('value', '');
        $(this).delay(100).hide();

       $.ajax({
            url: ajaxwpse.ajaxurl,
            type: 'post',
            data: { 
                action: 'data_fetchmeta', 
                ID: $(this).attr('id')
            },
            success: function(data) {
                $('#viewspec').html( data );
            }
        });
    });
})(jQuery);

And finally changed your data_fetchmeta() function query like this

add_action('wp_ajax_data_fetchmeta' , 'data_fetchmeta');
add_action('wp_ajax_nopriv_data_fetchmeta','data_fetchmeta');
function data_fetchmeta(){
    $ID = esc_attr( $_POST['ID'] ); ?>       
    <p>
        <?php echo get_post_meta( $ID, 'brand', true );?>
        <?php echo get_post_meta( $ID, 'price', true );?>
        <?php echo get_post_meta( $ID, 'cpu', true );?>
        <?php echo get_post_meta( $ID, 'ram', true );?>
    </p>
  <?php die();
}

You can see, I just grab the dynamic id and used to display post meta.

Hope it make sense to you.

  • Thanks code work well,,, some help here when i click on a title this show its custom fields now after that i don't not want to see title more.. in-short search field will be blank after click on title – FRQ6692 Sep 28 '16 at 21:26
  • Did you want to hide the title after click and search input value blank ? I did some update on my answer, so see that and if you want to hide full list a title then use like this $('#datafetch a').delay(1000).slideUp(); or you can hide by useing .hide() or fadeOut etc – Mohammad Limon Sep 28 '16 at 22:13
1

If you use a event handler when user click on your link, you can remove the onClick event.

the a tag must look like this to make it work with this method (assuming your loop has $post).

<a href="#" data-id="<?php echo $post->ID;?>" name="metakey" id="metakey"><?php echo $post->post_title;?></a>

the js :

$('a #metakey').on('click',function(e){
    e.preventDefault();
    var post_id = e.target.dataset.id
    data = {
         action: 'data_fetchmeta', 
         sel_action: 'show_metafield',
         post_id: post_id,
         }
    $.post(ajaxurl, data, function(response) {
        var json = $.parseJSON(response);
        $('#viewspec').html(json.metakey);
    });

});

the callback function

function data_fetchmeta(){
    if(isset($_POST['list_action'])){
        $action = $_POST['list_action'];
    }
    $action_params = array();
    parse_str($_POST['data'], $action_params);

    switch ($action){

        case 'show_metafield':
            ob_start(); // not necessary if you make a single string for $ result

            echo get_post_meta( $_POST['id'], 'brand', true );
            echo '<br/>;
            echo get_post_meta( $_POST['id'], 'price', true );
            echo '<br/>;
            echo get_post_meta( $_POST['id'], 'cpu', true );
            echo '<br/>;
            echo get_post_meta( $_POST['id'], 'ram', true );

            $result = ob_get_clean();
           echo json_encode(array(
                    'metakey'  =>$result
                )
            );


            exit();
        break;
        default:
        break;

}

There is many ways to do it, I hope this one helps you.

0

It appears you are not capturing the event when a search result is clicked. Your code for each search result is this:

<a href="#" name="metakey" id="metakey">Sony Lite</a>

I would add onclick='getPostMeta()' or similar. You may have to pass some data so the function knows which data to look up.

Inside the new function, put the jQuery.ajax function. That should get you started on getting data into the metakey part of your page.

  • Please read this tutorial from wordpress: codex.wordpress.org/AJAX_in_Plugins. It will help you understand why the ajax code works, rather than me doing your work for you. – scott Sep 28 '16 at 17:58

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.