根据网站域名网址自动将外部链接转换为会员链接

Automatically convert external link based on website domain url to affiliate link

提问人:Huda 提问时间:11/11/2023 最后编辑:miken32Huda 更新时间:11/11/2023 访问量:52

问:

<?php

namespace ExternalImporter\application\libs\pextractor\parser\parsers;

use ExternalImporter\application\libs\pextractor\parser\AdvancedParser;
use ExternalImporter\application\libs\pextractor\parser\Product;

class ExampleAdvanced extends AdvancedParser
{
    public function getHttpOptions()
    {
        $user_agent = array('ia_archiver');

        return array('user-agent' => $user_agent[array_rand($user_agent)]);
    }

    public function parseLinks()
    {
        $path = array(
            ".//a[@class='product__title a']/@href",
        );

        return $this->xpathArray($path);
    }

    public function parseTitle()
    {
        return $this->xpathScalar(".//h1[@class='product__title']") . ' ' . $this->xpathScalar(".//h2[@class='product-details__description inherit-font-styles']");
    }

    public function parseDescription()
    {
        $d = $this->xpathScalar(".//div[@id='tab6']", true);
        return preg_replace('~<div class="product-number text-uppercase">.+?</div>~ims', '', $d);
    }

    public function afterParseFix(Product $product)
    {
        // Replace image URLs
        $product->image = str_replace(',w_520,h_520,', ',w_1800,h_1800,', $product->image);
        foreach ($product->images as $k => $img)
        {
            $product->images[$k] = str_replace(',w_520,h_520,', ',w_1800,h_1800,', $img);
        }

        // Import images to the WooCommerce product gallery
        $this->importImageToProductGallery($product->id, $product->image);
        foreach ($product->images as $img)
        {
            $this->importImageToProductGallery($product->id, $img);
        }

        // Update the product URL to the affiliate link only for example.com
        if (strpos($product->url, 'example.com') !== false) {
            $product->url = $this->generateTrackingLink($product->url);

            // Enqueue the JavaScript for affiliate link conversion
            add_action('wp_footer', function () use ($product) {
                $this->addAffiliateJavascript($product->url);
            });
        }

        return $product;
    }

    protected function importImageToProductGallery($productId, $imageUrl)
    {
        // Download the image to a temporary file (use wp_remote_get for WordPress)
        $response = wp_remote_get($imageUrl);
        $tempFilePath = wp_tempnam($imageUrl);
        if (is_wp_error($response) || !is_wp_error($tempFilePath)) {
            // Handle the error, log it, etc.
            return;
        }

        // Get the file name from the URL
        $filename = basename($imageUrl);

        // Prepare the image data for WooCommerce
        $imageData = [
            'name' => $filename,
            'post_title' => $filename,
            'post_content' => '',
            'post_status' => 'inherit',
        ];

        // Create an attachment from the temporary file and add it to the product gallery
        $attachmentId = wp_insert_attachment($imageData, $tempFilePath, $productId);
        if (!is_wp_error($attachmentId)) {
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attachmentData = wp_generate_attachment_metadata($attachmentId, $tempFilePath);
            wp_update_attachment_metadata($attachmentId, $attachmentData);

            // Add the image to the product gallery
            add_post_meta($productId, '_product_image_gallery', $attachmentId, false);
        }

        // Clean up the temporary file
        unlink($tempFilePath);

        // Add any additional processing or linking logic as needed
    }

    protected function addAffiliateJavascript($productUrl)
    {
        ?>
        <script>
            jQuery(document).ready(function($) {
                // Attach a click event to all <a> elements
                $("a").click(function() {
                    // Check if the link is from example.com
                    if ($(this).attr('href').indexOf('example.com') >= 0) {
                        // Check if the link already contains the affiliate parameters
                        if ($(this).attr('href').indexOf('id=a0s*vOA3SnI') < 0) {
                            // Update the link with the affiliate parameters
                            $(this).attr('href', function(_, currentHref) {
                                return currentHref +
                                    (currentHref.includes('?') ? '&' : '?') +
                                    'id=a0s*vOA3SnI&mid=50238&murl=' +
                                    encodeURIComponent(currentHref);
                            });
                        }
                    }
                    // Return true to follow the link
                    return true;
                });
            });
        </script>
        <?php
    }
}

解析数据后,我想在产品来自 example.com 或任何其他广告商时自动附加会员 URL。

我还在代码中添加了检查产品 URL 是否包含“example.com”的逻辑。如果是这样,它会生成一个跟踪链接,并将 JavaScript 排入队列以进行关联链接转换。

我不知道我在这里做错了什么,会员网址没有转换。我必须在开头附加代码,谁能帮我解决这个问题?

谢谢。

javascript php jquery wordpress woocommerce

评论

0赞 Vasim Shaikh 11/11/2023
我不清楚输出和链接是内容的一部分,那么您可以使用过滤器

答:

1赞 Hristijan Manasijev 11/11/2023 #1

我建议使用 DOMDocument() 类,而不是使用 Javascript 来动态操作链接。

以下是如何操作的分步指南:

  1. 在响应中显示/发送您的内容之前,请对其应用“过滤器”方法。它看起来像这样:
<?php
  $filteredContent = applyAffiliateLinks($htmlContent);
  return response($filteredContent);
?>
  1. 您的 applyAffiliateLinks(string $content);函数如下所示:
function applyAffiliateLinks(string $content){
   // We instantiate a DOMDocument object, which will 'hold' DOM document.
   $dom = new DOMDocument();

   // On this domains we will add affiliate params
   $whitelistDomains = [ 'example.com', 'hello.com' ];

   // We load the HTML content in our temporary DOM document.
   $dom->loadHTML($content);

   // We get all the A elements from the DOM document.
   $aElements = $dom->getElementsByTagName( 'a' );

   // We iterate all links, and try to find those that we want to transform/append affiliate params.
   foreach ($aElements as $aElement) {
        $host = parse_url($aElement->getAttribute('href'), PHP_URL_HOST);

        if ( in_array( $host, $whitelistHosts ) ){
            // We get the current **href** value, and append the affiliate param to it.
            $href = $aElement->getAttribute('href');
            $href .= '?affiliateId=12345'

            // we save the new 'href' attribute value.
            $aElement->setAttribute('href', $href);
        } 
    }

   return $dom->saveHTML();
}

瞧。现在,您的服务器将在将相应的链接发送到客户端之前对其进行修改。