Skip Navigation

[Resolved] Relationship in api rest

This thread is resolved. Here is a description of the problem and solution.

Problem: I would like to add related parent post information to the response of a REST API endpoint for the child post type.

Solution: Use the following custom code as a guide for adding related post information in a custom registered field in your REST API response for the child post type:

add_action( 'rest_api_init', 'create_api_posts_meta_field_promociones');
     
function create_api_posts_meta_field_promociones() {
    register_rest_field( 'promociones', 'parent-page', array(
           'get_callback'    => 'get_parent_page_for_api_promociones',
           'schema'          => null,
        )
    );
}

function get_parent_page_for_api_promociones( $object ) {
    //get the id of the post object array
    $post_id = $object['id'];
    //return the related comercio post ID
    return toolset_get_related_post( $post_id, 'comercio_promocion', 'parent');
}

Relevant Documentation:
https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/#toolset_get_related_post
https://developer.wordpress.org/reference/functions/register_rest_field/

This support ticket is created 3 years, 11 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

This topic contains 21 replies, has 2 voices.

Last updated by avansisI-2 3 years, 11 months ago.

Assisted by: Christian Cox.

Author
Posts
#1846455

In relation to this topic
https://toolset.com/forums/topic/relationship-in-api-rest/

If I want to create other relationship, How i can add action?
If I repeat this code with other custom type 'promociones' said its not posible because

I think they should be done separately, don't you?

But it's wrong

//AÑADIR RELATIONSHIPS PROMOCIONES
add_action( 'rest_api_init', 'create_api_posts_meta_field');
  
function create_api_posts_meta_field() {
    register_rest_field( 'promociones', 'parent-page', array(
           'get_callback'    => 'get_parent_page_for_api',
           'schema'          => null,
        )
    );
}
  
function get_parent_page_for_api( $object ) {
    //get the id of the post object array
    $post_id = $object['id'];
    //return the post meta
    return toolset_get_related_post( $post_id, 'promociones');
}
 
//AÑADIR RELATIONSHIPS BONOS
add_action( 'rest_api_init', 'create_api_posts_meta_field');
  
function create_api_posts_meta_field() {
    register_rest_field( 'bonos', 'parent-page', array(
           'get_callback'    => 'get_parent_page_for_api',
           'schema'          => null,
        )
    );
}
  
function get_parent_page_for_api( $object ) {
    //get the id of the post object array
    $post_id = $object['id'];
    //return the post meta
    return toolset_get_related_post( $post_id, 'bonos');
}

Could you help me?

Thanks

#1846613

Hi, you must use unique function names in PHP to prevent a Fatal Error. So you can update the second repetition of code like this:

//AÑADIR RELATIONSHIPS BONOS
add_action( 'rest_api_init', 'create_api_posts_meta_field_bonos');
   
function create_api_posts_meta_field_bonos() {
    register_rest_field( 'bonos', 'parent-page', array(
           'get_callback'    => 'get_parent_page_for_api_bonos',
           'schema'          => null,
        )
    );
}
   
function get_parent_page_for_api_bonos( $object ) {
    //get the id of the post object array
    $post_id = $object['id'];
    //return the post meta
    return toolset_get_related_post( $post_id, 'bonos');
}

Try this update first, and if it does not work as expected we can dig a bit deeper.

#1846673

Great! It's work.

In case the custom type bonus should appear in the profile of the user who created it and in the json. how should it be done?

#1846681

I'm not sure I understand. Do you want a list of Bonus posts to appear in the User's profile at /wp-admin/user-edit.php?user_id=12345, for example, or in the Author archive for a User at /author/username?

Which JSON are you referring to, exactly?

#1846683

Yes, the user "creates" his coupon, and is then referenced in his user data. I need to be able to send the coupon number and expiry date of that coupon with the user's json by API REST

#1846685
#1846703

Maybe doesnt work.

wp-json/wp/v2/promociones, in this json parent-page is 0 and this 'promociones' its depend one 'comercio', with bonos is the same. (wp-json/wp/v2/bonos)

Could you help me?

thanks

Code is yours in bonos and this in promociones

