I have javascript on custom page for get custom fields when hover a link of title post. my reference
custom.php
// other stuff here, wp_query etc
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>" target="_blank"><?php echo get_the_title(); ?></a>
footer.php
<script type="text/javascript">
jQuery(document).ready(function($) {
var request;
$('a[rel="bookmark"]')
.mouseenter(function() {
var dataId = $(this).attr('data-id');
request = $.ajax({
dataType: "JSON",
url: '<?php echo admin_url("admin-ajax.php"); ?>',
data: {"action": "our_ajax_function", "id": dataId},
success: function(data){
if(!data) {
console.log('data empty');
} else if(data.error) {
console.log('error');
} else {
console.log(data);
}
},
complete: function(){
console.log('complete')
}
})
})
.mouseleave(function() {
if (request) {
request.abort();
request = null;
}
});
});
</script>
And this my custom function on function.php to get_post_meta
by id
of post.
function our_ajax_function(){
$output = get_customs($_REQUEST['id']);
if( is_array( $output ) ) {
$output = json_encode( $output );
}
else {
wp_send_json_error();
}
}
function get_customs($id){
$custom = array(
"image" => get_post_meta($post->$id, 'image', true),
"synopsis" => get_post_meta($post->$id, 'synopsis', true)
);
if( count($custom) ) {
return $custom;
}
return false;
}
add_action('wp_ajax_our_ajax_function', 'our_ajax_function');
add_action('wp_ajax_nopriv_our_ajax_function', 'our_ajax_function');
So, I want the output should be $image
, $synopsis
using $id
form attribute data-id
of a[rel="bookmark"]
when mouse enter it and the request triggers. But on console I get data empty
. I'm sure, $output
are not empty.
XHR finished loading: GET "http://localhost/wp-admin/admin-ajax.php?action=our_ajax_function&id=17710".
data empty
complete
Sorry, I'm not telling you to correct my code. I just want to know the right way to do get custom fields, anyone can help me?