wordpress主题开发2-常用模板函数

作者: dreamfly 分类: php,个人博客 发布时间: 2020-05-18 12:40

上一讲我们讲到了wordpress主题开发中的模板结构,今天我们来讲一讲开发主题中我们经常使用到的模板函数。

我们都知道一个主题不仅仅有着好看的样式就行,还需要显示我们想要显示的内容才行。如何在模板中显示文章的内容,文章的标题,文章的各种信息?答案就是使用wordpress提供给我们的模板函数。

wordpress封装了很多模板函数,我们可以轻松的获取到我们想要的数据库中的各个字段。

文章详情页

比如我们想要获取文章标题,调用the_title()这个函数就可以。

the_title( string $before = '', string $after = '', bool $echo = true )

想要获取文章的摘要,同理,我们只需要调用the_excerpt()这个函数就可以。

the_excerpt()

同理,我们想要获取文章内容的话,调用the_content()这个函数就可以。

the_content( string $more_link_text = null, bool $strip_teaser = false )

从中我们不难发现规律,只要the_xxx就可以获取数据库对应的字段,可以说记起来还是很容易的。

单页面

一个单页面中我们想要获取指定的文章数据,如何获取呢?通过get_post()函数就可以


<?php $post_7 = get_post(7); $title = $post_7->post_title; ?> 

通过这个函数我们可以获取指定id的文章内容。

如果想要获取页面内容的话,我们需要使用get_page()函数来获取,传入page_id就可以获取page内容,而在wordpres中page也是存入到post表中的,只不过类型字段不一样。

<?php 
$page_id = 123; 

$page_data = get_page( $page_id ); 

echo '<h3>'. $page_data->post_title .'</h3>';

echo apply_filters('the_content', $page_data->post_content); 
?>

文章列表页

文章列表页就是我们可以循环显示文章的页面。在文章列表页,我们主要通过循环来获取文章内容。


<ul>
<?php

global $post;

$args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 1 );

$myposts = get_posts( $args );

foreach( $myposts as $post ) : setup_postdata($post); ?>
    <li>
          <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>
<?php endforeach; ?>

</ul>

通过get_posts 函数可以获取我们的文章列表。

还有一种方式是

<?php while (have_posts()): the_post(); ?>
<article>

        <a class="title" href="<?php echo get_permalink(); ?>">
            <h2><?php the_title(); ?></h2>
        </a>

        <div class="meta">
            <i class="icon"><?php echo get_the_date('Y-m-d'); ?></i>
            <?php the_category(', ', 'span'); ?>
        </div>

        <div class="excerpt">
            <?php the_excerpt(); ?>

            <a href="<?php echo get_permalink(); ?>" class="readmore">阅读全文 »</a>
        </div>
    </article>
<?php endwhile;?>

通过while, the_posts函数,我们也可以循环获取文章列表内容。

分页获取:the_posts_pagination()通过这个函数我们可以显示分页。

小工具显示

wordpress后台提供了小工具功能,可以方便我们显示导航,分类等信息,我们在模板中只需要使用get_sidebar()函数,它就会自动加载后台设置的小工具,可以说非常方便。

总结

wordpress封装了各种调用函数,基本上我们想要的数据,都可以通过函数获取到,因此,wordpress模板开发,了解一些常用的自带函数还是非常重要的。

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!