2011-03-15 16 views
5

मैं WP से अंतिम तीन पोस्ट प्राप्त करने के लिए अपने स्वयं के वेबपृष्ठ में लूप का उपयोग कर रहा हूं।एक वर्डप्रेस पोस्ट से सीमित, टेक्स्ट-केवल अंश प्राप्त करें?

<?php 
     $args = array('numberposts' => 3); 
     $myposts = get_posts($args); 
     foreach($myposts as $post) : setup_postdata($post); ?> 

        <!-- DATE --> 
        <div class="date"> 
        <?php the_time('m F Y');?> 
        </div> 

        <!-- TITLE --> 
        <div class="title"> 
        <?php the_title(); ?> 
        </div> 

        <!-- SNIPPET --> 
        <div class="content"> 
        <?php the_excerpt(); ?> 
        </div> 
<?php endforeach; ?> 

सब कुछ ठीक काम कर रहा है - the_excerpt() को छोड़कर। पूर्वावलोकन के रूप में दिखाने के लिए मुझे पोस्ट से सादा पाठ के लगभग 15-20 शब्दों की आवश्यकता है। मैं यह कार्य कैसे करूं?

धन्यवाद :)

उत्तर

4

आप पोस्ट के पहले 20 शब्दों हड़पने के लिए अगर कोई अंश उपलब्ध है कुछ इस तरह उपयोग करने का प्रयास कर सकता है।

$content = get_the_content(); 
echo substr($content, 0, 20); 
+0

क्षमा करें यह नहीं शब्द मैं स्पष्ट रूप से सोच एकदम चमक पात्रों हड़पने के लिए, यदि आप शब्द चाहता था यहाँ यह कैसे करना है [यहां] पर एक समारोह है (http://www.nutt.net/2004/12/29/php-a-function-to-return-the-first-n-words-from-a-string/) – Tianbo84

2

इस प्रयास करें:

पोस्ट चित्र शामिल हैं:

$content = get_the_content(); 
$content = apply_filters('the_content', $content); 
$content = str_replace(']]>',']]&gt;', $content); 
echo substr(strip_tags($content),0,100); 

और बिना छवियों: substr का उपयोग कर

$content = get_the_content(); 
echo substr($content, 0, 25); 
9

से बचें। क्यूं कर?

यदि आप substr() का उपयोग करते हैं, तो यह अंतिम HTML टैग को छोटा कर सकता है और विकृत HTML को वापस कर सकता है।

पहिया का पुन: आविष्कार न करें!

वर्डप्रेस 3.3 के बाद wp_trim_words() नामक एक नया कोर फ़ंक्शन है।

wp_trim_words पैरामीटर तोड़ डाउन:

wp_trim_words($text, $num_words, $more); 

$text 
    (string) (required) Text to trim 
    Default: None 

$num_words 
    (integer) (optional) Number of words 
    Default: 55 

$more 
    (string) (optional) What to append if $text needs to be trimmed. 
    Default: '…' 

उदाहरण उपयोगों:

<?php echo wp_trim_words(get_the_content(), 40, '...'); ?> 

<?php echo wp_trim_words(get_the_excerpt(), 20, '... read more...'); ?> 
0

functions.php में इस कोड डाल

function new_excerpt_length($length) { 
    return 20;} 
add_filter('excerpt_length', 'new_excerpt_length'); 

और बस अपने टेम्पलेट पेज या index.php फ़ाइल से इस समारोह फोन

the_excerpt(); 
संबंधित मुद्दे