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

如何从WordPress多组数组中提取指定单条目标数据

问题描述

在WordPress中使用以下PHP代码获取文章自定义字段:

<?php
$meta_keys = get_post_custom_keys($post->ID);
foreach ($meta_keys as $meta_key) {
    $meta_values = get_post_custom_values($meta_key, $post->ID);
    print_r($meta_values);
    foreach ($meta_values as $meta_value) {
        $meta_value = maybe_unserialize($meta_value);
    }
}
?>

执行后得到输出:

Array ( [0] => 30718 )
Array ( [0] => 69 )
Array ( [0] => 30717 )
Array ( [0] => a:1:{i:0;a:1:{s:6:"_state";s:8:"expanded";}} )
Array ( [0] => 151 )
Array ( [0] => Read %%title%% %%page%% Manga %%sep%% %%sitename%% )
Array ( [0] => Read %%title%% manga online for free. )
Array ( [0] => )
Array ( [0] => 20 )
Array ( [0] => 30788 )
Array ( [0] => 1651670463:6 )
Array ( [0] => 6 )

需要提取输出中第二组数组的值69,用于后续自动加1处理,该如何实现?


解决方案

方法一:通过索引定位(依赖字段顺序)

如果确定目标值始终是输出中的第二个自定义字段值,可以直接在遍历中通过索引判断,找到后立即跳出循环:

<?php
$meta_keys = get_post_custom_keys($post->ID);
$target_value = 0;

// 遍历字段键,索引从0开始,第二个元素索引为1
foreach ($meta_keys as $index => $meta_key) {
    if ($index === 1) {
        $meta_values = get_post_custom_values($meta_key, $post->ID);
        // 取出值并转为整数,避免字符串干扰
        $target_value = intval($meta_values[0]);
        break;
    }
}

// 自动加1处理
$target_value += 1;
// 可根据需求使用该值,比如更新回自定义字段或输出
echo $target_value;
?>

方法二:通过字段键精准获取(更可靠)

如果知道69对应的自定义字段键名(比如假设键为custom_count),直接通过键获取值是更稳定的方案,无需依赖字段顺序:

<?php
// 替换为实际的自定义字段键名
$meta_values = get_post_custom_values('你的目标字段键名', $post->ID);
$target_value = 0;

if (!empty($meta_values)) {
    $target_value = intval($meta_values[0]);
    // 自动加1
    $target_value += 1;
    // 后续操作示例:更新自定义字段
    // update_post_meta($post->ID, '你的目标字段键名', $target_value);
}

echo $target_value;
?>

注意事项

  • 方法一仅适用于自定义字段顺序固定的场景,若后续字段顺序变化,会导致取值错误。
  • 方法二更推荐,只要明确目标字段的键名,就能稳定获取对应值,不受其他字段影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 04:40:29