[英]Wordpress: Update Custom Field using API Javascript
我正在嘗試使用javascript和Wordpress REST API更新自定義字段。
我可以使用它輕松地創建一個新帖子,並且效果很好:
var post = new wp.api.models.Post( { title: 'This is a test post' } );
post.save();
但是,我需要更新帖子自定義字段。 我已經嘗試過以下代碼: https : //wordpress.stackexchange.com/questions/218261/wp-api-js-backbone-client-how-to-update-post-meta :
var parentId = 91; // the post id
var metaData = new wp.api.collections.PostMeta('', {parent: parentId});
metaData.fetch()
.done(function(data) {
var someKey = data.findWhere({key: 'someKey'});
someKey.set('value', 'newValue');
someKey.save({parent: parentId});
});
但我只是在控制台中收到以下錯誤:
Uncaught TypeError: wp.api.collections.PostMeta is not a constructor
任何幫助都會很棒。
謝謝
不是解決方案
我放棄了這種方法,而是使用了Ajax的不同方法,如下所示: https : //teamtreehouse.com/community/how-update-custom-fields-with-ajax-in-wordpress
基本上是jQuery:
jQuery.ajax({ // In Wordpress use jQuery rather than $ to avoid conflict
url : 'https://example.com/wp-admin/admin-ajax.php', // This address will redirect the query to the functions.php file, where we coded the function that we need.
type : 'POST',
data : {
action : 'my_action',
postid : postid,
},
beforeSend: function() {
//console.log('Updating Field');
},
success : function( response ) {
},
complete: function(){
}
});
Functions.php
function my_action(){
$order_id = $_POST['postid'];
// DO something
echo $return;
wp_die($order_id = ''); // this is required to terminate immediately and
return a proper response
}
我不會將其標記為解決方案,因為它不是,但在這里它可以幫助遇到它的任何人。
假設您有一個自定義分類法車輛
var vehicles = new wp.api.collections.Vehicles();
vehicles.create(
{
name: 'Truck',
description: 'A truck or lorry is a motor vehicle designed to transport cargo'
meta:{
'_wiki_link': 'https://en.wikipedia.org/wiki/Truck'
}
});
參見wp-includes / rest-api / endpoints / class-wp-rest-terms-controller.php:437
add_action( 'rest_insert_vehicles', function( $term, $request, $flag ){
$term_meta = $request->get_json_params()['meta'] ?? [];
foreach( $term_meta as $meta_key => $meta_value ){
update_term_meta( $term->term_id, $meta_key, $meta_value );
}
}, 20, 3 );
遇到了類似的問題,嘗試從javascript rest API更新術語meta。
似乎您不能完全使用javascript做...
原因是,一旦通過其余術語控制器插入了該術語(下面的代碼段)
參見wp-includes / rest-api / endpoints / class-wp-rest-terms-controller.php#L428
$term = wp_insert_term( wp_slash( $prepared_term->name ), $this->taxonomy, wp_slash( (array) $prepared_term ) );
...術語的實際詳細信息不會發送到此控制器的更新部分
參見wp-includes / rest-api / endpoints / class-wp-rest-terms-controller.php#L444
if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
$meta_update = $this->meta->update_value( $request['meta'], (int) $request['id'] );
if ( is_wp_error( $meta_update ) ) {
return $meta_update;
}
}
您會注意到,它是通過$request['id']
而不是$term['id']
,這是有原因的(也許您執行的是更新而不是創建)
我在這里可能是錯的...但這就是我的結論
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.