PHP模版引擎twig wordpress中调用文章第一张图片

wordpress当文章没有添加Featured media的时候,

就调用文章第一张图片,

调用的wordpress代码函数为: 

<?php echo catch_that_image(); ?>

 

网站使用的themes是Notio,配套插件为Gantry 5 Fraamework,
然而Notio使用的是twig模版引擎,前台文件都是以.twig结尾,
Notio的分类首页使用的文件为主题根目录下的index.php,
而分类下的各个页面使用的是archive.php文件,两者都调用了模版views/partials/content.html.twig

 



 
index.php先将所有的数据存放在$context中,之后传递给模版文件使用,
而我发现$context中并没有文章第一张图片这个属性,但是有post_id, content等等的属性,
所以可以自己加上去,通过正则匹配读取post content ,提取出第一个img 的url,作为网站的第一张图片。
同理把如下代码加到archive.php中,
 
// add from Ryan 2018/05/09 catch posts the first image
function catch_the_image( $post_content ) {
    // global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post_content, $matches);
    $first_img = $matches [1] [0];

    return $first_img;
}

for ($i = 0; $i < count($context['posts']); $i++) {
    $context['posts'][$i]->the_posts_first_image = catch_the_image($context['posts'][$i]->post_content);
}

Timber::render($templates, $context);
 
 
接着就是在显示到前台页面了,由于在index.html.twig有对posts的数据进行循环,
而我们的数据就存放在posts中,因此可以直接绑定。
 
{# Begin Featured Image #}
                {% if gantry.config.get('content.' ~ scope ~ '.featured-image.enabled', '1') and post.thumbnail.src %}
                    {% set position = (gantry.config.get('content.' ~ scope ~ '.featured-image.position', 'none') == 'none') ? '' : 'float-' ~ gantry.config.get('content.' ~ scope ~ '.featured-image.position', 'none') %}
                    <a href="{{ post.link }}" class="post-thumbnail" aria-hidden="true">
                        <img src="{{ post.thumbnail.src|resize(gantry.config.get('content.' ~ scope ~ '.featured-image.width', '1150'), gantry.config.get('content.' ~ scope ~ '.featured-image.height', '285')) }}" class="featured-image tease-featured-image {{ position }}" alt="{{ post.title }}" />
                    </a>
                    {% else %}
                    <a href="{{ post.link }}" class="post-thumbnail" aria-hidden="true">
                        <img src="{{post.the_posts_first_image}}" class="featured-image tease-featured-image {{ position }}" alt="test" />
                    </a>
                    
                {% endif %}
{# End Featured Image #}
 
 
 

猜你喜欢

转载自www.cnblogs.com/ryanzheng/p/9014806.html