简体   繁体   中英

Twig Template Import External WordPress Posts

I'm trying to load in a few WordPress posts into a website built using Twig. I've tried inserting this code into the page but it gets commented out. I'm guessing there's some special way I'm supposed to rewrite this to work in Twig. Can anyone help me?

<?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; ?>

Thanks in advance!

You cannot mix PHP and Twig code in a given Twig template. You should query for the posts in a PHP file and then pass that variable to a Twig variable to render the results.

By the way, the equivalent Twig template would be something like the following:

{% 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 %}

To render this template in your PHP application, first make sure that Twig lib is installed. Then, in your PHP file, do the following:

<?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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM