wordpress 獲取文章內(nèi)所有圖片個數(shù)與圖片地址的相關(guān)文章以前小編有介紹過了,今天看到兩個優(yōu)化比較好的代碼我給各位整理一下吧。
WordPress獲取文章中的圖片個數(shù)
復(fù)制以下代碼到當(dāng)前使用主題的functions.php文件中,然后在文章列表主循環(huán)或文章頁中調(diào)用該函數(shù)即可。
注:xiu主題已有該功能。
WordPress獲取文章中的圖片個數(shù)函數(shù):
- /*
- * 獲取文章中的圖片個數(shù) (使用在文章列表主循環(huán)中、或文章頁中)
- */
- if( !function_exists('get_post_images_number') ){
- function get_post_images_number(){
- global $post;
- $content = $post->post_content;
- preg_match_all('/<img.*?(?: |//t|//r|//n)?src=[/'"]?(.+?)[/'"]?(?:(?: |//t|//r|//n)+.*?)?>/sim', $content, $result, PREG_PATTERN_ORDER);
- return count($result[1]); //Vevb.com
- }
- }
函數(shù)使用方法:
<?php echo get_post_images_number().'張圖片' ?>
wordpress 獲取文章內(nèi)所有圖片,將代碼插入functions.php:
- function hui_get_thumbnail( $single=true, $must=true ) {
- global $post;
- $html = '';
- if ( has_post_thumbnail() ) {
- $domsxe = simplexml_load_string(get_the_post_thumbnail());
- $src = $domsxe->attributes()->src;
- $src_array = wp_get_attachment_image_src(hui_get_attachment_id_from_src($src), 'thumbnail');
- $html = sprintf('<li><img src="%s" /></li>', $src_array[0]);
- } else {
- $content = $post->post_content;
- preg_match_all('/<img.*?(?: |//t|//r|//n)?src=[/'"]?(.+?)[/'"]?(?:(?: |//t|//r|//n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);
- $images = $strResult[1];
- $counter = count($strResult[1]);
- $i = 0;
- foreach($images as $src){
- $i++;
- $src2 = wp_get_attachment_image_src(hui_get_attachment_id_from_src($src), 'thumbnail');
- $src2 = $src2[0];
- if( !$src2 && true ){
- $src = $src;
- }else{
- $src = $src2;
- }
- $item = sprintf('<li><img src="%s" /></li>', $src);
- if( $single){
- return $item;
- break;
- }
- $html .= $item;
- if(
- ($counter >= 4 && $counter < 8 && $i >= 4) ||
- ($counter >= 8 && $i >= 8) ||
- ($counter > 0 && $counter < 4 && $i >= $counter)
- ){
- break;
- }
- }
- }
- return $html;
- }
- function hui_get_attachment_id_from_src ($link) {
- global $wpdb;
- $link = preg_replace('/-/d+x/d+(?=/.(jpg|jpeg|png|gif)$)/i', '', $link);
- return $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE guid='$link'");
- }
以上代碼規(guī)則可根據(jù)自己實(shí)際要求來修改,前端調(diào)用:
<?php echo hui_get_thumbnail(false,true);?>
新聞熱點(diǎn)
疑難解答
圖片精選