WP REST-API create posts with custom fields generated by CPT - wordpress

I used the CPT to create a post type UserQuestion with a few fields, such as ip_data. I want to be able to create one of this posts through API. So I looked into WP REST API .
However, the API offers /v2/user_question:
{
"title" : "test2",
"slug": "user_question",
"status": "publish",
"post_type": "user_question",
"meta": {
"ip" : "1111",
"question": "test question",
"answer": "yes, the answer"
}
}
The post is created, but it's not updating the customized fields data.
How should I make the request?

add_action("rest_insert_user_question", function (\WP_Post $post, $request, $creating)
{
$metas = $request->get_param("meta");
if (is_array($metas)) {
foreach ($metas as $name => $value) {
//update_post_meta($post->ID, $name, $value);
update_field($name, $value, $post->ID);
}
}
}, 10, 3);
In your functions.php (or in your plugin) add the above add_action and function. Change the 'user_question' in the add_action to match your post type, for example "rest_insert_portfolio" for a portfolio post type. Use update_field if you're using Advanced Custom Fields or update_post_meta if you're using regular custom fields.

Related

How to display a custom field in the dashboard posts list( replacing the title )

I'm using WordPress and I did create a custom post type with several custom fields ( using ACV, advanced custom fields )
I have hidden all the basic WordPress fields like title, content editor thumbnails, etc, etc so I leave just my custom fields for the creation of a new post.
Since the title is not filled at the creation of the post, I get a list of post with every title set as “auto draft”
The thing that I don't want obviously.
My question is simple :
Is it possible and if yes how to replace the title with one of my custom fields in the dashboard post list.
I searched everywhere but I couldn't find an answer.
Sorry for my English, it’s not my native tongue, I hope You understand what I basically want to do.
Thanks for your time to read my question.
Have a good day
I managed to find a solution myself.
Let us say that you have a custom post type named "test" with 3 custom fields named one, two and three. And you want to remove the title and the date, show the content of one, two, and three in the post list table.
First you have to create a function that removes the title and the date, and also creates the new columns.
function custom_columns($columns)
{
unset($columns['title']);
unset($columns['date']);
return array_merge(
$columns,
array(
'one' => __('One'),
'two' => __('Two'),
'three' => __('Three')
)
);
}
add_filter('manage_test_posts_columns', 'custom_columns');
Then you need to display the custom field content in the post list table:
function display_custom_columns($column, $post_id)
{
switch ($column) {
case 'one':
echo get_post_meta($post_id, 'one', true);
break;
case 'two':
echo get_post_meta($post_id, 'two', true);
break;
case 'three':
echo get_post_meta($post_id, 'three', true);
break;
}
}
add_action('manage_test_posts_custom_column', 'display_custom_columns', 10, 2);
Further reading
You can use wp_insert_post_data to accomplish the desired functionality. This action is triggered when a post is created or updated.
add_action( 'wp_insert_post_data', 'my_updated_title', 99, 1 );
function my_updated_title( $data ) {
// If this is just a revision, don't update title.
if ( wp_is_post_revision( $data['ID'] ) ) {
return;
}
// Set the post title to your custom field value
$data['post_title'] = get_field( 'your_acf_field', $data['ID'] );
// Return the updated post data
return $data;
}

Add Post Meta Fields via WP API v2

I'm trying to play with the WP API v2 and insert posts from Postman.
If I post this raw request, it creates a post just fine:
{
"title": "Test Title",
"content": "Test Content",
}
However, I'm trying to add some custom field values to this as well, and I can't seem to get them to work. This request creates a post, but doesn't add any meta fields:
{
"title": "Test Title",
"content": "Test Content",
"meta": {
"foo": "bar",
"foo2": "bar2"
}
}
How do I POST the meta fields foo and foo2 with the values bar and bar2 through the API endpoint https://my-site.com/wp-json/wp/v2/posts?
Edit: It also appears custom fields don't get pulled natively in GET requests. I put this code in a mu-plugin:
add_filter( 'rest_prepare_post', 'xhynk_api_post_meta', 10, 3 );
function xhynk_api_post_meta( $data, $post, $context ){
$meta = get_post_custom( $post->ID );
if( $meta ) {
$data->data['meta'] = $meta;
}
return $data;
}
Which at least lets me view it on a GET request. However I still can't seem to get it to POST via Postman. Even adding "status": "publish" will cause the new post to publish instead of being a draft like it is by default. Are there any hooks or filters I can use on API POST requests to make sure the custom fields are added?
to handle metas on insertion and update, you can do it with action rest_insert_ + post type
add_action("rest_insert_page", function (\WP_Post $post, $request, $creating) {
$metas = $request->get_param("meta");
if (is_array($metas)) {
foreach ($metas as $name => $value) {
update_post_meta($post->ID, $name, $value);
}
}
}, 10, 3);

