【问题标题】:wordpress php str_replace function with variables not quite therewordpress php str_replace函数,变量不完全存在
【发布时间】: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 $textprint_r($replace_magic) 如果您也可以在这里发布它们会很有帮助

标签: php wordpress variables str-replace


【解决方案1】:

首先我认为你需要更换 $replace_magic = 数组( 和 $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 很陌生,我希望它有用。

【讨论】:

  • 谢谢,您的调试是对的 - 我发现 $profilenat 变量未定义。我用一个较短的调用替换了我的 wordpress 主题中有一个函数。 $drivernat = get_custom_field('driver_nationality', TRUE);这有效----自定义字段功能是: function get_custom_field($key, $echo = FALSE) { global $post; $custom_field = get_post_meta($post->ID, $key, true); if ($echo == FALSE) 返回 $custom_field;回声 $custom_field; }
猜你喜欢
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 2011-09-16
  • 1970-01-01
相关资源
最近更新 更多