Forum Replies Created

Viewing 8 replies - 1 through 8 (of 8 total)
  • Thread Starter bassius

    (@bassius)

    I managed to get it to work with the following code:

    add_action( 'rest_api_init', function () {
        register_rest_field( 'lv_listing', 'meta', array(
            'get_callback' => function( $data ) {
                $listing_obj = get_post_meta( $data['id'], '', false );
                return $listing_obj;
            },
            'update_callback' => function($value, $listing_obj, $field_name ) {
                foreach ($value as $key => $value) {
                    #post id to link meta to
                    error_log($listing_obj->ID);
                    #name of the meta field to update/add
                    error_log($key);
                    #value of the meta field
                    error_log($value);
                    update_post_meta($listing_obj->ID, $key, $value);
                }
                return true;
            },
             'schema' => null,
        ) );
    } );
     

    With this code however I am only able to create meta fields that contain 1 value. When I send an array for each meta field, it results in a 400 – Bad Request, probably because the function can’t handle multiple values per meta item.

    On the other hand I don’t think that I need to be able to handle two values per meta object, although this wordpress theme returns two values when I use the GET function.

    I’ve tested my code and so far I can achieve what I wanted to achieve 🙂

    Thread Starter bassius

    (@bassius)

    Hey bcworkz,

    The problem indeed seems to be in the array, but I can’t figure out how to fix this. The 500 was caused by a typo. I fixed that.

    This is the function.php after modifying it according to the example for the comment / karma.

    add_action( 'rest_api_init', function () {
        register_rest_field( 'lv_listing', 'meta', array(
            'get_callback' => function( $data ) {
                $listing_obj = get_post_meta( $data['id'], '', false );
                return $listing_obj;
            },
            'update_callback' => function($value, $listing_obj, $field_name ) {         
                $ret = update_post_meta($listing_obj->ID, $field_name, $value);
                if ( false === $ret ) {
                    return new WP_Error(
                      'rest_update_meta_failed',
                      __( 'Failed to update metadata.' ),
                      array( 'status' => 500 )
                    );
                }
                return true;
            },
             'schema' => null,
        ) );
    } );

    As you already mentioned, I need to save all the data as individual values. If I now make a call with the above register_rest_field, with multiple meta objects in an array, it responds for the meta field like this:

    "meta": {
            "meta": ["a:1:{i:0;a:3:{s:14:\"lv_listing_lat\";a:1:{i:0;s:9:\"50.996727\";}s:14:\"lv_listing_lng\";a:1:{i:0;s:9:\"5.9249742\";}s:9:\"_linkedin\";a:1:{i:0;s:19:\"http:\/\/www.test.com\";}}}"]
        },

    As you can see everything is put into one object called ‘meta’ as one large value. I was expecting the “field_name” variable to always have the name of the object (as I am working in an array – correct?), but field_name always has the value ‘meta’.

    Should I now call the ‘register_rest_field’ in a for each loop then?

    Thread Starter bassius

    (@bassius)

    Hi bcworkz and thanks for responding.

    I’ve just added an update_callback and all that based on some other how-to from stackexchange and it now looks like this:

    function rest_api_lv_listing_meta() {
        register_rest_field('lv_listing', 'meta', array(
                'get_callback' => 'get_lv_listing_meta',
               'update_callback' => 'update_lv_listing_meta',
               'schema' => null,
            )
        );
    }
    
    function get_lv_listing_meta($object) {
        $postId = $object['id'];
    
        return get_post_meta($postId);
    }
    
    function update_lv_listing_meta($meta, $post) {
        $postId = $post->ID;
    
        foreach ($meta as $data) {
            update_post_meta($postId, $data['key'], $data['value']);
        }
    }
    
    add_action('rest_api_init', 'rest_api_lv_listing_meta');

    If there is meta available for the post type, it is shown in the JSON GET.

    If i now however do this POST request:

    {	
    "status": "publish",	
    "title":  "Homegrown",	
    "content": "<p>Quisque</p>" ,
    "excerpt": "<p>Quisque vel sem ac enim facilisis ultrices. Vivamus neque sapien]<\/p>\n",	
    "comment_status": "closed",		
    "listing_amenities": [420, 421, 422, 448, 449],	
    "listing_category": [419,  430], 	
    "listing_location": [459], 
    "listing_keyword": [349, 350, 352, 362],	
    "meta": {		
      "lv_listing_lng": ["-0.146984374219"],		
      "lv_listing_lat": ["51.5167522444"],		
      "_phone2": ["207-2363-4657"],
      "_address": ["14 Sample St. London 316"], 
      "_email": ["[email protected]"],		
      "_website": ["http:\/\/javothemes.com\/javo-spot"]	
     }
    } 

    For a minute I thought it was related to multiple “values” per each meta item, but after removing them (as in the example above) it still doesn’t work.

    The response I get to my POST request is this, where the meta array is shown as empty.

    {
        "data": {
            "id": 10583,
            "date": "2018-03-31T18:54:06",
            "date_gmt": "2018-03-31T18:54:06",
            "guid": {
                "rendered": "http://mywebsite.com/listing/homegrown-3/",
                "raw": "http://mywebsite.com/listing/homegrown-3/"
            },
            "modified": "2018-03-31T18:54:06",
            "modified_gmt": "2018-03-31T18:54:06",
            "password": "",
            "slug": "homegrown-3",
            "status": "publish",
            "type": "lv_listing",
            "link": "http://mywebsite.com/listing/homegrown-3/",
            "title": {
                "raw": "Homegrown",
                "rendered": "Homegrown"
            },
            "content": {
                "raw": "<p>Quisque</p>",
                "rendered": "<p>Quisque</p>
    ",
                "protected": false
            },
            "excerpt": {
                "raw": "<p>Quisque vel sem ac enim facilisis ultrices. Vivamus neque sapien]</p>
    ",
                "rendered": "<p>Quisque vel sem ac enim facilisis ultrices. Vivamus neque sapien]</p>
    ",
                "protected": false
            },
            "author": 2,
            "featured_media": 0,
            "comment_status": "closed",
            "ping_status": "closed",
            "template": "",
            "listing_amenities": [
                420,
                421,
                422,
                448,
                449
            ],
            "listing_category": [
                419,
                430
            ],
            "listing_location": [
                459
            ],
            "listing_keyword": [
                349,
                350,
                352,
                362
            ],
            "meta": []
        },
        "headers": {
            "Location": "http://mywebsite.com/wp-json/wp/v2/lv_listing/10583",
            "Allow": "GET, POST"
        },
        "status": 201
    }

    Any quick hints on what I’m doing wrong? I suspect something is up with the update_post_meta statement that I’ve made there and i’m wondering whether or not it should be an array. Unfortunately my PHP skills really aren’t that good to get the syntax correct. I tried making some changes to it based on the official WP API example you linked earlier but that just ends up with an internal server error :/.

    • This reply was modified 8 years, 2 months ago by bassius.
    Thread Starter bassius

    (@bassius)

    Hi,

    Thanks for that, but I already figured some of it out myself.

    Do you have any idea why WordPress assigns the #main img { } to a thumbnail ? I guess it is a bit of a mix between #main img and .thumb.

    I modified the PHP syntax and renamed the class for thumbnails to “thumb”, but once I add a margin to that class it does not work. Borders however do work?

    Once I edit the #main img div and give that some margin, it works but I can’t see where in the PHP a thumbnail should get that div ?

    Thread Starter bassius

    (@bassius)

    Thanks for that then 🙂

    Could you tell me how I can style the thumbnail element in CSS? Apparently I do not need to make a seperate PHP line in the index.php, which causes me to not have a seperate div for the thumbs.

    Thread Starter bassius

    (@bassius)

    Also I am using the ‘Featured Content Gallery’ plugin, but when deactivating that plugin I still do not get the option “Post Thumbnail”.

    Thread Starter bassius

    (@bassius)

    Yes, and it doesn’t give me the option to enable thumbnails. What I can check there is:

    – Categories
    – Post
    – Tags
    – kandidaat (taxonomy)
    – Featured Image
    – WP Calendar Event
    – Excerpt
    – Send Trackbacks
    – Custom Fields
    – Discussion Comments
    – Slug
    – Author
    – Revisions

    Featured image is not the correct one if im right.

    Thread Starter bassius

    (@bassius)

    I’ve tried various options, but this in my current functions.php

    <?php
    if ( function_exists('register_sidebars') )
    register_sidebars(1);
    
    function kandidaat_init() {
      register_taxonomy(
        'kandidaat',
        'post',
        array(
          'label' => __('kandidaat'),
          'rewrite' => array('slug' => 'profiles'),
        )
      );
    }
    add_action( 'init', 'kandidaat_init' ); 
    
    add_theme_support( 'post-thumbnails' );
    set_post_thumbnail_size( 200, 200, true ); // Normal post thumbnails
    add_image_size( 'single-post-thumbnail', 400, 9999 ); // Permalink thumbnail size
    
    ?>

    What I’m using the functions.php for:

    – loading sidebar
    – create one or more taxonomies
    – load thumbnails

Viewing 8 replies - 1 through 8 (of 8 total)