• Chris Lowry

    (@medical-revision)


    I’ve been attempting to make a function that allows me to adjust excerpts. I’m fairly amateur at all this, so I’m not completely clear on exactly how add_filter actually works.

    1. Does it replace a filter with a new one, but requires the new one will pass the same arguments? For example, in my link it decides that $length is a WP_Object for some reason and then doesn’t work.

    2. Does this mean that I’ll always have to call my custom function to use the extra arguments? So, for example, rather than calling get_the_excerpt(”,5) to get a 5 word excerpt, I’ll need to call excerptional(”,5) to do it?

    function excerptional ($text,$length) {
    $raw_excerpt = $text;
    if ( '' == $text ) {
        
        $text = get_the_content('');
        $text = strip_shortcodes( $text );
     
        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]>', $text);
        //delete all header text, gives you rubbish short paragraphs in excerpts otherwise
    	$regex = array ('#\<h1[^]]*\>(.*?)\</h1\>#','#\<h2[^]]*\>(.*?)\</h2\>#','#\<h3[^]]*\>(.*?)\</h3\>#','#\<h4[^]]*\>(.*?)\</h4\>#','#\<h5[^]]*\>(.*?)\</h5\>#','#\<h6[^]]*\>(.*?)\</h6\>#');
    	$text = preg_replace($regex, '$1', $text);
    	
    	// if ($length=='') {$length = 'monkey';}
    	
    	// change headers to paragraphs
    	// $text = str_replace(array('<h1>', '<h2>', '<h3>', '<h4>', '<h5>', '<h6>'),'<p>', $text);
    	// $text = str_replace(array('</h1>', '</h2>', '</h3>', '</h4>', '</h5>', '</h6>'),'</p>', $text);
    	
        $allowed_tags = '<p>,<a>,<em>,<strong>';
        $text = strip_tags($text, $allowed_tags);
        
    	if ($length!='') {$excerpt_word_count = $length;}
    	else {$excerpt_word_count = 250;}
    	
        $excerpt_length = apply_filters('excerpt_length', $excerpt_word_count); 
         
        $excerpt_end = '';
        $excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end);
        
        $words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
        if ( count($words) > $excerpt_length ) {
            array_pop($words);
            $text = implode(' ', $words);
            $text = $text;
        } else {
           $text = implode(' ', $words);
        }
    
        //explode to get the first two paragraphs
        $paras = explode("</p>",$text);
        //$text = "<strong>".$paras[0]."</strong>".$paras[1];
        $text = $paras[0];
    }
    return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
    }
    remove_filter('get_the_excerpt', 'wp_trim_excerpt');
    add_filter('get_the_excerpt', 'excerptional',10,2);

    The page I need help with: [log in to see the link]

Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)

The topic ‘Custom Excerpts causing WP_Post variable error’ is closed to new replies.