警告:在WordPress 4.9.8

时间:2018-08-09 13:44:12

标签: wordpress wordpress-theming

我正在尝试在WordPress 4.9.8中运行此代码,但出现错误:

  

警告:WordPress 4.9.8中为foreach()提供了无效的参数

<?php
        // Create an array for post title
        $post_title = [
            "Hello World",
            "Hello PHP",
            "Hello WordPress"
        ];

        //Loop through array of post

        foreach ( $post_titles as $post_title){

            // Call the $display_title title functions and pass it the post title

            display_title ( $post_title);
        }

        /* Display the title for a post
        *
        * @param string $title the title to be displayed
        */

        function display_title( $title){
            // Echo an h3 tag with the title inside

            echo "<h3>". $title ."</h3>";
        }


?>

1 个答案:

答案 0 :(得分:3)

您当前正在尝试遍历不存在的数组。

不是为您的数组分配变量:

$post_title

您应将其分配为:

$post_titles

从那里,您可以通过将变量称为新变量来遍历数组。 您当前正在尝试回显数组变量,而不是回显每个标题。下面更新了代码。

<?php 
    // Create an array for post title 
    $post_titles = [ "Hello World", "Hello PHP", "Hello WordPress" ]; 
    //Loop through array of post 
    foreach ( $post_titles as $title){ 
       echo "<h3>". $title ."</h3>"; 
    } 
?>

如果您只是想在查询循环中获取帖子的标题,则可以使用:

the_title()

有关WordPress标题的更多信息,请点击此处:https://codex.wordpress.org/Function_Reference/the_title