【问题标题】:WP get first and last post titleWP获取第一个和最后一个帖子标题
【发布时间】:2013-08-24 23:05:38
【问题描述】:

我列出了城市并按字母顺序排列,我想出了这个代码

<?php
$args = array(
    'post_type'        => 'cities',
    'orderby'          => 'title',
    'order'            => 'ASC',
    'posts_per_page'   => -1,
    'caller_get_posts' => 1
);
$my_query = new WP_Query($args);

if ($my_query->have_posts()) {
    while ($my_query->have_posts()) : $my_query->the_post();?>
        <?php
        $this_char = strtoupper(substr($post->post_title, 0, 1));
        if ($this_char != $last_char) {
            $last_char = $this_char;
            if (isset($flag))
                echo '</div>';
            echo '<div data-role="collapsible" class="excerpts">';
            echo '<h3 class="alphabet">' . '<div>' . $last_char . '</div>' . '</h3>';
            $flag = true;
        } ?>

        <p class="inner"><a data-transition="slide"
                            href="<?php the_permalink() ?>" rel="bookmark"
                            title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
        </p>
    <?php endwhile;
}
if (isset($flag))
    echo '</div>';

wp_reset_query();?>

此代码生成以下 HTML

<div class="collapsible">
    <h3><div>A</div></h3>
    <p>Atlanta</p>
    <p>Alabama</p>
    <p>Arizona</p>
</div>

但我想要实现的是将第一个和最后一个帖子标题放在字母旁边,像这样

<div class="collapsible">
    <h3><div>A</div> Atlanta - Arizona</h3>
    <p>Atlanta</p>
    <p>Alabama</p>
    <p>Arizona</p>
</div>

如何在 wordpress 中获得最后一篇文章的标题?有任何想法吗?谢谢你。

我第一次尝试了这个,但我不知道最后一次

echo '<h3 class="alphabet">'. '<div>'.$last_char. '</div>' .  get_the_title() .' - get_the_last_title' .'</h3>';

【问题讨论】:

    标签: php wordpress loops


    【解决方案1】:

    使用get_posts 这将为您提供帖子数组,您可以访问任何数组中的数据。

    <?php 
    $posts_array = get_posts( $args );
    echo $posts_array[0] // First posts;
    echo $posts_array[count($posts_array) -1 ] //Last Posts
    ?> 
    

    或使用 WP_query:

    $firstPost = $my_query -> $posts[0] // first post
    $lastPost  $my_query -> $posts[$my_query->$found_posts] // Last post
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2014-08-14
      • 1970-01-01
      • 1970-01-01
      • 2010-10-09
      • 2020-07-26
      • 2016-01-12
      相关资源
      最近更新 更多