How to add a "Read more" button to my blog? - php

I have an HTML template which I convert to a Wordpress theme, but i can't add a "Read more" button to the home page.
I use the following code in functions.php:
function the_content_limit($max_char, $more_link_text = '(more...)', $stripteaser = 0, $more_file = '') {
$content = get_the_content($more_link_text, $stripteaser, $more_file);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
$content = strip_tags($content);
if (strlen($_GET['p']) > 0) {
echo "<p>";
echo $content;
echo "</p>";
}
else if ((strlen($content)>$max_char) && ($espacio = strpos($content, " ", $max_char ))) {
$content = substr($content, 0, $espacio);
$content = $content;
echo "<p>";
echo $content;
echo "...";
echo "</p>";
}
else {
echo "<p>";
echo $content;
echo "</p>";
}
}
I also use the following code in index.php:
<div class="text_home"><?php the_content_limit(300); ?></div>
What can I do to solve my problem?

//keep this code in function.php
function get_excerpt($limit=10, $content) {
$content = explode(' ', $content,$limit);
if (count($content)>=$limit) {
array_pop($content);
$content = implode(" ",$content);
$content = $content.' ...';
} else {
$content = implode(" ",$content);
}
return $content;
}
where you want to call this function
$content = get_the_content();
$content = strip_tags($content);
echo get_excerpt(15, $content);

Related

PHP array splice not working

I'm trying to build a shortcode in wp that displays data from 2 RSS feeds.
The problem is that I can't limit the number of items in array. I tried these solutions and none worked.
function rss_posts_func( $atts ){
$feed = fetch_feed(array('rss-feed-1', 'rss-feed-2'));
$feed = array();
$feed = array_splice($feed, 0, 3);
// Loop the results
$content = '<ul class="rss-aggregator">';
foreach($feed->get_items() as $item) {
$content .= '<li class="feed-item">';
$content .= '<a href='.$item->get_permalink().'>';
$content .= $item->get_title();
$content .= '</a></li>';
}
$content .= '</ul>';
return $content;
}
Fixed with:
function rss_posts_func( $atts ){
$i = 1;
$feed = fetch_feed(array('rss-feed-1', 'rss-feed-2'));
$content = '<ul class="rss-aggregator">';
foreach($feed->get_items() as $item) {
$content .= '<li class="feed-item">';
$content .= '<a href='.$item->get_permalink().'>';
$content .= $item->get_title();
$content .= '</a></li>';
if($i++ == 8) break;
}
$content .= '</ul>';
return $content;
}

Custom Wordpress Excerpt by two paragraphs

I found the answers to limiting the excerpts to only 2 paragraphs or more. However, the code I found only apply to the actual excerpt, not to custom excerpt that I made. I made two excerpts, one for certain posts on front page and another for the posts page. I wanted to add that code to the custom excerpt that I made for the posts page. How do I do that.
Here's my code that I created:
// Create the Custom Excerpts callback
function wpden_excerpt($length_callback = '', $more_callback = '')
{
global $post;
if (function_exists($length_callback)) {
add_filter('excerpt_length', $length_callback);
}
if (function_exists($more_callback)) {
add_filter('excerpt_more', $more_callback);
}
$output = get_the_excerpt();
$output = apply_filters('wptexturize', $output);
$output = apply_filters('convert_chars', $output);
$output = '<p>' . $output . '</p>';
echo $output;
}
// Custom Length
function wpden_mag_len($length) {
return 200;
}
function wpden_more_view($more){
global $post;
return '... <a class="view-article" href="' . get_permalink($post->ID) . '">' . __('', 'wpden') . '</a>';
}
And I called it in my template_post.php:
<?php wpden_excerpt('wpden_mag_len','wpden_more_view'); ?>
The code in question that I wanted to use for my custom wpden_excerpt is either this:
add_filter( 'wp_trim_excerpt', 'my_custom_excerpt', 10, 2 );
function my_custom_excerpt($text, $raw_excerpt) {
if( ! $raw_excerpt ) {
$content = apply_filters( 'the_content', get_the_content() );
$text = substr( $content, 0, strpos( $content, '</p>' ) + 4 );
}
return $text;
}
from this site or from the other stack overflow question
$wpse0001_excerpt = get_the_content('');
$wpse0001_excerpt = strip_shortcodes( $wpse0001_excerpt );
$wpse0001_excerpt = apply_filters('the_content', $wpse0001_excerpt);
// Here we choose how many paragraphs do we want to cutthe excerpt at, This part thanks to Clément Malet
$wpse0001_excerpt = "<p>$wpse0001_excerpt</p>";
$wanted_number_of_paragraph = 2;
$tmp = explode ('</p>', $wpse0001_excerpt);
for ($i = 0; $i < $wanted_number_of_paragraph; ++$i) {
if (isset($tmp[$i]) && $tmp[$i] != '') {
$tmp_to_add[$i] = $tmp[$i];
}
}
$wpse0001_excerpt = implode('</p>', $tmp_to_add) . '</p>';
$wpse0001_excerpt = str_replace(']]>', ']]>', $wpse0001_excerpt);
$excerpt_end = ' ' . ' » ' . sprintf(__( 'Read more about: %s »', 'pietergoosen' ), get_the_title()) . '';
$excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end);
//$pos = strrpos($wpse0001_excerpt, '</');
//if ($pos !== false)
// Inside last HTML tag
//$wpse0001_excerpt = substr_replace($wpse0001_excerpt, $excerpt_end, $pos, 0);
//else
// After the content
$wpse0001_excerpt .= $excerpt_end;
return $wpse0001_excerpt;
}
return apply_filters('wpse0001_custom_wp_trim_excerpt', $wpse0001_excerpt, $raw_excerpt);
}
endif;
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'wpse0001_custom_wp_trim_excerpt');
The thing is that those codes in question apply to the the_excerpt and override the custom excerpt that I made. I tried to format the code like this:
function wpden_excerpt($text = '')
{
global $post;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace('\]\]\>', ']]>', $text);
$text = preg_replace('#<script[^>]*?>.*?</script>#si', '', $text);
$text = strip_tags($text, '<p>');
$excerpt_length = 80;
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words)> $excerpt_length) {
array_pop($words);
array_push($words, '[...]');
$text = implode(' ', $words);
}
}
return $text;
}
and called it in the template as
<?php wpden_excerpt('text'); ?>
But it's not working. What was wrong and how do I fix it?
UPDATE
I still need help!!! I tried many different combo of custom excerpt and limiting the excerpt to one paragraph and I wasn't able to do so... Please help!!
Thanks to my brother's help, I was able to edit the code to show two paragraphs for a custom excerpt:
// Create the Custom Excerpts callback
function wpden_excerpt()
{
global $post;
$output = get_the_content();
$wanted_number_of_paragraph = 2;
$tmp = explode ('</p>', $output);
for ($i = 0; $i < $wanted_number_of_paragraph; ++$i) {
if (isset($tmp[$i]) && $tmp[$i] != '') {
$tmp_to_add[$i] = $tmp[$i];
}
}
$output = implode('</p>', $tmp_to_add) . '</p>';
echo $output;
}
and call it in my template file as
<?php wpden_excerpt(); ?>

Foundation Magellan auto generate

I'd like to auto generate magellan on subpages from h3 tags.
For this purpose I tried jameswlane script (https://gist.github.com/jameswlane/f1eabeedf430ef67318d), and I changed only h2 tags to h3. It seems I dont aunderstand this code well.
I thought I only need to paste this code in my header.php file from wordpress theme and it will automatically sweep the DOM content for h3 tags, but it didn't.
Nothing shows up, even an empty div.
Used the followinf line as init:
<?php $tag = 'h3'; $html = get_the_content(); $items = getTextBetweenTags( $tag, $html ); ?>
Can I ask you for an advise in this matter?
<?php
function getTextBetweenTags($tag, $html, $strict=0) {
$dom = new domDocument;
if($strict==1) {
$dom->loadXML($html);
} else {
$dom->loadHTML($html);
}
$dom->preserveWhiteSpace = false;
$content = $dom->getElementsByTagname($tag);
$out = array();
foreach ($content as $item) {
$out[] = $item->nodeValue;
}
return $out;
}
function create_slug($string){
$slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
return $slug;
}
function create_magellan($items){
$output .= '<div data-magellan-expedition="fixed">' . PHP_EOL;
$output .= '<dl class="sub-nav">' . PHP_EOL;
foreach( $items as $item ) {
$output .= '<dd data-magellan-arrival="' . create_slug( $item ) . '">' . $item . '</dd>';
}
$output .= '</dl>' . PHP_EOL;
$output .= '</div>' . PHP_EOL;
add_filter('the_content', 'my_formatter', 99);
echo $output;
}
function my_formatter($content) {
$new_content = '';
$tag = 'h3';
$pattern_full = '{(<' . $tag . '>.*?</' . $tag . '>)}is';
$pattern_contents = '{<' . $tag . '>(.*?)</' . $tag . '>}is';
$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($pieces as $piece) {
if (preg_match($pattern_contents, $piece, $matches)) {
$test = $matches[1];
$new_content .= '<a name="'.create_slug($test).'"></a>'.PHP_EOL.'<'.$tag.' data-magellan-destination="'.create_slug($test).'">'.$test.'</'.$tag.'>'.PHP_EOL;
} else {
$new_content .= wptexturize(wpautop($piece));
}
}
return $new_content;
}
?>
EDIT
Something worked and returned error:
Warning: DOMDocument::loadHTML(): Empty string supplied as input in /www/ilee_www/www/2.goldbaltic/dev.goldbaltic.pl/wp-content/themes/dermiclab_fs/partials/2.Nav/mainNav.php on line 47
the line number 47 in my file is
$dom->loadHTML($html);
from
function getTextBetweenTags($tag, $html, $strict=0) {
$dom = new domDocument;
if($strict==1) {
$dom->loadXML($html);
} else {
$dom->loadHTML($html);
}
$dom->preserveWhiteSpace = false;
$content = $dom->getElementsByTagname($tag);
$out = array();
foreach ($content as $item) {
$out[] = $item->nodeValue;
}
return $out;
}

WordPress plugin adds the number 1 to content if activated

My WP plugin bizarely adds the numeral 1 to the content if the plugin is active.
add_filter( 'the_content', 'poc_shop_cart_button_filter' );
function poc_shop_cart_button_filter($the_content) {
$new_content = $the_content;
$new_content .= include(WP_CONTENT_DIR . "/custom_php/shop-cart-button.php");
return $new_content;
}
This is the page I am including with the plugin:
if(isset($_COOKIE['_abs_34287GjNW'])){
$cookieID = htmlspecialchars($_COOKIE['_abs_34287GjNW'], ENT_QUOTES, 'UTF-8');
} else {
$cookieID = '';
}
$supplierID = get_bloginfo('name');
require(ABSPATH . 'wp-content/custom_php/includes/connectDB.php');
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$conn->exec("SET CHARACTER SET utf8");
$sql = "SELECT COUNT(*) AS count
FROM `shoppingCart`
WHERE supplierID=:supplierID
AND cookieID = :cookieID";
$sqlprep = $conn->prepare($sql);
$ar_val = array(':supplierID'=>$supplierID,
':cookieID'=>$cookieID);
if($sqlprep->execute($ar_val)) {
while($row = $sqlprep->fetch(PDO::FETCH_OBJ)){
if($row->count=='' || $row->count==0){
$count='0';
} else{
$count = $row->count;
}
}
}
if($count == 1){
$items = "item";
} else {
$items = "items";
}
if(is_page(array(48)) || $count < 1){
echo '<div class="shopCartNoButton">';
echo "<img src='" . get_template_directory_uri() . "/images/cart-icon.png' alt=''>";
echo " <b>$count $items </b>";
echo '</div><div class="clearFix"></div>';
} else {
echo '<div class="shopCartButton">';
echo "<img src='" . get_template_directory_uri() . "/images/cart-icon.png' alt=''>";
echo " <b>$count $items </b>";
echo " <a href='office-seating/checkout/' class='btn btn-warning'> Checkout >></a>";
echo '</div><div class="clearFix"></div>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
So the solution to this after MUCH Googling is as follows:
$filename = get_include_contents('somefile.php');
function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
return ob_get_clean();
}
return false;
}
The code:
include( $filename );
returns the included file + the value 1 because the include was successful.
One must use output buffering to include a PHP file into a string and not return the value 1 with the returned file contents.
I had similar problem. It is because include returns value of the call, i.e. "true" or 1 when WordPress render data via echo. Just use file_get_contents it will help.

