如何在ajax调用中使用wordpress函数

我想知道是否有办法在ajax调用中使用query_post()这样的函数?

假设我正在调用文件_inc / ajax.php

我想能够使用wordpressfunction,但我不知道为什么。 有人可以帮助我吗?

非常感谢 :)

WordPress提供了一个Ajax Url,您应该使用它与完整的Ajax API一起使用。

您需要创建一个jQuery函数。

例:

jQuery(document).ready(function($) { var data = { action: 'my_action', whatever: 1234 }; jQuery.post(ajaxurl, data, function(response) { alert('Got this from the server: ' + response); }); }); 

管理员端始终可以使用ajaxurl var。 如果您在前端使用它,则需要定义它。

然后是一个PHP函数,您可以在其中运行查询。 PHP函数必须附加到wp_ajax_your_action操作。

例:

 add_action('wp_ajax_my_action', 'my_action_callback'); function my_action_callback() { global $wpdb; // this is how you get access to the database $whatever = intval( $_POST['whatever'] ); $whatever += 10; echo $whatever; die(); // this is required to return a proper result } 

wp_ajax_your_action操作适用于admin,如果您需要在前端使用它,则操作将为wp_ajax_nopriv_your_action

你必须在你的主题函数中创建你的function.php这是使用ajax加载热门post的示例

 function getPopularPosts() { $popularpostdata = wpp_get_mostpopular_data(); foreach($popularpostdata as $populardata) { $cur_id = $populardata->id; $cur_date = $populardata->post_date; $cur_date = date("F j, Y", strtotime($cur_date)); ?> 
>

'.getCategoryLink().''; $post_mp = get_post($cur_id); ?>

title;?>

post_author,$cur_id,$populardata->title,$cur_date); ?>
postcontent; //$content_post->post_content; $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); echo $content; wp_link_pages( array( 'before' => '', 'link_before' => '', 'link_after' => '', 'pagelink' => '' . __( 'Page', 'twentyfifteen' ) . ' %', 'separator' => ', ', ) ); ?>

TAGS:

post_author,$cur_id,$populardata->title); ?>
', '' ); ?>

'); $.ajax({ type: 'POST', url: "https://stackoverflow.com/questions/10807368/how-to-use-wordpress-functions-in-an-ajax-call//wp-admin/admin-ajax.php", data: { action: 'getPopularPosts' }, success: function( data ) { $('.popularposts').html(data); } }); } });

我强烈推荐JSON API插件: http : //wordpress.org/extend/plugins/json-api/ 。 它为最常见的WordPressfunction提供RESTful接口,包括query_post并允许您添加自己的操作。