douqian1975 2011-01-21 16:46
浏览 18
已采纳

抓取WordPress帖子的图像并显示它?

Is there a way to grab a post's first image and have it displayed as a thumbnail link to the post itself on the homepage? I can't seem to figure it out. Prefer not to use the featured image function. Is there a workaround? Any help would be much appreciated.


Would I be able to use the following code to acheive what I want? It doesn't seem like I can specify a post ID, but maybe i'm wrong?

http://www.wordimpressed.com/wordpress/get-the-first-image-from-a-post-and-display-it/

My main concern is grabbing a few posts and being able to display them on the frontpage/homepage. Is that possible?

  • 写回答

2条回答 默认 最新

  • dsf6778 2012-04-17 02:19
    关注

    You could do it through two ways:

    function post_photo_count_attachments( $post_id ) {
    
        $attachments = get_children(
            array( 'post_parent' => $post_id ) 
        );
    
        return( $attachments[0] );
    

    }

    Or by Query/XPath method:

    function post_photo_count_xpath( $post_id ) {
        global $wpdb;
    
        $post_id_safe = intval( $post_id );
    
        $html = $wpdb->get_row(
            "select * from {$wpdb->posts} where ID={$post_id_safe} limit 1"
        );
    
        $doc = new DOMDocument();
        @$doc->loadHTML( $html->post_content );
        $path = new DOMXpath( $doc );
        $images = $path->query( "//img" );
    
        return( $images->item(0)->getAttribute('src') );
    }
    

    print_r() these returns for more detailed information.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试