【问题标题】:List WordPress certain category's post url列出 WordPress 某个类别的帖子网址
【发布时间】:2017-11-01 03:38:35
【问题描述】:

有没有办法在没有插件的情况下列出 WordPress 中某个类别的所有帖子网址? 我不熟悉 PHP,但我在想如果有什么方法,我可以使用一个页面模板,其中一个方法将调用所有此类帖子的 url(例如:让我们将类别称为“博客”)。

【问题讨论】:

    标签: php wordpress url post categories


    【解决方案1】:

    查看WP_Query 和 WordPress 循环。如果我正确理解您的询问(包装在 php 标签中),这样的事情应该可以工作:

    $the_query = new WP_Query( array( 'category_name' => 'blog' ) );
    
    if ( $the_query->have_posts() ) {
     echo '<ul>';
     while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_permalink() . '</li>';
     }
     echo '</ul>';
     /* Restore original Post Data */
     wp_reset_postdata();
    } else {
     // no posts found
    } 
    

    【讨论】:

      【解决方案2】:

      您可以使用get_posts (https://codex.wordpress.org/Template_Tags/get_posts)。

      考虑这是 WP_Query 的精简版本,它将返回您想要的帖子数组。

      $categoryPosts = get_posts(array(
          // Note: The category parameter needs to be the ID of the category, and not the category name.
          'category' => 1,
          // Note: The category_name parameter needs to be a string, in this case, the category name.
          'category_name' => 'Category Name',
      ));
      

      然后你可以循环浏览帖子:

      foreach($categoryPosts as $categoryPost) {
          // Your logic
      }
      

      $categoryPost 默认包含以下内容(如果您有自定义字段,则更多字段),这些字段显然会被填充,但这是您在数组中可用的内容:

      WP_Post Object
      (
          [ID] =>
          [post_author] => 
          [post_date] => 
          [post_date_gmt] => 
          [post_content] => 
          [post_title] => 
          [post_excerpt] => 
          [post_status] => 
          [comment_status] => 
          [ping_status] => 
          [post_password] => 
          [post_name] => 
          [to_ping] => 
          [pinged] => 
          [post_modified] => 
          [post_modified_gmt] => 
          [post_content_filtered] => 
          [post_parent] => 
          [guid] => 
          [menu_order] => 
          [post_type] => 
          [post_mime_type] => 
          [comment_count] => 
          [filter] =>
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-03
        • 1970-01-01
        • 1970-01-01
        • 2020-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-22
        相关资源
        最近更新 更多