【发布时间】:2023-03-24 09:56:01
【问题描述】:
我对 PHP 还很陌生,所以可能缺乏一些基础知识,所以就到这里吧。
对于 WordPress,我有一个用于替换 TablePress 表中的一些文本的功能。当我使用以下代码时,该函数运行良好:
function replace_stuff($text) {
if (is_front_page() || is_page('2611') || is_child('2611')) {
$replace_magic = array(
//text to search => text to replace
'dog' => 'cat',
'mouse' => 'elephant'
);
}
$text = str_replace(array_keys( (array)$replace_magic), $replace_magic, $text);
return $text;
}
add_filter('tablepress_table_output', 'replace_stuff');
因此,在该示例中,狗将在前端显示为猫和老鼠,如大象。
但现在我想通过在自定义帖子类型“驱动程序”中查询所有帖子的字段来使事情复杂化并创建要替换的字符串。
我想出了类似的方法,目的是找到与帖子标题匹配的任何文本并替换为自定义字段中的文本(来自我的“驱动程序”自定义帖子类型的所有帖子),但它没有什么都不做!
function replace_stuff($text) {
if (is_front_page() || is_page('2611') || is_child('2611') || get_post_type() == 'drivers') {
query_posts('post_type=drivers');
if (have_posts()) :
while (have_posts()) : the_post();
$profilenat = get_post_meta($post->ID, 'driver_nationality', true);
$profiletitle = get_the_title();
$replace_magic = array(
//text to search => text to replace
$profiletitle => $profilenat
);
endwhile;
endif;
}
$text = str_replace(array_keys( (array)$replace_magic), $replace_magic, $text);
return $text;
}
add_filter('tablepress_table_output', 'replace_stuff');
有人可以给我建议吗? 非常感谢。
【问题讨论】:
-
@Jamie
echo $text和print_r($replace_magic)如果您也可以在这里发布它们会很有帮助
标签: php wordpress variables str-replace