Wordpress Rest API

Is it possible to access pluggin's data from WordPress database with some Rest API. I saw WP REST API but it doesn't give access to pluggin's data.
More specifically I use LearnDash pluggin and I want to access courses infos but they doesn't provide any API to access it.
Thanks
Overall you need to search Google for things having to do with "Wordpress rest api custom post type" and eventually you'll be dealing with registering custom post types and endpoints in your theme's functions.php
Here is the manual: https://developer.wordpress.org/rest-api/extending-the-rest-api
As an example, here is my situation: I'm using WordPress (4.7) and The Events Calendar ("TEC") plugin. I'm querying the WP DB from an Android app using the REST API, however the only data that's available to REST is basic WP post stuff. I need to expose the custom data in the TEC plugin to the REST API. In order to do that, I've included the following into my functions.php in my theme:
functions.php
/* Exposing the custom post type of the plugin to the REST API.
* In this case, for The Tribe Events Calendar plugin, the custom post type is
* "tribe_events". For other plugins it will be different. */
add_action( 'init', 'my_custom_post_type_rest_support', 25 );
function my_custom_post_type_rest_support() {
global $wp_post_types;
//be sure to set this to the name of your post type!
$post_type_name = 'tribe_events';
if( isset( $wp_post_types[ $post_type_name ] ) ) {
$wp_post_types[$post_type_name]->show_in_rest = true;
$wp_post_types[$post_type_name]->rest_base = $post_type_name;
$wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
}
}
/* Exposing the custom taxonomy of the plugin to the REST API.
* In this case, for The Tribe Events Calendar plugin, the custom
* taxonomy is "tribe_events_cat". For other plugins it will be different.
*/
add_action( 'init', 'my_custom_taxonomy_rest_support', 25 );
function my_custom_taxonomy_rest_support() {
global $wp_taxonomies;
//be sure to set this to the name of your taxonomy!
$taxonomy_name = 'tribe_events_cat';
if ( isset( $wp_taxonomies[ $taxonomy_name ] ) ) {
$wp_taxonomies[ $taxonomy_name ]->show_in_rest = true;
// Optionally customize the rest_base or controller class
$wp_taxonomies[ $taxonomy_name ]->rest_base = $taxonomy_name;
$wp_taxonomies[ $taxonomy_name ]->rest_controller_class = 'WP_REST_Terms_Controller';
}
}
With the above in my functions.php, now I can query just the custom post type and taxonomy with the REST API. Here's a sample query:
http://www.mywebsite.com/wp-json/wp/v2/tribe_events?tribe_events_cat=64
However, I still don't see any of the custom plugin data per-event. All I see are the basic standard WP fields.
So now I have to add more to my functions.php:
/* Add specific endpoints to REST API.
* The TEC plugin has good documentation, and they have a
* list of the variables. With any other plugin, you might
* have to do more detective work. */
add_action( 'rest_api_init', 'slug_register_event_venue' );
function slug_register_event_venue() {
register_rest_field( 'tribe_events',
'_EventVenueID',
array(
'get_callback' => 'slug_get_event_venue',
'schema' => null
)
);
}
function slug_get_event_venue( $object, $field_name, $request ) {
$postId = tribe_get_venue_id( $object[ 'id' ]);
if ( class_exists( 'Tribe__Events__Pro__Geo_Loc' ) ) {
$output[ 'locid' ] = (float) $postId;
$output[ 'lat' ] = (float) get_post_meta( $postId, Tribe__Events__Pro__Geo_Loc::LAT, true );
$output[ 'lng' ] = (float) get_post_meta( $postId, Tribe__Events__Pro__Geo_Loc::LNG, true );
} else {
$output = array(
'locid' => 0,
'lat' => 0,
'lng' => 0,
);
}
return $output;
}
... and a bunch more endpoint definitions of which I'm excluding the code here.
Now when I run the same query from earlier, new data fields are present in the JSON: all of the endpoints I've added.
At this point I want to exclude a ton of things from the REST API output (all the miscellaneous WP stuff) and just return the event fields I'm interested in. To do that I just add a "&fields" parameter to my query, with fields seperated by comma. There's also a per_page and order parameters too.
http://www.mywebsite.com/wp-json/wp/v2/tribe_events?tribe_events_cat=64&per_page=100&order=asc&fields=id,title.rendered,_EventVenueID.lat,_EventVenueID.lng,_EventVenueID.locid,_EventStartDate.startdate,tribe_events_cat
This returns JSON data with only the data I'm interested in.
The TEC plugin maker has stated they'll be introducing official REST API support sometime soon. This means in the future I can probably eliminate all of this code in functions.php, and just utilize whatever interface the plugin maker comes up with... hopefully a nice sexy page inside the plugin settings.
Now that WP (4.7) has more or less a fully featured REST API, the ball is in the court of the plugin makers to build support for it. So this year you should see plugins be updated accordingly.
When you are creating the custom post type in WordPress just add one more parameter show_in_rest as true for the support the rest API for Custom post type.
/**
* Register a book post type, with REST API support
*
* Based on example at:
https://codex.wordpress.org/Function_Reference/register_post_type
*/
add_action( 'init', 'my_book_cpt' );
function my_book_cpt() {
$args = array(
'public' => true,
'show_in_rest' => true,
'label' => 'Books'
);
register_post_type( 'book', $args );
}
Please visit here.
Then you can use the custom endpoint by the URL like this:
https://example.com/wp-json/wp/v2/book

