【问题标题】:Enabling Custom Fields in Wordpress REST API Custom Endpoint在 Wordpress REST API 自定义端点中启用自定义字段
【发布时间】:2017-04-02 06:49:01
【问题描述】:

我为我们正在制作的应用程序的首页创建了一个自定义 REST API 端点,以便它将根据帖子类型返回 3 个自定义查询,而不是为每种帖子类型发出 3 个不同的 HTTP 请求,但无法确定了解如何获取要显示的每个帖子的自定义字段。不知道下一步该去哪里:

    class Home_Custom_Route extends WP_REST_Controller {
        /**
         * Register the routes for the objects of the controller.
         */
        public function my_register_routes() {
            $version = 'v2';
            $namespace = 'wp/' . $version;
            $base = 'home';
            register_rest_route( $namespace, '/' . $base, array(
                array(
                    'methods'         => WP_REST_Server::READABLE,
                    'callback'        => array( $this, 'get_items' ),
                    'permission_callback' => array( $this, 'get_items_permissions_check' ),
                    'args'            => array(

                    ),
                ),
            ) );
            register_rest_route( $namespace, '/' . $base . '/schema', array(
                'methods'         => WP_REST_Server::READABLE,
                'callback'        => array( $this, 'get_public_item_schema' ),
            ) );
        }

        /**
         * Get a collection of items
         *
         * @param WP_REST_Request $request Full data about the request.
         * @return WP_Error|WP_REST_Response
         */
        public function get_items( $request ) {
                $eventargs = array(
                    'post_type'      => 'event',
                    'posts_per_page' => 3,
                    'meta_key'       => 'wpcf-event-start',
                    'meta_value'     => current_time( 'timestamp', 1 ),
                    'meta_compare'   => '<=',
                );
                $main_events = new WP_Query( $eventargs );

                $listingargs = array(
                    'post_type'      => 'listings',
                    'posts_per_page' => 3,
                    'orderby'        => 'date',
                    'order'          => 'DESC',
                );
                $main_listings = new WP_Query( $listingargs );

                $ticketsargs = array(
                    'post_type'      => 'product',
                    'posts_per_page' => 3,
                    'orderby'        => 'date',
                    'order'          => 'DESC',
                    'tax_query'      => array(
                        array(
                            'taxonomy'  => 'product_cat',
                            'field'     => 'slug',
                            'terms'     => 'tickets',
                        )
                    ),

                );
                $main_tickets = new WP_Query( $ticketsargs );

                $data = array(
                    'events'    =>  $main_events->posts,
                    'listings'  =>  $main_listings->posts,
                    'tickets'   =>  $main_tickets->posts,
                );
                return new WP_REST_Response( $data, 200 );
        }

        /**
         * Get one item from the collection
         *
         * @param WP_REST_Request $request Full data about the request.
         * @return WP_Error|WP_REST_Response
         */
        public function get_item( $request ) {
            //get parameters from request
            $params = $request->get_params();
            $item = array();//do a query, call another class, etc
            $data = $this->prepare_item_for_response( $item, $request );

            //return a response or error based on some conditional
            if ( 1 == 1 ) {
                return new WP_REST_Response( $data, 200 );
            }else{
                return new WP_Error( 'code', __( 'Couldnt find it', 'xxx' ) );
            }
        }
        /**
         * Check if a given request has access to get items
         *
         * @param WP_REST_Request $request Full data about the request.
         * @return WP_Error|bool
         */
        public function get_items_permissions_check( $request ) {
            return true; //<--use to make readable by all
        }
        /**
         * Check if a given request has access to get a specific item
         *
         * @param WP_REST_Request $request Full data about the request.
         * @return WP_Error|bool
         */
        public function get_item_permissions_check( $request ) {
            return $this->get_items_permissions_check( $request );
        }

        /**
         * Prepare the item for the REST response
         *
         * @param mixed $item WordPress representation of the item.
         * @param WP_REST_Request $request Request object.
         * @return mixed
         */
        public function prepare_item_for_response( $item, $request ) {
/*pretty sure this is where custom fields are enabled, but not sure how to do that*/
        }
    }

