使用DOM和XPath通过URL以编程方式设置缩略图-添加ELSEIF的位置

时间:2015-04-03 作者:Robert Ritz

EDIT3:我得到了一些外部帮助,并完全改变了我的代码,现在使用xpath来选择div,而不是使用html源代码中的第n个img。我很高兴地说,这是工作!现在我的问题是添加一个ELSEIF来评估不同的类别,而不仅仅是一个类别。我似乎被这种逻辑束缚住了。我曾尝试在“if(in\\u array(\'mongong.GoGo.mn\',$cat\\u name))”循环中添加ELSEIF,但这只会引发意外的ELSEIF错误。我又迷路了。。。代码如下:

add_action(\'publish_post\', \'custom_auto_featured_image_publish_post\',10,2);
function custom_auto_featured_image_publish_post($post_id, $post) {
    // get category of post ID
    $cat_detail=get_the_category($post_id);
    $cat_name = array();
    foreach($cat_detail as $cd){
        $cat_name[] = $cd->cat_name;
    }

    // get all image tags
    //if ( get_post_meta($post_id, \'_apt_skip_post_thumb\', true) ) {
        if ( in_array( \'Mongolia.GoGo.mn\', $cat_name ) ) {
            // get custom post field
            $custom_fields = get_post_custom($post_id);
            $htmlURL = $custom_fields[\'original_guid\'][0];
            // try to load the webpage
            $dom = new domDocument;

            @$dom->loadHTML(file_get_contents($htmlURL));



            $finder = new DomXPath($dom);
            $classname="newscover";
            $content = $finder->query("//*[contains(concat(\' \', normalize-space(@class), \' \'), \' $classname \')]");
            $imageURL = \'\';
            if($content->length){
                if($content->item(0)->childNodes->length > 1){
                    $imageURL = $content->item(0)->childNodes->item(1)->getAttribute(\'src\');
                }
            }else{
                $content = $dom->getElementById(\'ncbubuhome\');

                @$dom->loadHTML($content->nodeValue);

                $images = $dom->getElementsByTagName(\'img\');

                foreach ($content->childNodes as $node) {
                    if($node->nodeName != \'#text\'){
                        foreach ($node->childNodes as $childNode) {
                            if($childNode->nodeName == \'img\'){
                                $imageURL = $childNode->getAttribute(\'src\');
                                break;
                            }
                        }
                    }
                }

            }

            if($imageURL != \'\'){
                $imageURL = str_replace(\' \', \'%20\', $imageURL);

                // download image from url
                $tmp = download_url($imageURL);

                $ext = pathinfo(basename($imageURL), PATHINFO_EXTENSION);
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $name = strtotime("now") . \'_feature_image.\' . $ext;
                $type = finfo_file($finfo, $tmp);
                $file = array(
                    \'name\' => $name,
                    \'size\' => filesize($tmp),
                    \'type\' => $type,
                    \'tmp_name\' => $tmp,
                    \'error\' => UPLOAD_ERR_OK
                );

                $overrides = array(
                    \'test_form\' => false,
                    \'test_size\' => true,
                    \'test_upload\' => true, 
                );

                // upload image to server
                $file_uploaded = wp_handle_sideload( $file, $overrides );

                // $filename should be the path to a file in the upload directory.
                $filename = $file_uploaded[\'file\'];
                $filetype = $file_uploaded[\'type\'];

                // Prepare an array of post data for the attachment.
                $attachment = array(
                    \'guid\'           => $file_uploaded[\'url\'], 
                    \'post_mime_type\' => $filetype,
                    \'post_title\'     => preg_replace( \'/\\.[^.]+$/\', \'\', basename( $filename ) ),
                    \'post_content\'   => \'\',
                    \'post_status\'    => \'inherit\'
                );

                // Insert the attachment.
                $attach_id = wp_insert_attachment( $attachment, $filename );

                // Generate the metadata for the attachment, and update the database record.
                $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
                wp_update_attachment_metadata( $attach_id, $attach_data );
                // set the featured image
                update_post_meta($post_id, \'_thumbnail_id\', $attach_id);
            }
        }

    //}
}
原文:我试图通过函数以编程方式设置特色缩略图。php。这是我写了一半的代码(其余的代码来自另一篇StackExchange帖子,非常有用。似乎没有任何语法错误(我已经打开了调试),但当使用正确的类别创建新帖子时,什么都没有发生。我对PHP非常陌生,所以我认为这是我的代码的一个问题,但我不确定具体在哪里。

(这个逻辑已经过时了。现在我使用xpath来选择我想要的类)我通过DOM在自定义字段中加载URL的HTML,然后提取IMG标记。之后,If-ElseIf查看类别并根据类别抓取第n幅图像,并将其附加为帖子缩略图。我觉得逻辑是对的,但我可能遗漏了什么。

//以前过时的代码段

EDIT2:我还在研究这个。我已经从Wordpress论坛获得了一些帮助来更改我的代码,但这个功能似乎仍然不起作用。这里的逻辑似乎很简单,但不起作用。我就是不明白。。。这是我当前的代码。

//以前过时的代码段2

1 个回复
最合适的回答,由SO网友:Robert Ritz 整理而成

好的,我知道了!以下是我使用的代码:

add_action(\'publish_post\', \'custom_auto_featured_image_publish_post\',10,2);
function custom_auto_featured_image_publish_post($post_id, $post) {
    // get category of post ID
    $cat_detail=get_the_category($post_id);
    $cat_name = array();
    foreach($cat_detail as $cd){
        $cat_name[] = $cd->cat_name;
    }

    $custom_fields = get_post_custom($post_id);

    if(isset($custom_fields[\'original_guid\']) && !empty($custom_fields[\'original_guid\'])){
        $htmlURL = $custom_fields[\'original_guid\'][0];
        // try to load the webpage
        $dom = new domDocument;
        $imageURL = \'\';

        @$dom->loadHTML(file_get_contents($htmlURL));

        if ( in_array( \'Mongolia.GoGo.mn\', $cat_name ) ) {

            $finder = new DomXPath($dom);
            $classname="newscover";
            $content = $finder->query("//*[contains(concat(\' \', normalize-space(@class), \' \'), \' $classname \')]");

            if($content->length){
                if($content->item(0)->childNodes->length > 1){
                    $imageURL = $content->item(0)->childNodes->item(1)->getAttribute(\'src\');
                }
            }else{
                $content = $dom->getElementById(\'ncbubuhome\');

                if($content->childNodes->length){
                    foreach ($content->childNodes as $node) {
                        if($node->nodeName != \'#text\'){
                            foreach ($node->childNodes as $childNode) {
                                if($childNode->nodeName == \'img\'){
                                    $imageURL = $childNode->getAttribute(\'src\');
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }elseif ( in_array( \'InfoMongolia\', $cat_name ) ) {

            $finder = new DomXPath($dom);
            $classname="full_text";
            $content = $finder->query("//*[contains(concat(\' \', normalize-space(@class), \' \'), \' $classname \')]");

            if($content->length){
                if($content->item(0)->childNodes->length){
                    foreach ($content->item(0)->childNodes as $node) {
                        if($node->nodeName == \'img\'){
                            $imageURL = $node->getAttribute(\'src\');
                            break;
                        }
                    }
                }
            }
            if($imageURL != \'\'){
            if (filter_var($imageURL, FILTER_VALIDATE_URL) === false) {
                $domain = \'http://www.infomongolia.com/\';
                $imageURL = str_replace(\'../\', \'\', $imageURL);
                $imageURL = $domain . $imageURL;
            }
            }
        } elseif ( in_array( \'UBPost\', $cat_name ) ) {

            $finder = new DomXPath($dom);
            $classname="full_text";
            $content = $finder->query("//*[contains(concat(\' \', normalize-space(@class), \' \'), \' $classname \')]");

            if($content->length){
                if($content->item(0)->childNodes->length){
                    foreach ($content->item(0)->childNodes as $node) {
                        if($node->nodeName == \'img\'){
                            $imageURL = $node->getAttribute(\'src\');
                            break;
                        }
                    }
                }
            }
            if($imageURL != \'\'){
            if (filter_var($imageURL, FILTER_VALIDATE_URL) === false) {
                $domain = \'http://www.infomongolia.com/\';
                $imageURL = str_replace(\'../\', \'\', $imageURL);
                $imageURL = $domain . $imageURL;
            }
            }
        }
        if($imageURL != \'\'){
            $imageURL = str_replace(\' \', \'%20\', $imageURL);

            // download image from url
            $tmp = download_url($imageURL);

            $ext = pathinfo(basename($imageURL), PATHINFO_EXTENSION);
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $name = strtotime("now") . \'_feature_image.\' . $ext;
            $type = finfo_file($finfo, $tmp);
            $file = array(
                \'name\' => $name,
                \'size\' => filesize($tmp),
                \'type\' => $type,
                \'tmp_name\' => $tmp,
                \'error\' => UPLOAD_ERR_OK
            );

            $overrides = array(
                \'test_form\' => false,
                \'test_size\' => true,
                \'test_upload\' => true, 
            );

            // upload image to server
            $file_uploaded = wp_handle_sideload( $file, $overrides );

            // $filename should be the path to a file in the upload directory.
            $filename = $file_uploaded[\'file\'];
            $filetype = $file_uploaded[\'type\'];

            // Prepare an array of post data for the attachment.
            $attachment = array(
                \'guid\'           => $file_uploaded[\'url\'], 
                \'post_mime_type\' => $filetype,
                \'post_title\'     => preg_replace( \'/\\.[^.]+$/\', \'\', basename( $filename ) ),
                \'post_content\'   => \'\',
                \'post_status\'    => \'inherit\'
            );

            // Insert the attachment.
            $attach_id = wp_insert_attachment( $attachment, $filename );

            // Generate the metadata for the attachment, and update the database record.
            $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
            wp_update_attachment_metadata( $attach_id, $attach_data );
            // set the featured image
            update_post_meta($post_id, \'_thumbnail_id\', $attach_id);
        }
    }
}

结束

相关推荐

列出分类法:如果分类法没有POST,就不要列出分类法--取决于定制的POST-META?

这可能很难解释,我不知道是否有解决办法!?我有一个名为“wr\\u event”的自定义帖子类型和一个名为“event\\u type”的分层自定义分类法。自定义帖子类型有一个元框,用于event_date 并且与此帖子类型关联的所有帖子都按以下方式排序event_date. 我在循环中有一个特殊的条件来查询event_date 已经发生了-在这种情况下,它没有显示,但只列在我的档案中。就像你可以使用wp_list_categories() 我编写了一个自定义函数,它以完全相同的方式列出所有分类术语。现在