Woocommerce web siteniz varsa ürünün açıklama kısmında benzer ürünleri göstermek için fonksiyon. Temanızın fonksiyon dosyasına ekleyerek kullanabilirsiniz.
Açıklamanın toplam karakter sayısını hesaplar ve 3 eşit parçaya bölerek 3 tane ürün gösterir. Eğer karakter sayısı 1000'den az ise 2 ürün gösterir.
Kodun çıktısı;
https://prnt.sc/xkEuYHTbezpQ
add_filter('the_content', 'urun_aciklamasi_icin_rastgele_benzer_urunler');
function urun_aciklamasi_icin_rastgele_benzer_urunler($content) {
// Sadece WooCommerce ürün sayfalarında çalışsın
if ( ! function_exists('is_product') || ! is_product() ) {
return $content;
}
global $post;
// Mevcut ürünün kategorilerini al (product_cat taksonomisi)
$terms = wp_get_post_terms( $post->ID, 'product_cat' );
if ( empty( $terms ) || is_wp_error( $terms ) ) {
return $content;
}
// Kategori dizisindeki "son" kategoriyi seçelim.
// (Varsayım: wp_get_post_terms dönen dizideki son eleman istenen kategoridir)
$last_term = end( $terms );
if ( ! $last_term ) {
return $content;
}
$category_slug = $last_term->slug;
// Sorgu ayarları: Sadece seçilen kategoriye ait ürünler, mevcut ürünü hariç tutarak 3 ürün çekelim.
$args = array(
'post_type' => 'product',
'posts_per_page' => 3,
'post__not_in' => array( $post->ID ),
'orderby' => 'rand', // Rastgele sıralama
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $category_slug,
),
),
);
$benzer_query = new WP_Query( $args );
if ( ! $benzer_query->have_posts() ) {
return $content;
}
// Sorgudan dönen ürünleri diziye aktaralım
$similar_products = array();
while ( $benzer_query->have_posts() ) {
$benzer_query->the_post();
// Ürünün öne çıkan görselini al (varsa)
$thumbnail_url = get_the_post_thumbnail_url( get_the_ID(), 'medium' );
$similar_products[] = array(
'title' => get_the_title(),
'permalink' => get_permalink(),
'image' => $thumbnail_url,
);
}
wp_reset_postdata();
// İçeriğin toplam karakter sayısını hesapla
$content_length = mb_strlen( strip_tags( $content ) );
// İçeriği 3 eşit parçaya bölelim
$part_length = intval( $content_length / 3 );
// İçeriği DOMDocument ile parse edip uygun noktalara ekleme yapalım.
libxml_use_internal_errors(true);
$doc = new DOMDocument();
// UTF-8 desteği için encoding etiketini ekleyelim
$doc->loadHTML('<?xml encoding="utf-8" ?>' . $content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($doc);
// İçeriği metin olarak alalım
$text_content = strip_tags( $doc->saveHTML() );
// İçeriği 3 parçaya bölecek pozisyonları bulalım
$split_positions = array();
$current_length = 0;
$parts = array();
// DOMDocument içindeki tüm metin düğümlerini bulalım
$text_nodes = $xpath->query('//text()');
foreach ( $text_nodes as $node ) {
$node_text = $node->nodeValue;
$node_length = mb_strlen( $node_text );
// Eğer mevcut uzunluk, parça uzunluğunu geçerse, bu noktayı bölme pozisyonu olarak işaretle
if ( $current_length + $node_length >= $part_length * ( count( $split_positions ) + 1 ) ) {
$split_positions[] = $node;
}
$current_length += $node_length;
}
// Eğer 3 parçaya bölünemediyse, içeriği olduğu gibi kabul et
if ( count( $split_positions ) < 2 ) {
return $content;
}
// Benzer ürünleri 3 parçaya ekleyelim
foreach ( $similar_products as $index => $product_data ) {
if ( ! isset( $split_positions[ $index ] ) ) {
continue;
}
$split_node = $split_positions[ $index ];
// Ürünü gösterecek kapsayıcı div oluşturuyoruz
$wrapper = $doc->createElement('div');
$wrapper->setAttribute('class', 'benzer-urun');
$wrapper->setAttribute('style', 'display: flex; align-items: center; gap: 10px; margin-top: 15px; border: 1px solid #ddd; padding: 10px; border-radius: 5px;');
// Ürün görseli (varsa)
if ( ! empty( $product_data['image'] ) ) {
$img = $doc->createElement('img');
$img->setAttribute('src', esc_url( $product_data['image'] ));
$img->setAttribute('alt', htmlspecialchars( $product_data['title'] ));
$img->setAttribute('style', 'width: 80px; height: auto; border-radius: 5px;');
$wrapper->appendChild( $img );
}
// Ürün başlığını link olarak ekleyelim
$link = $doc->createElement('a', htmlspecialchars( $product_data['title'] ));
$link->setAttribute('href', esc_url( $product_data['permalink'] ));
$link->setAttribute('style', 'text-decoration: none; font-weight: bold; color: #333;');
$wrapper->appendChild( $link );
// Bölme noktasından sonra ekleyelim
$parent = $split_node->parentNode;
if ( $split_node->nextSibling ) {
$parent->insertBefore( $wrapper, $split_node->nextSibling );
} else {
$parent->appendChild( $wrapper );
}
// Düzeni korumak için bir <br> etiketi ekleyelim
$br = $doc->createElement('br');
if ( $wrapper->nextSibling ) {
$parent->insertBefore( $br, $wrapper->nextSibling );
} else {
$parent->appendChild( $br );
}
}
$new_content = $doc->saveHTML();
// XML encoding etiketini temizleyelim
$new_content = preg_replace('/^<\?xml.*?\?>/', '', $new_content);
libxml_clear_errors();
return $new_content;
}