I have this excerpt function that cuts the content after the first paragraph (after the first </p> tag.
I need to modify this so I can cut the content after the second or third paragraph, that is the second or third </p> tag. My knowledge of php is not great, so any help will be appreciated.
Here is my function
if ( ! function_exists( 'wpse0001_custom_wp_trim_excerpt' ) ) :
function wpse0001_custom_wp_trim_excerpt($wpse0001_excerpt) {
global $post;
$raw_excerpt = $wpse0001_excerpt;
if ( '' == $wpse0001_excerpt ) {
$wpse0001_excerpt = get_the_content('');
$wpse0001_excerpt = strip_shortcodes( $wpse0001_excerpt );
$wpse0001_excerpt = apply_filters('the_content', $wpse0001_excerpt);
$wpse0001_excerpt = substr( $wpse0001_excerpt, 0, strpos( $wpse0001_excerpt, '</p>' ) + 4 );
$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');
EDIT
This is the section of code I need to modify, but not sure how
$wpse0001_excerpt = substr( $wpse0001_excerpt, 0, strpos( $wpse0001_excerpt, '</p>' ) + 4 );
$wpse0001_excerpt = "<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p>";
$wanted_number_of_paragraph = 3;
$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>';
echo $wpse0001_excerpt;
// Output : <p>1</p><p>2</p><p>3</p>
Related
I'm trying to make my list of tags, organized with first letter heads, to show Alphabet (a, b, c, d, etc..) first then numbers and symbols (#,1,2,3 etc..)
here is my code:
<?php $list = '';
$tags = get_tags();
$groups = array();
if( $tags && is_array( $tags ) ) {
foreach ($tags as $tag) {
$first_letter = strtoupper( $firstLetter );
$groups[ $first_letter ][] = $tag;
}
if( !empty( $groups ) ) {
foreach( $groups as $letter => $tags ) {
usort($letter, 'myComparison');
$list .= "\n\t" . '</ul><h2>' . apply_filters( 'the_title', $letter ) .'</h2>';
$list .= "\n\t" . '</ul><ul id="archiveEach">';
foreach( $tags as $tag ) {
$lower = strtolower($tag->name);
$name = str_replace(' ', ' ', $tag->name);
$naam = str_replace(' ', '-', $lower);
$link = $tag->link;
$list .= "\n\t\t" . '<li>'.$name.'</li>';
}}}}else $list .= "\n\t" . '<p>Sorry, but no tags were found</p>';
print_r( $list);
?>
I've tried to sort using different functionalities, using this
function myComparison($a, $b){
if(is_numeric($a) && !is_numeric($b))
return 1;
else if(!is_numeric($a) && is_numeric($b))
return -1;
else
return ($a < $b) ? -1 : 1;
}
then calling the function using usort($differnentelements, 'myComparison')
I cannot get it to work -- any suggestions would be really greatly appreciated. thanks!
I'm new to PHP, still learning, so please excuse and kindly tell me what would be the appropriate fix. I used the breadcrumb script from here answered by Pieter Goosen. I want the breadcrumbs to work with google and schema, the part that isn't working is the <meta itemprop="position" content="number" /> tag. The content="number" needs to be set for each crumb, in order (1,2,3...). On line 8 I added $i = 1;, then changed $link_after = '<meta itemprop="position" content="' . $i++ . '" /></li>';. But $i++ is not printing a new sequential number, it is just repeating itself as if there was no other $i++. My guess is to apply the rule globally and to search for $i++ used, as it's probably being applied closed within the rule, but wouldn't know how to do this.
Code:
function get_hansel_and_gretel_breadcrumbs()
{
// Set variables for later use
$here_text = __( 'You are currently here!' );
$home_link = home_url('/');
$home_text = __( 'Home' );
$link_before = '<span typeof="v:Breadcrumb">';
$i = 1;
$link_after = '<meta itemprop="position" content="' . $i++ . '" /></span>'
$link_attr = ' rel="v:url" property="v:title"';
$link = $link_before . '<a' . $link_attr . ' href="%1$s">%2$s</a>' . $link_after;
$delimiter = ' » '; // Delimiter between crumbs
$before = '<span class="current">'; // Tag before the current crumb
$after = '</span>'; // Tag after the current crumb
$page_addon = ''; // Adds the page number if the query is paged
$breadcrumb_trail = '';
$category_links = '';
/**
* Set our own $wp_the_query variable. Do not use the global variable version due to
* reliability
*/
$wp_the_query = $GLOBALS['wp_the_query'];
$queried_object = $wp_the_query->get_queried_object();
// Handle single post requests which includes single pages, posts and attatchments
if ( is_singular() )
{
/**
* Set our own $post variable. Do not use the global variable version due to
* reliability. We will set $post_object variable to $GLOBALS['wp_the_query']
*/
$post_object = sanitize_post( $queried_object );
// Set variables
$title = apply_filters( 'the_title', $post_object->post_title );
$parent = $post_object->post_parent;
$post_type = $post_object->post_type;
$post_id = $post_object->ID;
$post_link = $before . $title . $after;
$parent_string = '';
$post_type_link = '';
if ( 'post' === $post_type )
{
// Get the post categories
$categories = get_the_category( $post_id );
if ( $categories ) {
// Lets grab the first category
$category = $categories[0];
$category_links = get_category_parents( $category, true, $delimiter );
$category_links = str_replace( '<a', $link_before . '<a' . $link_attr, $category_links );
$category_links = str_replace( '</a>', '</a>' . $link_after, $category_links );
}
}
if ( !in_array( $post_type, ['post', 'page', 'attachment'] ) )
{
$post_type_object = get_post_type_object( $post_type );
$archive_link = esc_url( get_post_type_archive_link( $post_type ) );
$post_type_link = sprintf( $link, $archive_link, $post_type_object->labels->singular_name );
}
// Get post parents if $parent !== 0
if ( 0 !== $parent )
{
$parent_links = [];
while ( $parent ) {
$post_parent = get_post( $parent );
$parent_links[] = sprintf( $link, esc_url( get_permalink( $post_parent->ID ) ), get_the_title( $post_parent->ID ) );
$parent = $post_parent->post_parent;
}
$parent_links = array_reverse( $parent_links );
$parent_string = implode( $delimiter, $parent_links );
}
// Lets build the breadcrumb trail
if ( $parent_string ) {
$breadcrumb_trail = $parent_string . $delimiter . $post_link;
} else {
$breadcrumb_trail = $post_link;
}
if ( $post_type_link )
$breadcrumb_trail = $post_type_link . $delimiter . $breadcrumb_trail;
if ( $category_links )
$breadcrumb_trail = $category_links . $breadcrumb_trail;
}
// Handle archives which includes category-, tag-, taxonomy-, date-, custom post type archives and author archives
if( is_archive() )
{
if ( is_category()
|| is_tag()
|| is_tax()
) {
// Set the variables for this section
$term_object = get_term( $queried_object );
$taxonomy = $term_object->taxonomy;
$term_id = $term_object->term_id;
$term_name = $term_object->name;
$term_parent = $term_object->parent;
$taxonomy_object = get_taxonomy( $taxonomy );
$current_term_link = $before->labels->singular_name . '<li class="curr-cat" itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"><span itemprop="name">' . $term_name . '</span><meta itemprop="position" content="' . $i++ . '" /></li>';
$parent_term_string = '';
if ( 0 !== $term_parent )
{
// Get all the current term ancestors
$parent_term_links = [];
while ( $term_parent ) {
$term = get_term( $term_parent, $taxonomy );
$parent_term_links[] = sprintf( $link, esc_url( get_term_link( $term ) ), $term->name );
$term_parent = $term->parent;
}
$parent_term_links = array_reverse( $parent_term_links );
$parent_term_string = implode( $delimiter, $parent_term_links );
}
if ( $parent_term_string ) {
$breadcrumb_trail = $parent_term_string . $delimiter . $current_term_link;
} else {
$breadcrumb_trail = $current_term_link;
}
} elseif ( is_author() ) {
$breadcrumb_trail = __( 'Author archive for ') . $before . $queried_object->data->display_name . $after;
} elseif ( is_date() ) {
// Set default variables
$year = $wp_the_query->query_vars['year'];
$monthnum = $wp_the_query->query_vars['monthnum'];
$day = $wp_the_query->query_vars['day'];
// Get the month name if $monthnum has a value
if ( $monthnum ) {
$date_time = DateTime::createFromFormat( '!m', $monthnum );
$month_name = $date_time->format( 'F' );
}
if ( is_year() ) {
$breadcrumb_trail = $before . $year . $after;
} elseif( is_month() ) {
$year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );
$breadcrumb_trail = $year_link . $delimiter . $before . $month_name . $after;
} elseif( is_day() ) {
$year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );
$month_link = sprintf( $link, esc_url( get_month_link( $year, $monthnum ) ), $month_name );
$breadcrumb_trail = $year_link . $delimiter . $month_link . $delimiter . $before . $day . $after;
}
} elseif ( is_post_type_archive() ) {
$post_type = $wp_the_query->query_vars['post_type'];
$post_type_object = get_post_type_object( $post_type );
$breadcrumb_trail = $before . $post_type_object->labels->singular_name . $after;
}
}
// Handle the search page
if ( is_search() ) {
$breadcrumb_trail = __( 'Search query for: ' ) . $before . get_search_query() . $after;
}
// Handle 404's
if ( is_404() ) {
$breadcrumb_trail = $before . __( 'Error 404' ) . $after;
}
// Handle paged pages
if ( is_paged() ) {
$current_page = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : get_query_var( 'page' );
$page_addon = $before . sprintf( __( ' ( Page %s )' ), number_format_i18n( $current_page ) ) . $after;
}
$breadcrumb_output_link = '';
$breadcrumb_output_link .= '<div class="breadcrumb">';
if ( is_home()
|| is_front_page()
) {
// Do not show breadcrumbs on page one of home and frontpage
if ( is_paged() ) {
$breadcrumb_output_link .= $here_text . $delimiter;
$breadcrumb_output_link .= '' . $home_text . '';
$breadcrumb_output_link .= $page_addon;
}
} else {
$breadcrumb_output_link .= $here_text . $delimiter;
$breadcrumb_output_link .= '' . $home_text . '';
$breadcrumb_output_link .= $delimiter;
$breadcrumb_output_link .= $breadcrumb_trail;
$breadcrumb_output_link .= $page_addon;
}
$breadcrumb_output_link .= '</div><!-- .breadcrumbs -->';
return $breadcrumb_output_link;
}
I would like to make a small change in a code for a table of contents.
I want to add a sign in front of each heading. The character should be recognized as text.
I've tried a few things, but unfortunately I have not found the right variable.
The code comes from a plugin for Wordpress
I have already tried the following variables:
$items
$tic
$find
$replace
$post
Here is the code that prints the list:
if ( $tic->is_eligible($custom_toc_position) ) {
extract( $args );
$items = $tic->extract_headings( $find, $replace,wptexturize($post->post_content) );
$title = ( array_key_exists('title', $instance) ) ? apply_filters('widget_title', $instance['title']) : '';
if ( strpos($title, '%PAGE_TITLE%') !== false ) $title = str_replace( '%PAGE_TITLE%', get_the_title(), $title );
if ( strpos($title, '%PAGE_NAME%') !== false ) $title = str_replace( '%PAGE_NAME%', get_the_title(), $title );
$hide_inline = $toc_options['show_toc_in_widget_only'];
$css_classes = '';
// bullets?
if ( $toc_options['bullet_spacing'] )
$css_classes .= ' have_bullets';
else
$css_classes .= ' no_bullets';
if ( $items ) {
// before widget (defined by themes)
echo $before_widget;
// display the widget title if one was input (before and after titles defined by themes)
if ( $title ) echo $before_title . $title . $after_title;
// display the list
echo '<ul class="toc_widget_list' . $css_classes . '">' . $items . '</ul>';
// after widget (defined by themes)
echo $after_widget;
}
This are the full code of function extract_headings:
public function extract_headings( &$find, &$replace, $content = '' )
{
$matches = array();
$anchor = '';
$items = false;
// reset the internal collision collection as the_content may have been triggered elsewhere
// eg by themes or other plugins that need to read in content such as metadata fields in
// the head html tag, or to provide descriptions to twitter/facebook
$this->collision_collector = array();
if ( is_array($find) && is_array($replace) && $content ) {
// get all headings
// the html spec allows for a maximum of 6 heading depths
if ( preg_match_all('/(<h([1-6]{1})[^>]*>).*<\/h\2>/msuU', $content, $matches, PREG_SET_ORDER) ) {
// remove undesired headings (if any) as defined by heading_levels
if ( count($this->options['heading_levels']) != 6 ) {
$new_matches = array();
for ($i = 0; $i < count($matches); $i++) {
if ( in_array($matches[$i][2], $this->options['heading_levels']) )
$new_matches[] = $matches[$i];
}
$matches = $new_matches;
}
// remove specific headings if provided via the 'exclude' property
if ( $this->options['exclude'] ) {
$excluded_headings = explode('|', $this->options['exclude']);
if ( count($excluded_headings) > 0 ) {
for ($j = 0; $j < count($excluded_headings); $j++) {
// escape some regular expression characters
// others: http://www.php.net/manual/en/regexp.reference.meta.php
$excluded_headings[$j] = str_replace(
array('*'),
array('.*'),
trim($excluded_headings[$j])
);
}
$new_matches = array();
for ($i = 0; $i < count($matches); $i++) {
$found = false;
for ($j = 0; $j < count($excluded_headings); $j++) {
if ( #preg_match('/^' . $excluded_headings[$j] . '$/imU', strip_tags($matches[$i][0])) ) {
$found = true;
break;
}
}
if (!$found) $new_matches[] = $matches[$i];
}
if ( count($matches) != count($new_matches) )
$matches = $new_matches;
}
}
// remove empty headings
$new_matches = array();
for ($i = 0; $i < count($matches); $i++) {
if ( trim( strip_tags($matches[$i][0]) ) != false )
$new_matches[] = $matches[$i];
}
if ( count($matches) != count($new_matches) )
$matches = $new_matches;
// check minimum number of headings
if ( count($matches) >= $this->options['start'] ) {
for ($i = 0; $i < count($matches); $i++) {
// get anchor and add to find and replace arrays
$anchor = $this->url_anchor_target( $matches[$i][0] );
$find[] = $matches[$i][0];
$replace[] = str_replace(
array(
$matches[$i][1], // start of heading
'</h' . $matches[$i][2] . '>' // end of heading
),
array(
$matches[$i][1] . '<span id="' . $anchor . '">',
'</span></h' . $matches[$i][2] . '>'
),
$matches[$i][0]
);
// assemble flat list
if ( !$this->options['show_heirarchy'] ) {
$items .= '<li><a href="#' . $anchor . '">';
if ( $this->options['ordered_list'] ) $items .= count($replace) . ' ';
$items .= strip_tags($matches[$i][0]) . '</a></li>';
}
}
// build a hierarchical toc?
// we could have tested for $items but that var can be quite large in some cases
if ( $this->options['show_heirarchy'] ) $items = $this->build_hierarchy( $matches );
}
}
}
return $items;
}
I tried it like this:
$items = '>'.$items
$tic = '>'.$tic
$find = '>'.$find
.
.
.
Unfortunately, nothing has hit the right place
$ items addressed only the entire list
The other Variables had no effect or led to errors
The extract_headings is creating the list items. This section of the function...
// assemble flat list
if ( !$this->options['show_heirarchy'] ) {
$items .= '<li><a href="#' . $anchor . '">';
if ( $this->options['ordered_list'] ) $items .= count($replace) . ' ';
$items .= strip_tags($matches[$i][0]) . '</a></li>';
}
Should look like this:
// assemble flat list
if ( !$this->options['show_heirarchy'] ) {
$items .= '<li><a href="#' . $anchor . '">>';
if ( $this->options['ordered_list'] ) $items .= count($replace) . ' ';
$items .= strip_tags($matches[$i][0]) . '</a></li>';
}
You can see I've added an extra > inside the hyperlink on the third line. If adding an extra > causes any issues, you can also use >.
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(); ?>
I got this snippet of code to display my post views counter in my wordpress website.
function bac_PostViews($post_ID) {
$count_key = 'post_views_count';
$count = get_post_meta($post_ID, $count_key, true);
if($count == ''){
$count = 0;
delete_post_meta($post_ID, $count_key);
add_post_meta($post_ID, $count_key, '0');
return $count . ' Visitas';
}else{
$count++;
update_post_meta($post_ID, $count_key, $count);
if($count == '1'){
return $count . ' Visita';
}
else {
return $count . ' Visitas';
}
}
}
Then, in my 'single.php' file I added this code for retrieving the count:
$blog_number_visits = bac_PostViews(get_the_ID());
And this code for showing the count:
if ( $blog_author || $blog_date || $show_comments_number ) {
$meta .= '<p class="meta">';
if ( $blog_date ) $meta .= esc_html( date_i18n( $date_format, strtotime( get_the_time( 'Y-m-d' ) ) ) );
if ( $blog_date && $blog_author ) $meta .= ' — ';
if ( $blog_author ) $meta .= '<span class="visitas">' . $blog_number_visits . ' </span>';
if ( ( $blog_date || $blog_author ) && $show_comments_number ) $meta .= ' — ';
if ( $show_comments_number ) $meta .= '<span class="commentCount">' . $comments_number . '</span>';
$meta .= '</p>';
}
My problem is that I can't display it in the home page. The HOME is getting the code from functions.php and if I put my snippet of code in functions.php and try to display it from there... It always shows 0 VIEWS.
I think maybe the problem is that functions.php is not inside 'the LOOP' and thats why is not displaying in the home.
My website: Website home where I want to display VIEWS COUNTER