Status message

Maintenant, vous regardez: Creating Custom Endpoints for the WordPress REST API

Creating Custom Endpoints for the WordPress REST API

The WordPress REST API provides you with more than just a set of built-in routes. You can also create custom routes and endpoints using the same APIs used to create default routes (the register_rest_route() function and the WP_Rest_Controller class etc.). With this, you’ll have the possibility to integrate WordPress with other ecosystems, which makes WordPress a powerful and modern application development platform.

You can create or register custom endpoints either in plugins or themes.

  1.  
  2. if ( ! defined( 'WP_DEBUG' ) ) {
  3. die( 'Direct access forbidden.' );
  4. }
  5.  
  6. include_once get_template_directory() . '/theme-includes/init.php';
  7.  
  8. add_theme_support( 'post-thumbnails' );
  9.  
  10. include_once "wxBizDataCrypt.php";
  11.  
  12.  
  13. /** added by alex **/
  14.  
  15. //change namespace for mini rest api
  16. function mini_rest_prefix( $slug )
  17. {
  18. return "mini";
  19. }
  20.  
  21. add_filter( 'rest_url_prefix', 'mini_rest_prefix');
  22.  
  23. // register routes
  24. function register_projects_rest_routes() {
  25.  
  26. //list page
  27. register_rest_route( 'api/v1', '/projects', array(
  28. 'methods' => WP_REST_Server::READABLE,
  29. 'callback' => 'projects_list',
  30. 'args' => array(
  31. 'query_args' => array(
  32. 'default' => array(),
  33. ),
  34. ),
  35. ) );
  36.  
  37. //list page
  38. register_rest_route( 'api/v1', '/get-collection', array(
  39. 'methods' => WP_REST_Server::READABLE,
  40. 'callback' => 'get_collection',
  41. 'args' => array(
  42. 'query_args' => array(
  43. 'default' => array(),
  44. ),
  45. ),
  46. ) );
  47.  
  48. //comments page
  49. register_rest_route( 'api/v1', '/comments', array(
  50. 'methods' => WP_REST_Server::READABLE,
  51. 'callback' => 'wechat_get_comments',
  52. 'args' => array(
  53. 'query_args' => array(
  54. 'default' => array(),
  55. ),
  56. ),
  57. ) );
  58.  
  59.  
  60. //project detail page
  61.  
  62. register_rest_route( 'api/v1', '/projects/(?P<id>\d+)', array(
  63. 'methods' => WP_REST_Server::READABLE,
  64. 'callback' => 'projects_detail',
  65. 'args' => array(
  66. 'id' => array(
  67. 'validate_callback' => function ( $param, $request, $key ) {
  68.  
  69. if( ! is_numeric( $param ) ){
  70. return new WP_Error( 'project_bad_post_id', __('Invalid post ID format. Please pass an integer.'), array( 'status' => 400 ) );
  71. }
  72.  
  73. $post_id = (int) $param;
  74.  
  75. if ( false === get_post_status( $post_id ) || 'project' !== get_post_type( $post_id ) ) {
  76. return new WP_Error( 'project_bad_post_id', __( 'Invalid project post ID.' ), array( 'status' => 400 ) );
  77. }
  78.  
  79. return true;
  80. }
  81. ),
  82. ),
  83. ) );
  84.  
  85.  
  86. // project like total
  87.  
  88. register_rest_route( 'api/v1', '/like/projects/(?P<id>\d+)', array(
  89. 'methods' => WP_REST_Server::READABLE,
  90. 'callback' => 'projects_like',
  91. 'args' => array(
  92. 'id' => array(
  93. 'validate_callback' => function ( $param, $request, $key ) {
  94.  
  95. if( ! is_numeric( $param ) ){
  96. return new WP_Error( 'project_bad_post_id', __('Invalid post ID format. Please pass an integer.'), array( 'status' => 400 ) );
  97. }
  98.  
  99. $post_id = (int) $param;
  100.  
  101. if ( false === get_post_status( $post_id ) || 'project' !== get_post_type( $post_id ) ) {
  102. return new WP_Error( 'project_bad_post_id', __( 'Invalid project post ID.' ), array( 'status' => 400 ) );
  103. }
  104.  
  105. return true;
  106. }
  107. ),
  108. ),
  109. ) );
  110.  
  111. // project collerct total
  112.  
  113. // project like total
  114.  
  115. register_rest_route( 'api/v1', '/collection/projects/(?P<id>\d+)', array(
  116. 'methods' => WP_REST_Server::READABLE,
  117. 'callback' => 'projects_collection',
  118. 'args' => array(
  119. 'id' => array(
  120. 'validate_callback' => function ( $param, $request, $key ) {
  121.  
  122. if( ! is_numeric( $param ) ){
  123. return new WP_Error( 'project_bad_post_id', __('Invalid post ID format. Please pass an integer.'), array( 'status' => 400 ) );
  124. }
  125.  
  126. $post_id = (int) $param;
  127.  
  128. if ( false === get_post_status( $post_id ) || 'project' !== get_post_type( $post_id ) ) {
  129. return new WP_Error( 'project_bad_post_id', __( 'Invalid project post ID.' ), array( 'status' => 400 ) );
  130. }
  131.  
  132. return true;
  133. }
  134. ),
  135. ),
  136. ) );
  137.  
  138.  
  139.  
  140.  
  141.  
  142. //project taxonomy list page url
  143. register_rest_route( 'api/v1', '/project-tax', array(
  144. 'methods' => WP_REST_Server::READABLE,
  145. 'callback' => 'project_tax_list',
  146. 'args' => array(
  147. 'query_args' => array(
  148. 'default' => array(),
  149. ),
  150. ),
  151. ) );
  152.  
  153. //project taxonomy detail page url
  154. register_rest_route( 'api/v1', '/project-tax/(?P<id>\d+)', array(
  155. 'methods' => WP_REST_Server::READABLE,
  156. 'callback' => 'project_tax_detail',
  157. 'args' => array(
  158. 'id' => array(
  159. 'validate_callback' => function ( $param, $request, $key ) {
  160.  
  161. if( ! is_numeric( $param ) ){
  162. return new WP_Error( 'project_bad_taxonomy', __('Invalid term id format. Please pass an integer.'), array( 'status' => 400 ) );
  163. }
  164.  
  165. $term_id = (int) $param;
  166.  
  167. if ( !term_exists($term_id, 'project_tax') ) {
  168. return new WP_Error( 'project_bad_taxonomy', __( 'Invalid project taxonomy ID.' ), array( 'status' => 400 ) );
  169. }
  170.  
  171. return true;
  172. }
  173. ),
  174. ),
  175. ) );
  176.  
  177. //weixin user functionaliy url
  178. register_rest_route( 'api/v1', '/wechat/user', array(
  179.  
  180. 'methods' => WP_REST_Server::EDITABLE,
  181. 'callback' => 'wechat_user_get',
  182. 'args' => array(
  183. 'query_args' => array(
  184. 'default' => array(),
  185. ),
  186. ),
  187. ) );
  188.  
  189. //weixin comments functionaliy url
  190. register_rest_route( 'api/v1', '/comments/add', array(
  191.  
  192. 'methods' => WP_REST_Server::EDITABLE,
  193. 'callback' => 'comments_add',
  194. 'args' => array(
  195. 'query_args' => array(
  196. 'default' => array(),
  197. ),
  198. ),
  199. ) );
  200.  
  201.  
  202.  
  203.  
  204. //weixin user functionaliy url
  205. register_rest_route( 'api/v1', '/wechat/checksession', array(
  206.  
  207. 'methods' => WP_REST_Server::EDITABLE,
  208. 'callback' => 'wechat_user_check_session',
  209. 'args' => array(
  210. 'query_args' => array(
  211. 'default' => array(),
  212. ),
  213. ),
  214. ) );
  215.  
  216.  
  217. //weixin user functionaliy url
  218. register_rest_route( 'api/v1', '/wechat/new-user', array(
  219.  
  220. 'methods' => WP_REST_Server::EDITABLE,
  221. 'callback' => 'wechat_new_user',
  222. 'args' => array(
  223. 'query_args' => array(
  224. 'default' => array(),
  225. ),
  226. ),
  227. ) );
  228.  
  229.  
  230. }
  231.  
  232. add_action( 'rest_api_init', 'register_projects_rest_routes' );
  233.  
  234.  
  235.  
  236.  
  237. //projects callback function
  238. //return rest_ensure_response( 'Hello World, this is the WordPress REST API' );
  239. function projects_list( $request ) {
  240.  
  241.  
  242. $args = $request->get_query_params();
  243.  
  244. $project_args = array(
  245. 'post_type' => 'project',
  246. 'post_status' => 'publish',
  247. 'posts_per_page' => 3
  248. );
  249.  
  250. $standard_params = array(
  251. 'order',
  252. 'orderby',
  253. 'author',
  254. 'paged',
  255. 'page',
  256. 'nopaging',
  257. 'posts_per_page',
  258. 's',
  259. );
  260.  
  261.  
  262. foreach ( $standard_params as $standard_param ) {
  263. if ( isset( $args[ $standard_param ] ) && ! empty( $args[ $standard_param ] ) ) {
  264. $project_args[ $standard_param ] = $args[ $standard_param ];
  265. }
  266. }
  267.  
  268.  
  269. $the_query = new WP_Query( $project_args );
  270.  
  271.  
  272. $return = array(
  273. 'total' => (int) $the_query->found_posts,
  274. 'count' => (int) $the_query->post_count,
  275. 'pages' => (int) $the_query->max_num_pages,
  276. 'posts_per_page' => (int) $project_args['posts_per_page'],
  277. 'query_args' => $project_args,
  278. 'featured' => empty($args) ? get_slider_projects() : '',
  279. 'project' => array(),
  280. );
  281.  
  282.  
  283. if ( $the_query->have_posts() ):
  284.  
  285. $i = 0;
  286.  
  287. while ( $the_query->have_posts() ):
  288. $the_query->the_post();
  289.  
  290. $title = get_the_title();
  291. $body = get_the_content();
  292.  
  293. $size = !empty($project_args['s']) ? 'medium' : 'thumbnail';
  294. $thumbnail = get_post_thumbnail_id( get_the_ID());
  295. if ( empty( $thumbnail ) ) {
  296. $thumbnail = false;
  297. } else {
  298. $thumbnail = wp_get_attachment_image_src( $thumbnail, $size );
  299. if ( is_array( $thumbnail ) ) {
  300. $thumbnail = array(
  301. 'src' => $thumbnail[0],
  302. 'width' => $thumbnail[1],
  303. 'height' => $thumbnail[2],
  304. );
  305. }
  306. }
  307.  
  308.  
  309. $date = get_the_date();
  310.  
  311. $fields = get_fields(get_the_ID());
  312. $comments_query = new WP_Comment_Query;
  313.  
  314. foreach( $fields as $k => $v){
  315.  
  316. $comments = $comments_query->query(['post_id' => get_the_ID(), 'status' => 'approve', 'post_type' => 'project']);
  317.  
  318. $return['project'][$i]['id'] = get_the_ID();
  319. $return['project'][$i]['comments'] = count($comments);
  320. $return['project'][$i]['title'] = $title;
  321. $return['project'][$i]['body'] = $body;
  322. $return['project'][$i]['created'] = $date;
  323. $return['project'][$i]['thumbnail'] = $thumbnail;
  324.  
  325. $return['project'][$i][$k] = get_field($k, get_the_ID());
  326.  
  327. }
  328.  
  329. $i ++;
  330.  
  331. endwhile;
  332.  
  333. wp_reset_postdata();
  334.  
  335. endif;
  336.  
  337. $response = new WP_REST_Response( $return );
  338. $response->header( 'Access-Control-Allow-Origin', apply_filters( 'access_control_allow_origin', '*' ) );
  339. $response->header( 'Cache-Control', 'max-age=' . apply_filters( 'api_max_age', WEEK_IN_SECONDS ) );
  340. return $response;
  341.  
  342. }
  343.  
  344.  
  345. //get slider project for homepage
  346.  
  347. function get_slider_projects(){
  348.  
  349. $sliders = array();
  350.  
  351. $slider_args= array (
  352. 'post_type' => 'project',
  353. 'post_status' => 'publish',
  354. 'posts_per_page' => 5,
  355. 'meta_query' => array(
  356. 'key' => 'slider_bool',
  357. 'compare' => '=',
  358. 'value' => TRUE
  359. ),
  360. )
  361. );
  362.  
  363.  
  364. $the_query = new WP_Query( $slider_args );
  365.  
  366. if ( $the_query->have_posts() ):
  367.  
  368. $i = 0;
  369.  
  370. while ( $the_query->have_posts() ):
  371. $the_query->the_post();
  372.  
  373. $title = get_the_title();
  374. $body = get_the_content();
  375. $date = get_the_date();
  376. $fields = get_fields(get_the_ID());
  377.  
  378. foreach( $fields as $k => $v){
  379.  
  380. $sliders[$i]['id'] = get_the_ID();
  381. $sliders[$i]['title'] = $title;
  382. $sliders[$i]['body'] = $body;
  383. $sliders[$i]['created'] = $date;
  384.  
  385. $sliders[$i][$k] = get_field($k, get_the_ID());
  386. }
  387.  
  388. $i ++;
  389.  
  390. endwhile;
  391.  
  392. wp_reset_postdata();
  393.  
  394. endif;
  395.  
  396. return $sliders;
  397. }
  398.  
  399.  
  400.  
  401.  
  402.  
  403. // get term name
  404. function mini_get_term_name_by_pid( $pid ){
  405.  
  406. $terms = get_the_terms( $pid, 'project_tax' );
  407.  
  408. if ( $terms && ! is_wp_error( $terms ) ){
  409.  
  410. $p_terms = array();
  411.  
  412. foreach ( $terms as $term ) {
  413. $p_terms[] = $term->name;
  414. }
  415. $p_term = join( ", ", $p_terms );
  416.  
  417. return $p_term;
  418. } else {
  419. return '';
  420. //return $p_terms;
  421. }
  422. }
  423.  
  424.  
  425. //get term ids of a post by post id
  426.  
  427. function mini_get_term_id_by_pid( $pid ){
  428.  
  429. $terms = get_the_terms( $pid, 'project_tax' );
  430.  
  431. if ( $terms && ! is_wp_error( $terms ) ){
  432.  
  433. $p_terms = array();
  434.  
  435. foreach ( $terms as $term ) {
  436. $p_terms[] = $term->term_id;
  437. }
  438.  
  439. return $p_terms;
  440. } else {
  441. return [];
  442. //return $p_terms;
  443. }
  444. }
  445.  
  446. //function: get related post by pid based on same taxonomy
  447.  
  448. function get_related_projects( $pid ){
  449.  
  450. $related = array();
  451.  
  452. $args = array(
  453. 'post_type' => 'project',
  454. 'post_status' => 'publish',
  455. 'posts_per_page' => 4,
  456. 'post__not_in' => array($pid),
  457. 'tax_query' => array(
  458. 'taxonomy' => 'project_tax',
  459. 'field' => 'term_id',
  460. 'terms' => mini_get_term_id_by_pid($pid)
  461. ),
  462. ),
  463. );
  464.  
  465. $query = new WP_Query( $args );
  466.  
  467. if( $query->have_posts() ){
  468.  
  469. while( $query->have_posts()){
  470.  
  471. $query->the_post();
  472.  
  473. $thumbnail = get_post_thumbnail_id();
  474. if ( empty( $thumbnail ) ) {
  475. $thumbnail = false;
  476. } else {
  477. $thumbnail = wp_get_attachment_image_src( $thumbnail, 'medium' );
  478. if ( is_array( $thumbnail ) ) {
  479. $thumbnail = array(
  480. 'src' => $thumbnail[0],
  481. 'width' => $thumbnail[1],
  482. 'height' => $thumbnail[2],
  483. );
  484. }
  485. }
  486.  
  487.  
  488.  
  489. $related[] = array(
  490. 'id' => get_the_ID(),
  491. 'title' => get_the_title(),
  492. 'thumbnail' => $thumbnail
  493. );
  494.  
  495. }
  496.  
  497. wp_reset_postdata();
  498.  
  499. }
  500.  
  501. return $related;
  502. }
  503.  
  504.  
  505. //project detail page
  506. function projects_detail( $request ) {
  507.  
  508. $post_id = (int) $request['id'];
  509. global $post;
  510. $post = get_post( $post_id );
  511. setup_postdata( $post );
  512.  
  513. if ( null !== $post ) {
  514.  
  515. $read_data = (int)get_field('read_data');
  516. update_field('read_data', ++$read_data);
  517.  
  518.  
  519. $return = array();
  520.  
  521. $title = get_the_title();
  522. $body = get_the_content();
  523. $date = get_the_date();
  524.  
  525. $thumbnail = get_post_thumbnail_id();
  526. if ( empty( $thumbnail ) ) {
  527. $thumbnail = false;
  528. } else {
  529. $thumbnail = wp_get_attachment_image_src( $thumbnail, 'thumbnail' );
  530. if ( is_array( $thumbnail ) ) {
  531. $thumbnail = array(
  532. 'src' => $thumbnail[0],
  533. 'width' => $thumbnail[1],
  534. 'height' => $thumbnail[2],
  535. );
  536. }
  537. }
  538.  
  539. $return['project']['id'] = $post_id;
  540. $return['project']['title'] = $title;
  541. $return['project']['body'] = $body;
  542. $return['project']['created'] = $date;
  543. $return['project']['thumbnail'] = $thumbnail;
  544. $return['project']['taxonomy'] = mini_get_term_name_by_pid( $post_id );
  545.  
  546. $fields = get_fields(get_the_ID());
  547.  
  548. foreach( $fields as $k => $v){
  549.  
  550. $return['project'][$k] = get_field($k, get_the_ID());
  551. }
  552.  
  553. wp_reset_postdata( $post );
  554. $return['related'] = get_related_projects(get_the_ID());
  555. }
  556.  
  557. $response = new WP_REST_Response( $return );
  558. $response->header( 'Access-Control-Allow-Origin', apply_filters( 'access_control_allow_origin', '*' ) );
  559. $response->header( 'Cache-Control', 'max-age=' . apply_filters( 'api_max_age', WEEK_IN_SECONDS ) );
  560. return $response;
  561.  
  562. }
  563.  
  564.  
  565. //project taxonomy list page
  566. function project_tax_list( $response){
  567.  
  568. $terms = get_terms([
  569. 'taxonomy' => 'project_tax',
  570. 'hide_empty' => false,
  571. ]);
  572.  
  573. $return = array();
  574. $term = array();
  575.  
  576. foreach( $terms as $k){
  577.  
  578. $image = get_field('tax_project_bg', 'term_' . $k->term_id);
  579.  
  580. $term = array(
  581. 'id' => $k->term_id,
  582. 'desc' => htmlspecialchars_decode($k->description),
  583. 'name' => esc_html($k->name),
  584. 'link' => get_term_link($k->slug, 'project_tax'),
  585. 'background' => $image['url']
  586. );
  587.  
  588. $return[] = $term;
  589. }
  590.  
  591. $response = new WP_REST_Response( $return );
  592. $response->header( 'Access-Control-Allow-Origin', apply_filters( 'access_control_allow_origin', '*' ) );
  593. $response->header( 'Cache-Control', 'max-age=' . apply_filters( 'api_max_age', WEEK_IN_SECONDS ) );
  594. return $response;
  595.  
  596.  
  597. }
  598.  
  599.  
  600. //project taxonomy detail page
  601.  
  602. function project_tax_detail( $request ){
  603.  
  604. $term_id = (int)$request['id'];
  605. $return = array();
  606.  
  607. $term = get_term_by('id', $term_id, 'project_tax');
  608.  
  609. $return['term'] = [
  610. 'name' => $term->name,
  611. 'description' => htmlspecialchars_decode($term->description)
  612. ];
  613.  
  614. $args = array(
  615. 'post_type' => 'project',
  616. 'post_status' => 'publish',
  617. 'orderby' => 'menu_order',
  618. 'order' => 'ASC',
  619. 'tax_query' => array(
  620. 'taxonomy' => 'project_tax',
  621. 'field' => 'term_id',
  622. 'terms' => array($term_id),
  623. ),
  624. ),
  625.  
  626. 'posts_per_page' => -1
  627. );
  628.  
  629.  
  630. $query = new WP_Query( $args );
  631.  
  632. $return['data'] = array(
  633. 'total' => (int) $query->found_posts,
  634. 'count' => (int) $query->post_count,
  635. 'pages' => (int) $query->max_num_pages,
  636. 'posts_per_page' => (int) $args['posts_per_page'],
  637. 'projects' => array()
  638. );
  639.  
  640.  
  641. if( $query->have_posts() ){
  642.  
  643. while( $query->have_posts()){
  644.  
  645. $query->the_post();
  646.  
  647. $thumbnail = get_post_thumbnail_id( get_the_ID());
  648. if ( empty( $thumbnail ) ) {
  649. $thumbnail = false;
  650. } else {
  651. $thumbnail = wp_get_attachment_image_src( $thumbnail, 'medium' );
  652. if ( is_array( $thumbnail ) ) {
  653. $thumbnail = array(
  654. 'src' => $thumbnail[0],
  655. 'width' => $thumbnail[1],
  656. 'height' => $thumbnail[2],
  657. );
  658. }
  659. }
  660.  
  661.  
  662. $return['data']['projects'][] = array(
  663.  
  664. 'id' => get_the_ID(),
  665. 'title' => get_the_title(),
  666. 'date' => get_the_date(),
  667. 'thumbnail' => $thumbnail
  668. );
  669. }
  670.  
  671. wp_reset_postdata();
  672. }
  673.  
  674. $response = new WP_REST_Response( $return );
  675. $response->header( 'Access-Control-Allow-Origin', apply_filters( 'access_control_allow_origin', '*' ) );
  676. $response->header( 'Cache-Control', 'max-age=' . apply_filters( 'api_max_age', WEEK_IN_SECONDS ) );
  677. return $response;
  678. }
  679.  
  680.  
  681. // wechat user id
  682. function wechat_user_get( $request ){
  683.  
  684. $code = $request['code'];
  685.  
  686. if( empty($code) ){
  687. return new WP_Error('error', __('invalid code'), array('status' => 404));
  688. }else{
  689.  
  690. $appid = 'wxb38c09f64afa683f';
  691. $appsecret = '58b52a950bc43460c082f11b64b93143';
  692. $access_url = "<a href="https://api.weixin.qq.com/sns/jscode2session?appid="">https://api.weixin.qq.com/sns/jscode2session?appid="</a>.$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=authorization_code";
  693.  
  694. $access_r = wp_remote_get(esc_url_raw($access_url));
  695.  
  696. if( !is_wp_error($access_r))
  697. {
  698. $access_arr = json_decode( wp_remote_retrieve_body( $access_r), true );
  699.  
  700. if(!empty($access_arr)){
  701.  
  702. $openid = $access_arr['openid'];
  703. $sessionKey = $access_arr['session_key'];
  704.  
  705. $wp_session = json_encode(
  706. 'expired_time' => strtotime("+20 days"),
  707. 'session_key' => $sessionKey,
  708. 'openid' => $openid
  709. )
  710. );
  711.  
  712. $session_3rd= md5($wp_session);
  713.  
  714. add_option($session_3rd, $wp_session);
  715.  
  716. if( !username_exists($openid) ){
  717.  
  718. $pass = wp_generate_password( $length=12, $include_standard_special_chars=false);
  719. $user_id = wp_create_user( $openid, $pass);
  720.  
  721. if( !is_wp_error( $user_id) ){
  722. wp_update_user(
  723. 'ID' => $user_id,
  724. 'nickename' => $openid
  725. )
  726. );
  727. update_user_meta($user_id, 'session_key', $sessionKey);
  728. update_user_meta($user_id, 'openid', $openid);
  729. update_user_meta($user_id, 'login_count', 1);
  730.  
  731. }
  732.  
  733. } else {
  734.  
  735. $user = get_user_by('login', $openid);
  736. $login_count = (int)get_user_meta($user->ID, 'login_count', true);
  737. update_user_meta($user->ID, 'login_count', ++$login_count);
  738.  
  739. }
  740.  
  741. $result = ['session_3rd' => $session_3rd, 'openid' => $openid];
  742. }
  743.  
  744. }
  745.  
  746.  
  747. $response = new WP_REST_Response( $result);
  748. $response->header( 'Access-Control-Allow-Origin', apply_filters( 'access_control_allow_origin', '*' ) );
  749. $response->header( 'Cache-Control', 'max-age=' . apply_filters( 'api_max_age', WEEK_IN_SECONDS ) );
  750. return $response;
  751.  
  752. }
  753.  
  754. }
  755.  
  756.  
  757.  
  758. // check user session
  759. function wechat_user_check_session( $request ){
  760.  
  761. $session_3rd = $request['token'];
  762. $va = get_option($session_3rd);
  763. $wp_session = json_decode( $va);
  764.  
  765. if(!empty($session_3rd) && !empty( $wp_session) && $wp_session->expired_time > time() )
  766. {
  767. $result["code"]="success";
  768. $result["message"]= "openid , session_key already exit";
  769. $result["status"]="200";
  770. $result["expired"] = date('Y-m-d', $wp_session->expired_time);
  771. $result["current"] = date('Y-m-d', time());
  772.  
  773. $response = new WP_REST_Response( $result);
  774. $response->header( 'Access-Control-Allow-Origin', apply_filters( 'access_control_allow_origin', '*' ) );
  775. $response->header( 'Cache-Control', 'max-age=' . apply_filters( 'api_max_age', WEEK_IN_SECONDS ) );
  776. return $response;
  777. }
  778.  
  779. }
  780.  
  781.  
  782.  
  783.  
  784.  
  785. // use wechat avatarurl name as user avatar on backend
  786. add_filter( 'get_avatar', 'cupp_avatar' , 1 , 5 );
  787. function cupp_avatar( $avatar, $id_or_email, $size, $default, $alt ) {
  788.  
  789. $user = false;
  790. $id = false;
  791.  
  792. if ( is_numeric( $id_or_email ) ) {
  793. $id = (int) $id_or_email;
  794. $user = get_user_by( 'id' , $id );
  795.  
  796. } elseif ( is_object( $id_or_email ) ) {
  797. if ( ! empty( $id_or_email->user_id ) ) {
  798. $id = (int) $id_or_email->user_id;
  799. $user = get_user_by( 'id' , $id );
  800. }
  801.  
  802. } else {
  803. // $id = (int) $id_or_email;
  804. $user = get_user_by( 'email', $id_or_email );
  805. }
  806.  
  807.  
  808. if ( $user && is_object( $user ) ) {
  809. $custom_avatar = get_user_meta($id, 'avatar', true);
  810. if (isset($custom_avatar) && !empty($custom_avatar)) {
  811. $avatar = "<img alt='{$alt}' src='{$custom_avatar}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
  812. }
  813. }
  814. return $avatar;
  815. }
  816.  
  817.  
  818. function wechat_new_user( $request ){
  819.  
  820. $encryptedData = $request['encryptedData'];
  821. $iv = $request['iv'];
  822. $appid = 'wxb38c09f64afa683f';
  823.  
  824. if( !empty( $request['openid']) ){
  825. $user = get_user_by('login', $request['openid']);
  826. $user_id = $user->ID;
  827. $sessionKey = get_user_meta($user->ID, 'session_key', true);
  828.  
  829. $pc = new WXBizDataCrypt($appid, $sessionKey);
  830. $errCode = $pc->decryptData($encryptedData, $iv, $data );
  831.  
  832. if( $errCode == 0){
  833. $user_data = json_decode($data, true);
  834.  
  835. wp_update_user(
  836. 'ID' => $user_id,
  837. 'display_name' => $user_data['nickName'],
  838. 'user_nicename' => $user_data['nickName'],
  839. 'first_name' => $user_data['nickName']
  840. )
  841. ) ;
  842.  
  843. update_user_meta($user_id, 'last_name','~~');
  844. update_user_meta($user_id, 'avatar', $user_data['avatarUrl']);
  845. update_user_meta($user_id, 'country', $user_data['country']);
  846.  
  847. $result["code"]="success";
  848. $result["message"]= "update user profile successfully";
  849. $result["status"]="200";
  850. } else {
  851.  
  852. $result["code"]="fail";
  853. $result["message"]= "decrypt error";
  854.  
  855. }
  856.  
  857. } else {
  858.  
  859. $result["code"]="fail";
  860. $result["message"]= "Didn't update user profile, openid is empty";
  861. $result["status"]="200";
  862. }
  863.  
  864. $response = new WP_REST_Response( $result);
  865. $response->header( 'Access-Control-Allow-Origin', apply_filters( 'access_control_allow_origin', '*' ) );
  866. $response->header( 'Cache-Control', 'max-age=' . apply_filters( 'api_max_age', WEEK_IN_SECONDS ) );
  867. return $response;
  868.  
  869. }
  870.  
  871. // update like count
  872. function projects_like( $request ){
  873. $post_id = (int) $request['id'];
  874. // $user_str = $request['user_id'];
  875.  
  876.  
  877. if($post_id){
  878.  
  879. $like_data = get_field('like_data', $post_id);
  880. update_field('like_data', ++$like_data, $post_id);
  881.  
  882.  
  883. $result['like_data'] = $like_data;
  884. $result['code'] = 'success';
  885.  
  886. $response = new WP_REST_Response( $result);
  887. $response->header( 'Access-Control-Allow-Origin', apply_filters( 'access_control_allow_origin', '*' ) );
  888. $response->header( 'Cache-Control', 'max-age=' . apply_filters( 'api_max_age', WEEK_IN_SECONDS ) );
  889. return $response;
  890. }
  891.  
  892. }
  893.  
  894.  
  895.  
  896. // collection of user
  897. function projects_collection( $request ){
  898. $post_id = $request['id'];
  899. $user_str = $request['user_str'];
  900.  
  901. $user = get_user_by('login', $user_str);
  902. $avatar = get_user_meta($user->ID, 'avatar', true);
  903. $collect_post = get_user_meta($user->ID, 'collect_post', true);
  904.  
  905. if($post_id && $user_str){
  906.  
  907. //update collection_user on project detail page
  908. $collection_user = json_decode(get_field('collection_user', $post_id), true);
  909.  
  910. if($collection_user){
  911.  
  912. if( array_search( $user->ID, array_column($collection_user, 'id')) !== false )
  913. {
  914. $result['user'] = 'existed';
  915.  
  916. }else{
  917.  
  918. //update collection_data on project
  919. $collection_data = get_field('collection_data', $post_id);
  920. update_field( 'collection_data', ++$collection_data, $post_id);
  921.  
  922. $collection_user[] = [ 'id' => $user->ID , 'avatar'=> $avatar];
  923. update_field( 'collection_user', addslashes(json_encode($collection_user)), $post_id );
  924. $result['user'] = 'appended';
  925.  
  926. }
  927.  
  928. } else {
  929. //collection_user field null
  930.  
  931. update_field( 'collection_data', 1, $post_id);
  932. update_field( 'collection_user', addslashes(json_encode(array([ 'id' => $user->ID, 'avatar' => $avatar]))), $post_id );
  933. $result['user'] = 'created';
  934.  
  935. }
  936.  
  937.  
  938. if( !$collect_post ){
  939.  
  940. $data = array(
  941. 'total' => 1,
  942. 'pid' => array($post_id)
  943. );
  944.  
  945. update_user_meta($user->ID, 'collect_post', json_encode($data));
  946. } else {
  947.  
  948. $curr = json_decode( $collect_post, true);
  949.  
  950. if( !in_array( $post_id, $curr['pid'])){
  951.  
  952. $curr['pid'][] = $post_id;
  953. $data = array(
  954. 'total' => ++$curr['total'],
  955. 'pid' => $curr['pid']
  956. );
  957. update_user_meta($user->ID, 'collect_post', json_encode($data));
  958. }
  959.  
  960. }
  961.  
  962.  
  963.  
  964.  
  965.  
  966. $result['collection_data'] = get_field('collection_data', $post_id);
  967. $result["collection_user"]= json_decode(get_field('collection_user', $post_id), true);
  968.  
  969. $response = new WP_REST_Response( $result);
  970. $response->header( 'Access-Control-Allow-Origin', apply_filters( 'access_control_allow_origin', '*' ) );
  971. $response->header( 'Cache-Control', 'max-age=' . apply_filters( 'api_max_age', WEEK_IN_SECONDS ) );
  972. return $response;
  973. }
  974.  
  975. }
  976.  
  977.  
  978.  
  979.  
  980. //get collection of a user
  981.  
  982. function get_collection( $request ){
  983.  
  984. $user_str = $request['user_id'];
  985.  
  986. if( $user_str && $user = get_user_by('login', $user_str) )
  987. {
  988. $return = array();
  989. $collect_post = get_user_meta($user->ID, 'collect_post', true);
  990.  
  991. if( $collect_post ){
  992.  
  993. $tmp = json_decode($collect_post, true);
  994.  
  995. $return['total'] = $tmp['total'];
  996. $return['project'] = array_map(
  997. function($p){ return array('id' => $p,'title' => get_the_title($p));},
  998. array_unique($tmp['pid'])
  999. );
  1000.  
  1001. }
  1002.  
  1003.  
  1004. $response = new WP_REST_Response( $return);
  1005. $response->header( 'Access-Control-Allow-Origin', apply_filters( 'access_control_allow_origin', '*' ) );
  1006. $response->header( 'Cache-Control', 'max-age=' . apply_filters( 'api_max_age', WEEK_IN_SECONDS ) );
  1007. return $response;
  1008. }else{return ['alex' => 'china'];}
  1009.  
  1010. }
  1011.  
  1012. //comments add function
  1013.  
  1014. function comments_add( $request ){
  1015.  
  1016. $parent = 0;
  1017. $formId = '';
  1018.  
  1019. $post_id = (int)$request['postId'];
  1020. $comment = $request['comment'];
  1021.  
  1022.  
  1023. if( isset($request['userLogin']) ){
  1024. $user_str = $request['userLogin'];
  1025.  
  1026. $user = get_user_by('login', $user_str);
  1027.  
  1028. $user_first_name = get_user_meta($user->ID, 'first_name', true);
  1029. $avatar = get_user_meta($user->ID, 'avatar', true);
  1030. }
  1031.  
  1032. if( isset($request['formId']) && !empty($request['formId'])){
  1033. $formId = $request['formId'];
  1034. }
  1035.  
  1036.  
  1037. if(isset($request['parent'])){
  1038. $parent = (int)$request['parent'];
  1039. }
  1040.  
  1041.  
  1042. $commentdata = array(
  1043. 'comment_post_ID' => $post_id,
  1044. 'comment_author' => $user_first_name,
  1045. 'comment_author_email' => $user_str . '@gmail.com',
  1046. 'comment_author_url' => $avatar,
  1047. 'comment_content' => $comment,
  1048. 'comment_type' => '',
  1049. 'comment_parent' => $parent,
  1050. 'user_id' => $user->ID
  1051. );
  1052.  
  1053. $comment_id = wp_new_comment($commentdata);
  1054.  
  1055. if($comment_id ){
  1056.  
  1057. if($formId){
  1058. add_comment_meta($comment_id, 'formId', $formId, false);
  1059. }
  1060. $return['status'] = "200";
  1061. $return['code'] = "sucess";
  1062. $return['message'] = "comment was created successfully";
  1063. $return['commentId'] = $comment_id;
  1064. }else{
  1065. $return['code'] = 'fail';
  1066. }
  1067.  
  1068. $response = new WP_REST_Response( $return);
  1069. $response->header( 'Access-Control-Allow-Origin', apply_filters( 'access_control_allow_origin', '*' ) );
  1070. $response->header( 'Cache-Control', 'max-age=' . apply_filters( 'api_max_age', WEEK_IN_SECONDS ) );
  1071. return $response;
  1072. }
  1073.  
  1074. // comments get
  1075.  
  1076. function wechat_get_comments( $request){
  1077.  
  1078. $args = $request->get_query_params();
  1079.  
  1080. $p_args = array(
  1081. 'status' => 'approve',
  1082. 'post_type' => 'project'
  1083. );
  1084.  
  1085. $standard = array(
  1086. 'post_id',
  1087. 'parent',
  1088. 'number'
  1089. );
  1090.  
  1091.  
  1092. if( isset($args['user_str']) && !empty($args['user_str']) && username_exists($args['user_str']) ) {
  1093.  
  1094. $user = get_user_by('login', $args['user_str']);
  1095.  
  1096. $p_args['user_id'] = $user->ID;
  1097. }
  1098.  
  1099.  
  1100.  
  1101. foreach( $standard as $st){
  1102. if( isset( $args[$st]) && !empty( $args[$st])){
  1103. $p_args[$st] = $args[$st];
  1104. }
  1105.  
  1106. }
  1107.  
  1108. $result = array();
  1109.  
  1110. //the query
  1111. $comments_query = new WP_Comment_Query;
  1112. $comments = $comments_query->query( $p_args );
  1113.  
  1114. if($comments)
  1115. {
  1116. $result['total'] = count($comments);
  1117.  
  1118. foreach( $comments as $comment){
  1119.  
  1120. if($comment->comment_parent != 0)
  1121. {
  1122. $parent_name = get_parent_name($comment->comment_parent);
  1123. }else{
  1124. $parent_name = '';
  1125. }
  1126.  
  1127. $result['comments'][] = [
  1128. 'author_url' => $comment->comment_author_url,
  1129. 'id' => $comment->comment_ID,
  1130. 'post_id' => $comment->comment_post_ID,
  1131. 'author_name' => $comment->comment_author,
  1132. 'userid' => $comment->user_id,
  1133. 'dateStr' => date('Y-m-d', strtotime($comment->comment_date)),
  1134. 'date' => date('Y-m-d', strtotime($comment->comment_date)),
  1135. 'summary' => $comment->comment_content,
  1136. 'formId' => get_comment_meta( $comment->comment_ID, 'formId', true),
  1137. 'parent_name' => $parent_name,
  1138. 'parent' => $comment->comment_parent
  1139.  
  1140. ];
  1141. }
  1142.  
  1143. }
  1144.  
  1145. $response = new WP_REST_Response( $result);
  1146. $response->header( 'Access-Control-Allow-Origin', apply_filters( 'access_control_allow_origin', '*' ) );
  1147. $response->header( 'Cache-Control', 'max-age=' . apply_filters( 'api_max_age', WEEK_IN_SECONDS ) );
  1148. return $response;
  1149.  
  1150.  
  1151. }
  1152.  
  1153. //return parent author name
  1154.  
  1155. function get_parent_name( $parent_id) {
  1156.  
  1157. global $wpdb;
  1158.  
  1159. $author_name = $wpdb->get_var(
  1160. $wpdb->prepare(
  1161. "SELECT `comment_author` FROM `wp_comments` WHERE `comment_ID` = %d",
  1162. $parent_id)
  1163. );
  1164.  
  1165. return $author_name;
  1166. }

Tags: