2016-09-07 51 views
0

我需要在我的主頁上顯示摘錄。我有標準的帖子和一個自定義的帖子類型'網絡研討會'。 CPT的'網絡研討會'有一個自定義字段,使用ACF的'webinar_description',相當於普通帖子中的'description'。使用the_content()在首頁顯示摘錄;和ACF

我能夠通過添加一個過濾器的這樣的「webinar_description」同時顯示,:

add_filter('the_content','add_my_custom_field'); 
function add_my_custom_field($data) { 
    $data .= get_field('webinar_description'); 
    return $data; 
} 

現在都在我文章類型顯示,但它顯示了整個「說明」或「webinar_description」領域。我需要用40字來修剪它,然後添加一個'...閱讀更多內容',其中'閱讀更多'是本文的鏈接。

我已經試過了,但它僅適用於正常「後」類型字段「描述」它不會對我的「研討會」自定義後類型的工作 - >自定義字段「研討會,說明」

<?php $content = get_the_content(); echo mb_strimwidth($content, 0, 400, '<a href="' . get_permalink() . '">[Read more]</a>');?> 

如何創建將限制爲400(或其他)字符並添加鏈接的過濾器或函數?

回答

0

不知道這是否會幫助任何人在類似的情況,但這是我如何解決它。首先,在functions.php中進行自定義後類型的可用

function cpt_get_excerpt(){ 
    $excerpt = get_field('webinar_description'); 
    $excerpt = preg_replace(" (\[.*?\])",'',$excerpt); 
    $excerpt = strip_shortcodes($excerpt); 
    $excerpt = strip_tags($excerpt); 
    $excerpt = substr($excerpt, 0, 400); 
    $excerpt = substr($excerpt, 0, strripos($excerpt, " ")); 
    $excerpt = trim(preg_replace('/\s+/', ' ', $excerpt)); 
    $excerpt = $excerpt.'... <a class="c-drkGold" href="'.get_permalink($post->ID).'">Read More</a>'; 
    return $excerpt; 
} 

然後要顯示它,使用如果立足崗位類型,並相應顯示/ else語句(本例中是從靜態的頭版) 。

<?php 
    if(get_post_type() == 'post') { 
     ?><p class="l-nmb"><?php 
     $content = get_the_content(); echo mb_strimwidth($content, 0, 400, '... <a href="' . get_permalink() . '" class="c-drkGold">Read more</a>'); ?> </p> 
    <?php } else { 
     ?><p class="l-nmb"><?php 
     $content = cpt_get_excerpt(); echo mb_strimwidth($content, 0, 400, '... <a href="' . get_permalink() . '" class="c-drkGold">Read more</a>'); ?> </p> 
    <?php } ?>