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();
}
<script>
:function h2 a{
... That needs to be fixed.