Skip to content

Instantly share code, notes, and snippets.

@lunule
Created February 19, 2017 19:25
Show Gist options
  • Save lunule/a34a07c9dd39999f140e7c5ae43e42f5 to your computer and use it in GitHub Desktop.
Save lunule/a34a07c9dd39999f140e7c5ae43e42f5 to your computer and use it in GitHub Desktop.
How filters work in WordPress, aka how to make your plugins and functions extendable and the output easily modifiable. | +Tags: filter, filters, extend
<?php
function eyn_wb17_excerpt_from_content( $content, $wordlimit, $url, $readmore = 'Read More' ) {
// Action hook before any output!
do_action( 'eyn_wb17_before_excerpt' );
// Make the Read More text filterable
$readmore = apply_filters( 'eyn_wb17_excerpt_rmtext', $readmore );
$rmString = ' ... <a href="' . $url . '">' . $readmore . '</a>';
// Make the Read More string filterable
$rmString = apply_filters( 'eyn_wb17_excerpt_rmstring', $rmString );
$excerpt = force_balance_tags(
html_entity_decode(
wp_trim_words(
htmlentities(
wpautop( $content )
),
$wordlimit,
$rmString
)
)
);
echo $excerpt;
// Action hook after rest of output!
do_action( 'eyn_wb17_after_excerpt' );
}
// Filter: Replace the readmore text
add_filter( 'eyn_wb17_excerpt_rmtext', 'eyn_wb17_excerpt_rmtext_mod' );
function eyn_wb17_excerpt_rmtext_mod( $text ) {
return 'Read Me Later';
}
// Filter: Replace the readmore string
add_filter( 'eyn_wb17_excerpt_rmstring', 'eyn_wb17_excerpt_rmstring_mod' );
function eyn_wb17_excerpt_rmstring_mod( $text ) {
$text = str_replace(
array( '...' ),
array( '>>>' ),
$text
);
return $text;
}
// Action: Add title before excerpt
add_action( 'eyn_wb17_before_excerpt', 'eyn_wb17_excerpt_addbefore' );
function eyn_wb17_excerpt_addbefore() {
echo '<h4>Beautiful Content Excerpt for ' . date( 'F j, Y') . ':</h4>';
}
// Action: add something after excerpt
add_action( 'eyn_wb17_after_excerpt', 'eyn_wb17_excerpt_addafter' );
function eyn_wb17_excerpt_addafter() {
echo '<div><img src="http://kacaj.eu/feltoltesek/2011/12/trollface-400x400.jpg" width="150" height="150" alt="Problem?"></div>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment