以下是一个示例代码:

function get_torrent_links() {

    $url = 'https://www.torrentmac.net/category/applications/';

    $response = wp_remote_request( $url, array(
        'timeout' => 10,
        'sslverify' => false,
    ) );

    if ( is_wp_error( $response ) ) {
        return;
    }

    $body = wp_remote_retrieve_body( $response );

    $doc = new DOMDocument();
    @$doc->loadHTML( $body );

    $links = array();

    $items = $doc->getElementsByTagName( 'article' );

    foreach ( $items as $item ) {

        $title = $item->getElementsByTagName( 'h2' )->item(0)->textContent;

        $link = $item->getElementsByTagName( 'a' )->item(0)->getAttribute( 'href' );

        $torrent_link = get_torrent_link( $link );

        $links[] = array(
            'title' => $title,
            'link' => $torrent_link,
        );

    }

    return $links;

}

function get_torrent_link( $url ) {

    $response = wp_remote_request( $url, array(
        'timeout' => 10,
        'sslverify' => false,
    ) );

    if ( is_wp_error( $response ) ) {
        return;
    }

    $body = wp_remote_retrieve_body( $response );

    $doc = new DOMDocument();
    @$doc->loadHTML( $body );

    $link = '';

    $items = $doc->getElementsByTagName( 'a' );

    foreach ( $items as $item ) {

        if ( strpos( $item->getAttribute( 'href' ), 'magnet:' ) !== false ) {
            $link = $item->getAttribute( 'href' );
            break;
        }

    }

    return $link;

}

function publish_torrent_articles() {

    $links = get_torrent_links();

    foreach ( $links as $link ) {

        $post = array(
            'post_title' => $link['title'],
            'post_content' => $link['link'],
            'post_status' => 'publish',
            'post_author' => 1,
            'post_type' => 'post',
            'comment_status' => 'closed',
            'ping_status' => 'closed',
        );

        $post_id = wp_insert_post( $post );

    }

}

add_action( 'wp_ajax_nopriv_publish_torrent_articles', 'publish_torrent_articles' );
add_action( 'wp_ajax_publish_torrent_articles', 'publish_torrent_articles' );

这段代码定义了一个名为 get_torrent_links 的函数,它会获取 https://www.torrentmac.net/category/applications/ 页面上的所有文章链接,并从每个链接中提取出文章标题和torrent链接。它还定义了一个名为 publish_torrent_articles 的函数,它会将获取到的文章标题和torrent链接发布到WordPress网站上。

为了确保安全,我们在 wp_remote_request 函数中设置了 sslverify 参数为 false,这样就可以忽略SSL证书的验证。这是一个不推荐的做法,但在某些情况下可能是必要的。

此外,我们还使用了WordPress的 wp_insert_post 函数来将文章发布到网站上。

最后,我们通过 add_action 函数将 publish_torrent_articles 函数添加到WordPress的AJAX钩子中,以便在前台页面上调用它。

利用WordPress的wp_remote_request 等函数 获取远程httpswwwtorrentmacnetcategoryapplications页面上的链接然后采集到文章标题内容和torrent链接处理请求错误如果成功调用函数发表WordPress文章。

原文地址: https://www.cveoy.top/t/topic/B1H 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录