//AÑADIR RELATIONSHIPS PROMOCIONES
add_action( 'rest_api_init', 'create_api_posts_meta_field_promociones');
    
function create_api_posts_meta_field_promociones() {
    register_rest_field( 'promociones', 'parent-page', array(
           'get_callback'    => 'get_parent_page_for_api_promociones',
           'schema'          => null,
        )
    );
}
    
function get_parent_page_for_api_promociones( $object ) {
    //get the id of the post object array
    $post_id = $object['id'];
    //return the post meta
    return toolset_get_related_post( $post_id, 'promociones');
}

#1847537

It sounds like you must first determine which 'comercio' post is created by the User, so you can use that 'comercio' post ID in the toolset_get_related_post API. Therefore, you must query the User's 'comercio' posts in your custom code using WP_Query to determine the 'comercio' post ID. You probably cannot access the 'comercio' post ID directly in the $object parameter in the User profile.

function get_parent_page_for_api_promociones( $object ) {
    // you should use WP_Query here to determine which post ID is the correct 'comercio' post
    // access the current User for WP_Query
    global $current_user; 
    $author_id = $current_user->ID;
    $comercio_query = new WP_Query( array( 'author' => $author_id , 'post_type' => 'comercio', 'posts_per_page' => -1) );
    //...your code should access the comercio post ID in the query results then use that post ID in the toolset_get_related_post API call...

See WP_Query author params here for more examples: https://developer.wordpress.org/reference/classes/wp_query/#author-parameters

#1847615

in the case of 'promociones' it does hang from 'comercios', as a parent. But it does not have to be associated with an author.

And the code introduced gives me parent 0.

In the case of 'bonos', it must be related to the author.

Can we solve first the 'promociones' one?

Thanks!

#1847639

Okay I think I understand better now. You want to access the 'comercio' post that is a child of the current 'promociones' post, correct? The toolset_get_related_post API expects you to pass in the child post slug 'comercio' and the relation 'child' in the 3rd parameter, like this:

function get_parent_page_for_api_promociones( $object ) {
    //get the id of the post object array
    $post_id = $object['id'];
    //return the post meta
    return toolset_get_related_post( $post_id, 'comercio', 'child');
}

https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/#toolset_get_related_post

This API should be used if there is only 1 child comercio post. For complex cases where more than 1 comercio child exists for any given promociones post, you must use the API toolset_get_related_posts: https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/#toolset_get_related_posts
The syntax is a bit different as you can see in the documentation.

#1847661

On the contrary, promociones is the child of comercios.
but if i add this code

//AÑADIR RELATIONSHIPS PROMOCIONES
add_action( 'rest_api_init', 'create_api_posts_meta_field_promociones');
     
function create_api_posts_meta_field_promociones() {
    register_rest_field( 'promociones', 'parent-page', array(
           'get_callback'    => 'get_parent_page_for_api_promociones',
           'schema'          => null,
        )
    );
}
     
function get_parent_page_for_api_promociones( $object ) {
    //get the id of the post object array
    $post_id = $object['id'];
    //return the post meta
    return toolset_get_related_post( $post_id, 'promociones');
}

Parent is 0

#1847675

Okay in that case the 'promociones' slug should be changed to 'comercio' since you want to get the 'comercio' post ID by querying with a known 'promociones' child post ID:

return toolset_get_related_post( $post_id, 'comercio');

The default 3rd parameter is 'parent', so that parameter can be omitted as shown above.

If this is not working as expected, please use error_log and logging to output the $object variable for inspection:

    // ...
    //get the id of the post object array
    $post_id = $object['id'];
    error_log('object: ');
    error_log(print_r( $object, true)) ;
    //return the post meta
    // ...

If you are not familiar with error logging, I can show you how to active a log temporarily. Go in your wp-config.php file and look for

define('WP_DEBUG', false);

Change it to:

define('WP_DEBUG', true);

Then add these lines, just after the WP_DEBUG line:

define('WP_DEBUG_LOG', dirname(__FILE__) . '/error_log.txt');
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );
define('WP_DISABLE_FATAL_ERROR_HANDLER',true);

