2017-02-22 1 views
2

私のsingle.phpページで私はIDで特定の投稿のカスタム長の抜粋を私に与える機能を作成しようとしています。私のカスタムget_the_excerpt()はIDで抜粋することができません

以下は、私が実行している2つの機能です。

/* Custom get_the_excerpt to allow getting Post excerpt by ID */ 
function custom_get_the_excerpt($post_id) { 
    global $post; 
    $save_post = $post; 
    $post = get_post($post_id); 
    $output = get_the_excerpt($post); 
    $post = $save_post; 
    return $output; 
} 

/* Change Excerpt length */ 
function excerpt($num, $post_id = '') { 
    $limit = $num+1; 
    $excerpt = explode(' ', custom_get_the_excerpt($post_id), $limit); 
    array_pop($excerpt); 
    $excerpt = implode(" ",$excerpt)."&#8230"; 
    echo $excerpt; 
} 

私は関数を呼び出すために使用しています。

<?php $previous = get_previous_post(); 
echo excerpt('30', $previous -> ID); ?> 

私はget_the_excerptにそれが現在のポストの抜粋ではなく、前回の記事の抜粋を返すことを渡すとき$ポストはしかし、私の前のポストの情報を与えているさに実行しています問題。これに

EDIT

変更された機能のいくつかの人々はまだ

/* Change Excerpt length */ 
function excerpt($num, $post_id = '') { 
    $limit = $num+1; 
    $excerpt = explode(' ', get_the_excerpt($post_id), $limit); 
    array_pop($excerpt); 
    $excerpt = implode(" ",$excerpt)."&#8230"; 
    echo $excerpt; 
} 

)(私はちょうどget_the_excerptするの$ post_idのを渡すことができます何の変化を私に言ったん後。あなたが を表示していました文字の数 - $ post_idの:あなたがコンテンツ

と取得したい記事のID: を - であれば - $ num個 :

+0

「エコー抜粋('30 '、$ previous-> ID)」の「 - >」の前後に空白があるのは誤植ですか? 「私はそれがうまくいかないと確信しています。そして、あなたがカスタム呼び出しで$ post_idを定義していないと思うので、現在の$ postを使います。また、私は 'get_post'を気にする必要はないと確信しています。ちょうどpost_idを渡してget_the_excerptがうまくいくはずです。 – MacPrawn

+0

" - >" の周りに空白を入れても変更はありませんまた、私はちょうど$ post_idを渡すことができますが、それでも問題は変わりません。 :( –

答えて

0

次の関数は2 parmetersを取得します文字列の末尾に "..."を付けて指定した文字数を返します。 - $ numが0の場合、最初の完全停止までコンテンツを返します。

function my_custom_excerpt($num = 0,$post_id=''){ 
$post=get_post($post_id); 
$content=$post->post_content; 
if(strpos($content,'&lt;!&#8211;more&#8211;&gt;')>0){ 
    return substr($content,0,strpos($content,'&lt;!&#8211;more&#8211;&gt;')); 
}else{ 
    if($num===0){ 
     return substr($content,0,strpos($content,'.')+1); 
    }else{ 
     return substr($content,0,$num).((strlen($content)>$num)?"...":""); 
    } 
} 
} 
1

Addi setup_postdata($ post)のng;私の問題を修正しました。

function custom_get_the_excerpt($post_id) { 
    global $post; 
    $save_post = $post; 
    $post = get_post($post_id); 
    setup_postdata($post); 
    $output = get_the_excerpt($post); 
    wp_reset_postdata(); 
    $post = $save_post; 
    return $output; 
} 
関連する問題