Forum Replies Created

Viewing 15 replies - 91 through 105 (of 213 total)
  • Yeah, basic Auth probably should be avoided. You should do some google searching on how how OAuth works before trying to delve into it. I just provided you the basic because that is what your original post was doing. Here is a well laid out, easy to understand explanation of OAuth: http://marktrapp.com/blog/2009/09/17/oauth-dummies/ Good luck.

    Your welcome. If this works for you, you can mark as resolved.

    Ok, your welcome. Apologies for the misinterpretation. Glad to help.

    The previous code was for getting. It is hooking the prepare post method. You kind of come off as whining to me (“this is what [the other guy] wants too” and “just let us…”), maybe I’m just in a bad mood, but I don’t care if I sound mean, so, if you can’t figure out how to get what you are looking for from the gimme code I gave you above, you probably shouldn’t be using this plugin and should instead hire a developer.

    Still, here’s more spoon feeding. You are provided, here, with two ways of retrieving the post’s associated attachment data; get_children and get_posts. Use only one. This is wrapped in the exact same function and hook as previous, just changed the code inside to get the things you needed. Take it and learn from it instead of complaining when it doesn’t exactly fit your needs. I’m trying to gives examples of how to fish, not shove fish down your throat every time you whine about being hungry.

    function playWithMeta($postray, $postdat, $context){
    	 $args = array(
    		'post_parent' => $postdat['ID'],
    		'post_type'   => 'attachment',
    		'posts_per_page' => -1,
    		'post_status' => 'any'
    	);
    	$chilattaches = get_children($args);
    	if($chilattaches){
    		$postray = array_merge($postray, (array)$chilattaches);
    	}
    	$attachments = get_posts( array(
    		'post_type' => 'attachment',
    		'posts_per_page' => -1,
    		'post_parent' => $postdat['ID'],
    		//'exclude'     =>
    	) );
    
    	if($attachments){
    		foreach ( $attachments as $attachment ) {
    			$class = "post-attachment mime-" . sanitize_title($attachment->post_mime_type);
    			$thumbimg = wp_get_attachment_link($attachment->ID, 'thumbnail-size', true);
    			echo '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>';
    		}
    		$postray = array_merge($postray, (array)$attachments);
    	}
    	return $postray;
    }
    
    add_filter( 'json_prepare_post', 'playWithMeta' ,10, 3 );

    1) Out of the box, valid authorization (correct user privileges) must be set before anyone accessing the API can successfully resolve any create/edit/put requests. The same goes with certain get requests.

    2) wp-json/posts/?type=myposttype&page=1&filter[posts_per_page]=1

    Try this:

    http://codex.ww.wp.xz.cn/Function_Reference/wp_set_object_terms

    function assignTaxes($post, $data, $update){
      /*
       Here you would get the terms and taxes from the data var
       $data['my-terms'] $data['my-taxes']
       These would be set in the post params from the sending device
      */
      $terms = array("bluegroup","orangegroup","whitegroup");
      $taxonomy = ("category","custom-tax");
      $append = false; //true = add to, false = replace all existing
       wp_set_object_terms($post['ID'], $terms, $taxonomy, $append);
      //wp_set_object_terms($post['ID'], array_map( 'intval', $data['my-terms'] );, $data['my-taxes']);
      //check for wp error or string if offered wrong term
      //if(is_wp_error($term_taxonomy_ids)){}else{}
    }
    
    add_action( 'json_insert_post', 'assignTaxes');

    Try this:

    function playWithMeta($postray, $postdat, $context){
    	 $morestuff = array("comment_counts" => wp_count_comments($postdat['ID']));
         return array_merge($postray, $morestuff);
    }
    add_filter( 'json_prepare_post', 'playWithMeta' ,10, 3 );

    http://codex.ww.wp.xz.cn/Function_Reference/wp_count_comments

    Just tested and works fine, but image data is coming through by default. Maybe when creating the posts, you are not correctly assigning thumbnail url?

    This relates to
    http://ww.wp.xz.cn/support/topic/custom-meta-data-2?replies=4.

    You can do something like this (untested):

    function playWithMeta($postray, $postdat, $context){
         $imstff = wp_get_attachment_image_src( get_post_thumbnail_id($postdat['ID']), 'thumbnail');
         $morestuff = array("imsrc"=>$imstff[0], "imwid"=>$imstff[1], "imhit"=>$imstff[2]);
         return array_merge($postray, $morestuff);
    }
    add_filter( 'json_prepare_post', 'playWithMeta',10, 3 );

    Thankfully, author has added a good number of hooks in order to allow customization of action, extension and results. I found that I was unable to retrieve a num post count when querying a post type. Because I plan to interface with a mobile app, I want to allow for them to correctly display pagination. In order to do that, they will need to know either how many pages can be made regulated by posts per or how many posts total so they can calculate it themselves. I hooked into post type data to add that information to the result array:

    function send_num_pages_too($data, $type){
    	$added = array();
    	//"publish"]=> string(4) "8417" ["future"]=> int(0) ["draft"]=> int(0) ["pending"]=> int(0) ["private"]=> int(0) ["trash"]=> int(0) ["auto-draft"]=> int(0) ["inherit"]=> int(0)
    	$pcount = wp_count_posts($data['slug'], 'readable');
    	$added['num_posts'] = (int)$pcount->publish;
    	$added['num_private_posts'] = (int)$pcount->private;
    	return array_merge($data, $added);
    }
    add_filter( 'json_post_type_data', 'send_num_pages_too', 10, 2);

    In your guys’ situations, author indicates that with json_prepare_post hook, you can customize the output of your query. He also states that if you pass the param context=post you get all the meta. Here’s the code so you can see that you are getting that (the $post_fields_raw[‘post_meta’] returns almost all meta. if you have not requested raw data, you will not get back serialized values, otherwise, you will)

    if ( 'edit' === $context ) {
    			if ( current_user_can( $post_type->cap->edit_post, $post['ID'] ) ) {
    				if ( is_wp_error( $post_fields_raw['post_meta'] ) ) {
    					return $post_fields_raw['post_meta'];
    				}
    
    				$_post = array_merge( $_post, $post_fields_raw );
    			} else {
    				return new WP_Error( 'json_cannot_edit', __( 'Sorry, you cannot edit this post' ), array( 'status' => 403 ) );
    			}
    		}

    Or if you hook into the json prepare post filter, you can do something like this:

    function playWithMeta($postray, $postdat, $context){
         $morestuff =  get_post_meta($postdat['ID']);
         //don't do this, you will probably be duplicating a bunch of stuff
         return array_merge($postray, $morestuff);
    }
    add_filter( 'json_prepare_post', 'playWithMeta',10, 3 );

    RE: “THERE ARE NO HOOKS WITHIN THE “handle_post_meta_action” function AND THERE SHOULD BE!!!! :). ” I may be incorrect, there are hooks in the get_meta method that might be able to utilize…

    No, it’s not in the documentation. It’s in the code, however. It seems the author did not want to handle post creation alongside media upload and attachment. So, he separated the two requiring one to be done, then the other:

    /**
     * Upload a new attachment
    *
    * Creating a new attachment is done in two steps: uploading the data, then
    * setting the post. This is achieved by first creating an attachment, then
    * editing the post data for it.
    *
    * @param array $_files Data from $_FILES
    * @param array $_headers HTTP headers from the request
    * @return array|WP_Error Attachment data or error
    */

    This is however rather obscure in the code because I do not find anywhere to actually assign the post id to new media.

    I guess there is the ability to update_post_meta($post_id, ‘_thumbnail_id’, $image_id);. So after getting the media data back, you can assign a featured image by updating the post meta data with the previously returned media attachment id.

    You can also hook into the json_insert_post to do some messing around with the data after the post has been created (thank you author for finally adding this needed hook). Keep in mind, though, that this hook fires off AFTER the meta is added and THERE ARE NO HOOKS WITHIN THE “handle_post_meta_action” function AND THERE SHOULD BE!!!! :).

    There are two methods, attach_thumbnail and add_thumbnail_data, neither of which appear to be used anywhere.

    So, you can add some extra fields to your post data, call the hook above and handle your media attachments as you wish, relative to that specific post you are handling. You could extend the custom post type class and do some damage there and on that same thought you can extend the api and create your own class with custom routes and do whatever you want in there. You can then call the media class’ attach_thumbnail method to set a post thumbnail if you want, etc… etc… It’s not already done for you necessarily and it will take a few steps, but it’s doable.

    Author does hook into the auth errors filter, but only to verify nonce in wp cookie auth.

    /**
     * Check for errors when using cookie-based authentication
     *
     * WordPress' built-in cookie authentication is always active for logged in
     * users. However, the API has to check nonces for each request to ensure users
     * are not vulnerable to CSRF.
     *
     * @param WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
     * @return WP_Error|mixed|boolean
     */
    function json_cookie_check_errors( $result ) {
    	if ( ! empty( $result ) ) {
    		return $result;
    	}
    
    	global $wp_json_auth_cookie;
    
    	// Are we using cookie authentication?
    	// (If we get an auth error, but we're still logged in, another
    	// authentication must have been used.)
    	if ( $wp_json_auth_cookie !== true && is_user_logged_in() ) {
    		return $result;
    	}
    
    	// Do we have a nonce?
    	$nonce = null;
    	if ( isset( $_REQUEST['_wp_json_nonce'] ) ) {
    		$nonce = $_REQUEST['_wp_json_nonce'];
    	}
    	elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
    		$nonce = $_SERVER['HTTP_X_WP_NONCE'];
    	}
    
    	if ( $nonce === null ) {
    		// No nonce at all, so act as if it's an unauthenticated request
    		wp_set_current_user( 0 );
    		return true;
    	}
    
    	// Check the nonce
    	$result = wp_verify_nonce( $nonce, 'wp_json' );
    	if ( ! $result ) {
    		return new WP_Error( 'json_cookie_invalid_nonce', __( 'Cookie nonce is invalid' ), array( 'status' => 403 ) );
    	}
    
    	return true;
    }
    add_filter( 'json_authentication_errors', 'json_cookie_check_errors', 100 );

    The plugin author has removed any in code authentication methods and simply put a filter hook; json_authentication_errors. So, handling authentication is up to you. If you want to use oAuth, there is a plugin/extension for this json rest api that handles most of the code for you. https://github.com/WP-API/WP-API/blob/master/docs/authentication.md

    I use the basic auth like so:

    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json", "Accept:application/json", 'Authorization:Basic '. base64_encode($username.":".$password)));

    To hook into the filter, you would do something like this:

    function MineCheckAuth(){
    //do check auth stuff, basic authentication in the headers will be
    //stored in either the
    //$_SERVER["REMOTE_AUTHORIZATION"] global or
    //$_SERVER["REDIRECT_REMOTE_AUTHORIZATION"]
    
    //log user in if good
    
    return true; //or return wp_error
    //neither will do anything but he states that these are the two valid return values.
    }
    add_filter('json_authentication_errors', 'MineCheckAuth');
Viewing 15 replies - 91 through 105 (of 213 total)