Quantcast
Channel: CSS – eppz!
Viewing all articles
Browse latest Browse all 7

Advanced custom WordPress excerpt

$
0
0

Customizing WordPress excerpt is essential once content gets grow on a WordPress site. Unfortunately the usual inline HTML output echoed out straight from PHP makes maintaining such modules quiet cumbersome.

Custom WordPress excerpt

// Include this to your 'function.php' somehow. 
function excerpt_filter($excerpt)
{ return 'Customized'.$excerpt; }

add_filter('get_the_excerpt', 'excerpt_filter');

While creating a custom WordPress excerpt is two actual statement (shown above), let me introduce how you can maintain your site modules in a more intuitive, templated way.

Like always, templating lets you separate data from presentation (separate PHP from HTML/CSS) this case as well. After some Googling, probably the best HTML templating engine to use is Twig, even better when we realize that it is packed up in Timber WordPress plugin, so we can use it out of the box. So after the plugin installed, you can fetch / render Twig templates using static Timber methods, like Timber::fetch.

Documentation for Twig is straightforward, for now all we need to insert variables using the {{ }} notation into out excerpt template. Below the template file excerpt.twig this site uses for simple posts (at the time of this writing).

Advanced custom WordPress excerpt


    

{{ title }}

{{ thumbnailHTML }} {{ excerpt }}

It is a clean, simple HTML markup with some necessary CSS to style the appearance along. The PHP part is really a single statement, where this case I packed up the data manually for this template snippet.

function excerpt_filter($excerpt)
{
    return Timber::fetch(
        'excerpt.twig', // The template file above
        array
        (
            'title' => get_the_title(),
            'thumbnailHTML' => get_the_post_thumbnail(),
            'excerpt' => $excerpt,
            'permalink' => get_permalink(),
        )
    );
}

add_filter('get_the_excerpt', 'excerpt_filter');

The method Timber::fetch takes the template name as the first, and template data as the second parameter.

Timber has some built in function to provide you data directly from The Loop, so probably you can get this working with even thinner data. Dispatching different excerpt templates to different post types, or categories can be laid out nicely using Twig HTML templating.

The post Advanced custom WordPress excerpt appeared first on eppz!.


Viewing all articles
Browse latest Browse all 7

Latest Images

Trending Articles





Latest Images