将当前用户的ID添加到帖子内容中PDF超链接的末尾

时间:2018-12-14 作者:Drastec Development

如何在超链接后添加额外参数以进行跟踪?

例如,假设我在帖子中插入了媒体-http://mysite/wp-content/uploads/2018/12/My_PDF_File.pdf. 如何创建一个函数来自动插入这样的用户idhttp://mysite/wp-content/uploads/2018/12/My_PDF_File.pdf?user=54

同一页上会有多个pdf链接,我对如何做到这一点有点不知所措。

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

我想出了一个解决方案user 查询参数和当前用户ID到PDF链接,例如:

http://mysite/wp-content/uploads/2018/12/My_PDF_File.pdf?user=54

此代码通过使用the_content 筛选,然后使用解析内容DOMDocument. 我使用DOMDocument 这段代码中的大部分都处理这些边缘情况。还请注意,如果用户未登录,我们将立即退出,因为在这种情况下没有什么可做的。

真正的肉和土豆快吃完了wpse_append_current_user_id_to_pdf_links() 从内容中提取链接,检查以确保它们是PDF,然后add_query_arg() 用于附加user 查询参数和值。

/**
 * Filters post content and appends user query argument and user ID value
 * to PDF links.
 * 
 * @param string $content post content 
 */
add_filter( \'the_content\', \'wpse_append_current_user_id_to_pdf_links\' );
function wpse_append_current_user_id_to_pdf_links( $content ) {
    // Bail if there is no content to work with.
    if ( ! $content ) {
        return $content;
    }

    // Get the current user.
    $current_user = wp_get_current_user();

    // Bail if there is nobody logged in.
    if ( ! $current_user->exists() ) {
        return $content;
    }

    // Create an instance of DOMDocument.
    $dom = new \\DOMDocument();

    // Supress errors due to malformed HTML.
    // See http://stackoverflow.com/a/17559716/3059883
    $libxml_previous_state = libxml_use_internal_errors( true );

    // Populate $dom with $content, making sure to handle UTF-8, otherwise
    // problems will occur with UTF-8 characters.
    // Also, make sure that the doctype and HTML tags are not added to our HTML fragment. http://stackoverflow.com/a/22490902/3059883
    $dom->loadHTML( mb_convert_encoding( $content, \'HTML-ENTITIES\', \'UTF-8\' ), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );

    // Restore previous state of libxml_use_internal_errors() now that we\'re done.
    libxml_use_internal_errors( $libxml_previous_state );

    // Create an instance of DOMXpath.
    $xpath = new \\DOMXpath( $dom );

    // Get all links.
    $links = $xpath->query( "//a" );

    // Process the links.
    foreach ( $links as $link ) {
        $link_href = $link->getAttribute( \'href\' );

        // Get the extension for this link.
        $extension = pathinfo( $link_href, PATHINFO_EXTENSION );

        // Only process PDF links.
        if ( \'pdf\' === strtolower( $extension ) ) {
            $link->setAttribute( \'href\', add_query_arg( \'user\', $current_user->ID, $link_href ) );
        }   
    }

    // Save and return updated HTML.
    $new_content = $dom->saveHTML();
    return $new_content;
}

相关推荐