【问题讨论】:

    标签: php json wordpress wordpress-rest-api


    【解决方案1】:

    我发现了如何使用 get_post_meta 来解决这个问题,但我的答案在每个查询中执行了多次调用,因此它可能会被优化为首先拉取所有帖子元,然后只获取我需要的字段。

    public function get_items( $request ) {
            $eventargs = array(
                'post_type'      => 'event',
                'posts_per_page' => 3,
                'meta_key'       => 'wpcf-event-start',
                'meta_value'     => current_time( 'timestamp', 1 ),
                'meta_compare'   => '<=',
            );
            $main_events = new WP_Query( $eventargs );
            $events = $main_events->posts;
            foreach($events as $event) {
                foreach( array( 'wpcf-event-start', 'wpcf-event-end', 'wpcf-event-website' ) as $field ){
                    $event->$field = get_post_meta( $event->ID, $field, true );
                }
            }
    
            $listingargs = array(
                'post_type'      => 'listings',
                'posts_per_page' => 3,
                'orderby'        => 'date',
                'order'          => 'DESC',
            );
            $main_listings = new WP_Query( $listingargs );
            $listings = $main_listings->posts;
            foreach($listings as $listing) {
                foreach( array( 'wpcf-listing-hours', 'wpcf-correct-address', 'wpcf-total-ratings', 'wpcf-average-rating' ) as $field ){
                    $listing->$field = get_post_meta( $listing->ID, $field, true );
                }
            }
    
            $ticketsargs = array(
                'post_type'      => 'product',
                'posts_per_page' => 3,
                'orderby'        => 'date',
                'order'          => 'DESC',
                'tax_query'      => array(
                    array(
                        'taxonomy'  => 'product_cat',
                        'field'     => 'slug',
                        'terms'     => 'tickets',
                    )
                ),
    
            );
            $main_tickets = new WP_Query( $ticketsargs );
            $tickets = $main_tickets->posts;
            foreach($tickets as $ticket) {
                foreach( array( '_price', '_stock', '_stock_status' ) as $field ){
                    $ticket->$field = get_post_meta( $ticket->ID, $field, true );
                }
            }
    
            $data = array(
                'events'    =>  $events,
                'listings'  =>  $listings,
                'tickets'   =>  $tickets,
            );
            return new WP_REST_Response( $data, 200 );
    }
    

    【讨论】:

      【解决方案2】:

      帖子查询数据不会拉取自定义字段,它只是拉取原始帖子数据。你必须使用get_post_meta()

      但是,由于您正在创建 REST API 端点,因此最好执行自定义 $wpdb 查询。

      <?php 
         $querystr = "
            SELECT $wpdb->posts.*, $wpdb->postmeta.* 
            FROM $wpdb->posts, $wpdb->postmeta
            WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
            AND $wpdb->posts.post_status = 'publish' 
            AND $wpdb->posts.post_type = 'event'
            ORDER BY $wpdb->posts.post_date DESC 
         ";
      
         $events = $wpdb->get_results($querystr, OBJECT);
      ?>
      

      您只需将 'event' 替换为您想要使用的任何 post_type。

      【讨论】:

      • 我试过这个,它返回了 38,000 行代码和很多重复的帖子。我们将如何使用 get_post_meta 来简单地添加到查询响应中呢?我对此比较熟悉
      • &lt;?php $querystr = " SELECT $wpdb-&gt;posts.*, $wpdb-&gt;postmeta.* FROM $wpdb-&gt;posts LEFT JOIN $WPDB-&gt;postsmeta ON $wpdb-&gt;posts.ID = $wpdb-&gt;postmeta.post_id WHERE $wpdb-&gt;posts.post_status = 'publish' AND $wpdb-&gt;posts.post_type = 'event' ORDER BY $wpdb-&gt;posts.post_date DESC "; $events = $wpdb-&gt;get_results($querystr, OBJECT); ?&gt;
      • 左加入应该停止重复。
      • 这一次似乎只是转储了一堆临时数据,例如“Wordpress 有一个新的更新可用”,而不是发布数据。到目前为止,我非常感谢您的帮助!我已经找到了如何使自定义字段可用于每个帖子,但我这样做的方式仅使这些字段可用,而不是常规字段,例如帖子 ID 等,除非我将所有这些字段添加到数组中,这似乎效率低下
      • 在参数code $main_events = new WP_Query( $eventargs ); $events = $main_events-&gt;get_posts(); $return = array(); foreach($events as $event) { $newPost = array(); foreach( array( 'wpcf-event-start', 'wpcf-event-end', 'wpcf-event-website' ) as $field ){ $newPost[str_replace('-', '_', $field)] = get_post_meta( $event-&gt;ID, $field, true ); } $return[] = $newPost; }之后
      猜你喜欢
      • 2020-09-01
      • 2017-10-29
      • 2020-07-23
      • 2014-05-06
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-14
      相关资源
      最近更新 更多