You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress自定义文章类型全状态计数及自定义字段自动填充问题

解决方案

1. 统计自定义文章类型所有状态的帖子总数

你原来的代码仅统计已发布和草稿状态的帖子,要包含所有状态(包括自定义的「用户禁用」),可以用WP_Query查询全状态下的estate_property帖子总数,替换原计数逻辑:

/** Generate Custom ID when a new Estate Property is published.*/
add_action('save_post_estate_property', 'save_post_callback');
function save_post_callback($post_id){
    // 跳过自动保存和修订版本
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (wp_is_post_revision($post_id)) return;

    // 仅当prop字段为空时执行
    if (get_post_meta($post_id, 'prop', true) == '') {
        // 查询所有状态的estate_property帖子总数
        $all_posts_query = new WP_Query(array(
            'post_type' => 'estate_property',
            'post_status' => 'any', // 包含所有默认及自定义状态
            'posts_per_page' => -1,
            'fields' => 'ids' // 仅取ID,提升查询性能
        ));
        $total_posts = $all_posts_query->found_posts;
        // 更新prop字段值为总数+1
        update_post_meta($post_id, 'prop', $total_posts + 1);
    }
}

这里用post_status => 'any'覆盖所有状态,found_posts直接返回符合条件的总数量,最后用update_post_meta写入字段,比修改$_POST更可靠。

2. 获取prop字段的最后值并加1

如果要基于已有的prop字段最大值递增,可通过查询获取当前最大的prop值再加1:

/** Generate Custom ID when a new Estate Property is published.*/
add_action('save_post_estate_property', 'save_post_callback');
function save_post_callback($post_id){
    // 跳过自动保存和修订版本
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (wp_is_post_revision($post_id)) return;

    // 仅当prop字段为空时执行
    if (get_post_meta($post_id, 'prop', true) == '') {
        // 查询estate_property中prop字段的最大值
        $max_prop_query = new WP_Query(array(
            'post_type' => 'estate_property',
            'post_status' => 'any',
            'meta_key' => 'prop',
            'orderby' => 'meta_value_num', // 按数字排序,避免字符串排序误差
            'order' => 'DESC',
            'posts_per_page' => 1,
            'fields' => 'ids'
        ));
        
        if ($max_prop_query->have_posts()) {
            $max_prop = get_post_meta($max_prop_query->posts[0], 'prop', true);
            $new_prop = intval($max_prop) + 1;
        } else {
            // 无已存在的prop值时,从1开始
            $new_prop = 1;
        }
        // 更新prop字段
        update_post_meta($post_id, 'prop', $new_prop);
    }
}

这段代码会按数字降序找到最大的prop值,加1后作为新值;如果是第一个帖子,则直接设为1。

说明:两个方案都改用了save_post_estate_property钩子,仅针对estate_property类型帖子触发,覆盖草稿转发布、直接发布等场景,同时跳过自动保存和修订版本,避免重复执行。

内容的提问来源于stack exchange,提问作者seby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 15:33:10