Syncing custom fields between 2 languages (with WPML)

I'm using WPML (Wordpress multilanguage plugin) with custom post and fields (with Advanced Custom Fields plugin) and I have this "issue":
I've a custom post with a custom field (text), I enter text in the field and save. Now I go to the translated post and see that the same custom field is empty. Then the fields ar not synched. Notice that instead the Tag field is well synched between the languages.
Someone can help? Thanks
I don´t think the saved value of a custom field is synced by default. Only the name of the variable etc.
So if you have a custom field and wan´t it to have the same value on all languages, simply don´t add that custom field to other languages. Just have it on the main language.
Then in the template you can use this, to allways get the value from main language:
<?php the_field('fieldname',lang_page_original_id($post->ID));?>
Then add this to functions.php
function lang_page_original_id($id){
if(function_exists('icl_object_id')) {
return icl_object_id($id,'page', false, "MAIN LANGUAGE CODE EX: SV");
} else {
return $id;
}
}
Here are ACF docs: http://www.advancedcustomfields.com/resources/multilingual-custom-fields/
But it doesn't work as well as you may expect. Syncing is only "one way" from original to translated versions. See: https://wordpress.stackexchange.com/questions/181338/fixed-values-for-same-post-translations/214120#214120 for more details.
You will need WPML Multilingual CMS in order to use sync feature.
Hi use this in your function.php works 100%:
function sync_field_meta( $post_id, $post, $update ) {
$post_type = get_post_type($post_id);
// use this if u have muti custom post type
$posts_type = array('your_custom_post_type1', 'your_custom_post_type2', 'your_custom_post_type3', 'your_custom_post_type4');
if( ! in_array($post_type, $posts_type)) return;
$en = apply_filters( 'wpml_object_id', $post_id, 'any', FALSE, 'en' );
$fr = apply_filters( 'wpml_object_id', $post_id, 'any', FALSE, 'fr' );
// your acf key like (field_58136c9dc9963) you can check documention
$field = get_field('acf_key',$post_id);
if($en){
update_field('acf_key',$field,$en);
}
if($fr){
update_field('acf_key',$field,$fr);
}
}
add_action( 'save_post', 'sync_field_meta', 10, 3 );

Automatically insert WordPress custom field

I want to add a new custom field with a meta key and meta value to my posts.
Currently the only way it is added to a post is if I go into the post and click Update.
I have lots of posts and essentially want this custom field to be added to all posts automatically with an assigned meta value.
This meta value is different for each post.
I found this helpful: http://www.catswhocode.com/blog/wordpress-how-to-insert-data-programmatically
function add_custom_field_automatically($post_ID) {
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
add_post_meta($post_ID, 'field-name', 'custom value', true);
}
}
add_action('publish_page', 'add_custom_field_automatically');
add_action('publish_post', 'add_custom_field_automatically');
This will add a 'custom value' to the 'field-name' in the $post_ID.
I think the right method is using the 'save_post'hook,such as:
function cwp_add_custom_post_meta($post_id, $post){
global $wpdb;
$post_cat_id=get_the_terms( $post_id, 'category' );
$post_cat_id=cwp_object_to_array($post_cat_id);
$post_cat_id=$post_cat_id['0'] ["term_id"];
$display_voting = get_tax_meta($post_cat_id,'cwp_display_voting');
if(!wp_is_post_revision($post_id))
update_post_meta($post_id,'display_voting', $display_voting);
}
add_action( 'save_post', 'cwp_add_custom_post_meta', 10, 2 );

Resources