Skip to content

Instantly share code, notes, and snippets.

@wordpressvn
Forked from vielhuber/index.php
Created October 27, 2022 08:38
Show Gist options
  • Select an option

  • Save wordpressvn/a9498d7fedb7289882d7a2c27adf4853 to your computer and use it in GitHub Desktop.

Select an option

Save wordpressvn/a9498d7fedb7289882d7a2c27adf4853 to your computer and use it in GitHub Desktop.
split get content before / after read more tag outside loop #php #wordpress
<?php
// with wordpress native functions
echo get_extended($p->post_content)['main'];
echo get_extended($p->post_content)['extended'];
// with own function (wordpress own function has problems with enabled p tags)
function wp_split_more($content, $type, $more_html = null) {
$return = [
"before" => null,
"after" => null
];
// split up
if ( preg_match('/<!--more(.*?)?-->/', $content, $matches) ) {
list($return["before"], $return["after"]) = explode($matches[0], $content, 2);
}
else {
$return["before"] = $content;
$return["after"] = '';
}
// clean up
foreach($return as $key=>$value) {
// remove whitespace
$return[$key] = trim(preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $return[$key]));
// remove falsly opening p tag
if( strpos($return[$key], "</p>") === 0 ) { $return[$key] = trim(substr($return[$key], strlen("</p>"))); }
// remove opening p tag
if( strpos($return[$key], "<p>") === 0 ) { $return[$key] = trim(substr($return[$key], strlen("<p>"))); }
// remove closing p tag
if( strrpos($return[$key], "<p>") === strlen($return[$key])-strlen("<p>") ) { $return[$key] = trim(substr($return[$key], 0, strlen($return[$key])-strlen("<p>"))); }
if( strrpos($return[$key], "</p>") === strlen($return[$key])-strlen("</p>") ) { $return[$key] = trim(substr($return[$key], 0, strlen($return[$key])-strlen("</p>"))); }
}
// add more tag
if( $more_html !== null && $return["after"] !== "" ) {
$return["before"] = $return["before"]."".$more_html;
}
// add opening / closing p-tags
$return["before"] = "<p>".$return["before"]."</p>";
$return["after"] = "<p>".$return["after"]."</p>";
return $return[$type];
}
// example usage
echo '<div class="content">';
echo '<div class="before">';
echo wp_split_more($p->post_content, 'before', '<a href="'.get_permalink($p->post_id).'" class="more">&gt;&gt;&gt;</a>');
echo '</div>';
if( wp_split_more($p->post_content, 'after') !== null && wp_split_more($p->post_content, 'after') != "" ) {
echo '<div class="after">';
echo wp_split_more($p->post_content, 'after');
echo '</div>';
echo '</div>';
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment