我需要删除一些postmeta
从后端删除分类术语时。删除之前term
, 我需要找回Posteta的meka_key
以及术语id
这将被删除。使用术语id
执行某些任务,然后删除postmeta
和term
.
我已经试过用动作钩了set_object_terms
但是,我无法检索术语id
删除时term
因为它返回一个空数组。所以,我需要以某种方式得到这个术语id
在它被删除之前。
如何在删除术语id之前检索它?
add_action( \'set_object_terms\', function( $object_id, $terms, $tt_ids, $taxonomy ){
//$terms is returning the term\'s name (when adding an object id),
//it\'s returning empty when deleting the term.
//I need to have a valid $terms when deleting it, where can I get it?
$user_name = $terms;
$meta_key = \'_favorite_relation_added_\' . $user_name;
// Customize post type in next line according to your needs. I used \'category\' as example
if ( $taxonomy === \'favorite\' ) {
$post = get_post( $object_id );
if ( empty( $post ) ) return;
// Customize post type in next line according to your needs. I used \'post\' as example
if ( $post->post_type !== \'post\' ) return;
// let\'s see if the post has some terms of this category,
// because the hoook is fired also when terms are removed
$has_terms = get_the_terms( $object_id, $taxonomy );
// here we see if the post already has the custom field
$has = get_post_meta( $post->ID, $meta_key, true );
if ( ! $has && ! empty( $has_terms ) ) {
// if the post has not the custom field but has some terms,
// let\'s add the custom field setting it to current timestamp
update_post_meta( $post->ID, $meta_key, time() );
} elseif ( $has && empty( $has_terms ) ) {
// on the countrary if the post already has the custom field but has not terms
// (it means terms are all removed from post) remove the custom fields
delete_post_meta( $post->ID, $meta_key );
}
}
}, 10, 4);
SO网友:passatgt
实际上,您可以使用多个操作,至少这是wp\\u delete\\u term函数末尾的操作,该函数在单击分类术语上的delete时运行:
do_action( \'delete_term_taxonomy\', $tt_id );
do_action( \'deleted_term_taxonomy\', $tt_id );
do_action( \'delete_term\', $term, $tt_id, $taxonomy, $deleted_term );
do_action( "delete_$taxonomy", $term, $tt_id, $deleted_term );
最后一个可能最有用,您可以创建如下添加操作:
add_action( "delete_favorite" ...
SO网友:Gixty
删除术语之前运行的挂钩是\'delete_term_taxonomy\'
它是在删除之前使用术语\\u id所需的钩子。
现在,我们可以继续检索term
对象并删除postmeta
与正在删除的术语相关。
代码如下:
add_action( \'delete_term_taxonomy\', function($tt_id) {
$taxonomy = \'category\';
$term = get_term_by(\'term_taxonomy_id\', $tt_id, $taxonomy);
$user_name = $term->name;
$meta_key = "_category_relation_added_" . $user_name;
delete_post_meta_by_key( $meta_key );
}, 9, 1);