我对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');
因此,在该示例中,狗将在前端显示为cat&小鼠作为大象。
但现在我想让事情复杂化。通过查询自定义帖子类型“drivers”中所有帖子的字段来创建要替换的字符串。
我想出了类似的东西,目的是找到任何与帖子标题相匹配的文字。替换自定义字段中的文本(来自我的'驱动程序自定义帖子类型的所有帖子),但它没有做任何事情!
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');
有人可以告诉我吗? 非常感谢。
答案 0 :(得分:0)
首先我认为你需要更换 $ replace_magic = array( 同 $ replace_magic [$ profiletitle] = $ profilenat
目前,如果一切正常,那么对于每个驱动程序,您都要用新数组替换$ replace_magic的内容,该数组只包含该驱动程序的详细信息。相反,您想要将新项目添加到现有数组中。
更进一步,对于这类问题,进行一些快速调试以帮助您缩小问题的范围可能非常有用。所以在这里知道问题是否真的与你的str_replace有关,或者它是否真的与它上面的代码一起使用会很有用。
Debugging in Wordpress值得一读,完成后你可以使用error_log将一些细节输出到你的wp-content目录中的debug.log。
在你的str_replace之前,做 error_log中(的print_r($ replace_magic)); 会告诉您,如果您的查询循环是否按预期工作。 如果它没有,那么你可以在循环中放入一个日志语句。这将告诉您是否正在执行循环内容(在这种情况下,问题在于循环中的代码),或者不是(在这种情况下问题可能与您的查询有关)。
此外,如果您还没有,我建议您查看WordPress Codex on query_posts。 query_posts操纵主Wordpress查询,并可能在这样的过滤器中使用一些非常意外的结果。至少考虑WP_Query - 并查看关于wp_reset_posts的注释。
希望有所帮助 - 如果其中一些是你已经考虑过的东西而道歉,但正如你提到的那样,你对PHP非常陌生,我希望它有用。