Reload the User JSON data. This should create an error_log.txt file in your site's root directory. Use FTP to look for this file in the same directory as wp-config.php. You may need to click "Refresh" in your FTP browser to see a new file appear. Please download this file to your computer, open it in any text editing software, and send me its contents. Once that is done, you can revert the changes you made to wp-config.php and delete the log file using FTP.

#1847689

does not appear in the json
you can see it here
hidden link

I add this code...

 
//AÑADIR RELATIONSHIPS PROMOCIONES
add_action( 'rest_api_init', 'create_api_posts_meta_field_promociones');
    
function create_api_posts_meta_field_promociones() {
    register_rest_field( 'promociones', 'parent-page', array(
           'get_callback'    => 'get_parent_page_for_api_promociones',
           'schema'          => null,
        )
    );
}
    
function get_parent_page_for_api_promociones( $object ) {
    //get the id of the post object array
    $post_id = $object['id'];
    //return the post meta
    return toolset_get_related_post( $post_id, 'comercio');
}

I dont know if i have to put 'comercio' or 'comercios'

#1847729

It should be the slug of the 'comercio' post type, which you can find in Toolset > Post Types if it was created in Toolset Types. I can do some troubleshooting if you provide an admin login and FTP access in the private reply fields here.

#1848959

Okay I have made an adjustment in your child theme's functions.php file. Here is the working code for determining the parent comercios post in the promociones rest response JSON:

function get_parent_page_for_api_promociones( $object ) {
    //get the id of the post object array
    $post_id = $object['id'];
    //return the related comercio post ID
    return toolset_get_related_post( $post_id, 'comercio_promocion', 'parent');
}

Here is an example response:

[
  {
    "id": 5193,
    "date": "2020-11-15T01:43:47",
    "date_gmt": "2020-11-15T01:43:47",
    "guid": {
      "rendered": "***/?post_type=promociones&p=5193"
    },
    "modified": "2020-11-15T01:43:48",
    "modified_gmt": "2020-11-15T01:43:48",
    "slug": "promocion-1",
    "status": "publish",
    "type": "promociones",
    "link": "***/promociones/promocion-1/",
    "title": {
      "rendered": "Promoción 1"
    },
    "content": {
      "rendered": "",
      "protected": false
    },
    "template": "",
    "uagb_featured_image_src": [],
    "uagb_author_info": {
      "display_name": "user",
      "author_link": "***/author/"
    },
    "uagb_comment_info": 0,
    "uagb_excerpt": null,
    "parent-page": 4645,
    "toolset-meta": {
      "grupo-de-campo-para-promociones": {
        "promocion": {
          "type": "textfield",
          "raw": "Promoción 1"
        },
        "descripcion_promocion": {
          "type": "wysiwyg",
          "raw": ""
        },
        "imagen_promocion": {
          "type": "image",
          "raw": "***/wp-content/uploads/2020/11/las_rozas_market_logo.png",
          "attachment_id": 5083
        },
        "fecha_promocion": {
          "type": "date",
          "raw": "1606521600",
          "formatted": "November 28, 2020"
        }
      }
    },
    "_links": {
      "self": [
        {
          "href": "***/wp-json/wp/v2/promociones/5193"
        }
      ],
      "collection": [
        {
          "href": "***/wp-json/wp/v2/promociones"
        }
      ],
      "about": [
        {
          "href": "***/wp-json/wp/v2/types/promociones"
        }
      ],
      "version-history": [
        {
          "count": 1,
          "href": "***/wp-json/wp/v2/promociones/5193/revisions"
        }
      ],
      "predecessor-version": [
        {
          "id": 5194,
          "href": "***/wp-json/wp/v2/promociones/5193/revisions/5194"
        }
      ],
      "wp:attachment": [
        {
          "href": "***/wp-json/wp/v2/media?parent=5193"
        }
      ],
      "curies": [
        {
          "name": "wp",
          "href": "<em><u>hidden link</u></em>{rel}",
          "templated": true
        }
      ]
    }
  }
]

ID 4645 corresponds to the parent comercio post of the promociones post 5193, so it appears to be working. You can use this as a guide for updating the bonos endpoint as well. Let me know if you have questions about this.