树枝模板导入外部WordPress帖子

时间:2015-07-08 12:36:49

标签: php wordpress symfony twig

我正在尝试将一些WordPress帖子加载到使用Twig构建的网站中。我已经尝试将此代码插入到页面中,但它会被注释掉。我猜有一些特殊的方式我应该重写这个在Twig中工作。任何人都可以帮助我吗?

<?php define('WP_USE_THEMES', false);
require('../wordpress/wp-blog-header.php');
query_posts('showposts=3'); ?>

<?php while (have_posts()): the_post(); ?>
<div class="wordpress-post">
<?php if ( has_post_thumbnail() ) : ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_post_thumbnail(); ?>
<h2><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
<p><a class="read-more" href="<?php the_permalink(); ?>" class="red">Read More</a></p>
</div>
<?php endwhile; ?>

提前致谢!

1 个答案:

答案 0 :(得分:1)

您不能在给定的Twig模板中混合使用PHP和Twig代码。您应该在PHP文件中查询帖子,然后将该变量传递给Twig变量以呈现结果。

顺便说一下,等效的Twig模板将如下所示:

{% for the_post in posts %}
    <div class="wordpress-post">
        {% if the_post.thumbnail is defined %}
            <a href="{{ the_post.permalink }}" title="{{ the_post.title }}">
                {{ the_post.thumbnail }}
            </a>
        {% endif %}

        <h2>{{ the_post.title }}</h2>
        {{ the_post.excerpt }}

        <p><a class="read-more" href="{{ the_post.permalink }}" class="red">Read More</a></p>
    </div>
{% endfor %}

要在PHP应用程序中呈现此模板,请首先确保已安装Twig lib。然后,在PHP文件中,执行以下操作:

<?php
require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem('/path/to/templates/directory');
$twig = new Twig_Environment($loader);

// query the database for the posts and save the result in a $posts variable
$posts = ...

echo $twig->render('template_name.html', array('posts' => $posts));