How do I grab an external variable after the external file has been executed?

I'm trying to grab a variable from an external file, but I need the file to execute first. How can I do that?
I need to grab the variables: $title, $description, $link, $date, and $author.
rss.php:
$rss2_file = 'http://www.rune-pk.org/forums/external.php?forumids=2&type=rss2';
$is_item = false;
$tag = '';
$title = '';
$description = '';
$link = '';
$date = '';
$author = '';
function character_data($parser, $data) {
global $is_item, $tag, $title, $description, $link, $date, $author;
if ($is_item) {
switch ($tag) {
case "TITLE":
$title .= $data;
break;
case "DESCRIPTION":
$description .= $data;
break;
case "LINK":
$link .= $data;
break;
case "PUBDATE":
$date .= $data;
break;
case "AUTHOR":
$author .= $data;
break;
}
}
}
function begin_element($parser, $name) {
global $is_item, $tag;
if ($is_item) {
$tag = $name;
} else if ($name == "ITEM") {
$is_item = true;
}
}
function end_element($parser, $name) {
global $is_item, $title, $description, $link, $date, $author, $rss2_output;
if ($name == "ITEM") {
$rss2_output .= "<dt><strong><a href='" . trim($link) . "'>" . htmlspecialchars(trim($title)) . "</a></strong> - " . htmlspecialchars(trim($date)) . " by <em>" . htmlspecialchars(trim($author)) . "</em></dt><dd>" . htmlspecialchars(trim($description)) . "</dd>";
$title = "";
$description = "";
$link = "";
$date = "";
$author = "";
$is_item = false;
}
}
$parser = xml_parser_create();
xml_set_element_handler($parser, "begin_element", "end_element");
xml_set_character_data_handler($parser, "character_data");
$fp = fopen($rss2_file, "r");
while ($data = fread($fp, 4096)) {
xml_parse($parser, $data, feof($fp));
}
fclose($fp);
xml_parser_free($parser);
echo "Latest Announcements:";
echo $rss2_output;
?>
index.php:
include 'rss.php';
echo $rss->title;
?>
What you were trying is used for accessing variables stored in classes. But that's not the case here so do it this way:
<?php
include 'rss.php';
echo $title;
?>

Categories