我需要显示一个帖子列表并按日期排序。创建分类术语关系的日期。
这可能吗?如果是,我该如何处理?
非常感谢。
编辑-已解决谢谢你对通用汽车公司的帮助。
以下是我所做的:
对于每个set和remove操作,我给它一个不同的meta\\u键,并将用户名作为变量
带变量的meta\\u键
$meta_key = \'_category_relation_added_\' . $user_name;
删除术语和元
delete_post_meta($post_ID, $meta_key);
wp_remove_object_terms( $post_ID, $user_name, $taxonomy );
添加术语和元
wp_set_object_terms( $post_ID, $user_name, $taxonomy, true );
update_post_meta( $post_ID, $meta_key, time() );
然后我们用WP\\u query查询帖子
$meta_key = \'_category_relation_added_\' . $user_name;
$args = array(
// all your args here
\'meta_key\' => $meta_key,
\'orderby\' => \'meta_value_num\',
\'order\' => \'DESC\' // from more to less recent
);
$query = new WP_Query( $args );
更新-删除术语时,删除与术语相关的所有Posteta
add_action( \'delete_term_taxonomy\', function($tt_id) {
$term = get_term_by(\'term_taxonomy_id\', $tt_id, \'favorite\');
$user_name = $term->name;
$meta_key = "_category_relation_added_" . $user_name;
delete_post_meta_by_key( $meta_key );
}, 9, 1);
最合适的回答,由SO网友:gmazzap 整理而成
是的,是可行的。
我建议您在将特定分类法的某些术语添加到帖子中时,添加一个自定义字段。
当从同一帖子中删除所有条款时,您还应该删除该自定义字段。
可以使用\'set_object_terms\'
.
请阅读代码中的注释以了解更多说明:
add_action( \'set_object_terms\', function( $object_id, $terms, $tt_ids, $taxonomy ){
// Customize post type in next line according to your needs. I used \'category\' as example
if ( $taxonomy === \'category\' ) {
$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, "_category_relation_added", 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, "_category_relation_added", 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, "_category_relation_added" );
}
}
}, 10, 4);
不要忘记更改分类法和帖子类型名称。
将以前的代码添加到functions.php
您可以使用该自定义字段对帖子进行排序:
$args = array(
// all your args here
\'meta_key\' => \'_category_relation_added\',
\'orderby\' => \'meta_value_num\',
\'order\' => \'DESC\' // from more to less recent
);
$query = new WP_Query( $args );