dougou7782 2018-01-09 16:12
浏览 59

使用ajax,php到jquery获取wordpress posts数组

I am trying to write some code to retrieve wordpress posts to jquery using Ajax

I am just learning so have been alerting to the screen. This is what i have so far:

test.js

  jQuery(document).ready(function($){
   var test_name = "testname";    
   $.ajax({
     url:'/wp-content/plugins/myPlugin/test.php',
     data: {name:test_name},
     type: 'POST',
     cache: false,
     success: function(data){
       alert(data);
     },
     error: function(data){
       alert('something went wrong');           
     }
   });
});

test.php

<?php
$post_args = array(
    'post_type'  => 'products',
    'numberposts' => -1
);
$myProducts = get_posts($post_args);
echo $myProducts;
?>

Can someone point me in the right direction, I can receive strings back from the test.php, so i know the test.php file is being processed. Thank you for any help/explanations

  • 写回答

1条回答 默认 最新

  • drm30963 2018-01-09 18:22
    关注

    I believe I have got the solution I was looking for, thank you for pointing me towards the admin-ajax.php. Here is the code (not complete but good starter):

    test.js

       var wpajax_url = document.location.protocol + '//' + document.location.host + '/wp-admin/admin-ajax.php?action=myAction';
    
       var myPostType = "products";
    
       $.ajax({
         'method':'post',
         'url':wpajax_url,
         'data': {aPostType: myPostType},
         'datatype':'json', 
         'cache': false,
         'success': function(data){
           alert(data);
         },
         'error': function(data){
           alert('something went wrong');
         }
       });
    

    test.php

    //register myAction with wordpress
    add_action('wp_ajax_nopriv_myAction','myAction';
    add_action('wp_ajax_myAction','myAction');
    
    function myAction(){
            $post_args = array(
                    'post_type'  => $_POST['aPostType'],
                    'numberposts' => -1
            );
    
            $posts = get_posts( $post_args );
    
            foreach ( $posts as $key => $post) {
                $postArray[$key]= $post->post_title;
            }
            // return result as json
           $json_result = json_encode( $postArray );
           die( $json_result );
    }
    

    Hope this can help someone else

    评论

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