wordpress

Filters are the hooks that WordPress launches to modify text of various types before adding it to the database or sending it to the browser screen. We can add filters to our functions.php file, within our theme, to alter what content a theme provides by default.

Syntax:

<?php add_filter( $tag, $function_to_add, $priority, $accepted_args ); ?>

The excerpt is commonly shown on the homepage or a page such as categories of a website where multiple posts are shown, to displays a snippet of the post. The snippet is typically followed by [...] at the end, which functions as a ‘read more’ link. If you do not provide your own excerpt to a post in the optional excerpt field when creating a post, WordPress will display an automatic excerpt which refers to the first 55 words of the post’s content.

Two filters I have found extremely useful developing WordPress websites help alter the length of an excerpt and the words shown for the ‘read more’ link.

The first filter alters the length of an excert.

function my_excerpt_length($length) {
return 80;

}

add_filter(‘excerpt_length’, ‘my_excerpt_length’);

The first part of this code we create a function, the function has been named my_excerpt_length, which we will pass with the excerpt tag. The excerpt tag being ‘excerpt_length’.  The function simply returns a value we provide, in this case I have used the value 80.

The second filter is used to replaced the standard ‘read more’ link, shown by default as [...], with a value of our choice.

function new_excerpt_more($more) {
global $post;
return ‘ <a href=”‘. get_permalink($post->ID) . ‘”>[continue...]</a>’;
}
add_filter(‘excerpt_more’, ‘new_excerpt_more’);

The first part of this second code we create a function named new_excerpt_more, which we will pass with the excerpt tag ‘excerpt_more’.  The function slightly more complex then the previous code returns a snippet of HTML code. This HTML is dynamically generated and calls the global variable $post to ensure each post calls it’s own hyperlink. The words of the hyperlink live between the <a></a> tags, in this case I have used the value [continue...]

Remember these lines of code need to be placed inside the <?php ?> tags within the functions.php file.