genel rss ekleme uygulaması wordpress

Genel Forum
muratca61
Site Admin
Mesajlar: 35964
Kayıt: Cmt Ara 21, 2024 7:56 am

genel rss ekleme uygulaması wordpress

Mesaj gönderen muratca61 »

Kod:Tümünü seç

selam bu aşağıdakini genel bir eklentiye çevireceğiz. şöyle olacak admin panelinden ekle kaldır seçeneği ile satırlar ekleyeceğiz. her satırda rss adresi ve yazının rss içeriğinde hangi kod aralığında olduğu (<item> <entry> bilgileri bu satırlarda kullanıcı admin panelinde girecek mesela <item>
<title>Araklı'da Demirbağ Başkan Yardımcılığına Getirildi</title>
<category>SPOR</category>
<link>https://www.arihaber.net/haber/araklida-demirbag-baskan-yardimciligina-getirildi-11855</link>
<guid>https://www.arihaber.net/haber/araklida-demirbag-baskan-yardimciligina-getirildi-11855</guid>
<description>
<![CDATA[ ]]>
</description>
<content:encoded>
<![CDATA[ <p>Araklı İdman Yurdu'nda Sercan Demirbağ, Başkan Yardimcilığina getirildi</p> <p>Arakli'nin Sevilen İsimlerinden Futbol Menajerligi yapan Sercan Demirbağ, bu görevinde Sportif Anlamda direk yetkili olmustur.</p> <p>Sercan demirbağ yaptığı açıklamada</p> <p>"Başkan yardimciligi görevine beni layik gören sn.Kadir Çebi ve Yönetim kuruluna tesekkur ederim. Arakli icin her zaman her platformda var oldum olmayada devam edecegim Arakli gencleri icin onlarin gelisimi icin var gücümuzle yanlarinda olacagim. Arakli daki tüm kulupler bizim tum genclerin spor dallarinda basarili olmalari icin elimden geleni yapacagim, hersey Arakli " Dedi</p> ]]>
</content:encoded>
<pubDate>Mon, 10 Feb 2025 23:26:00 +0300</pubDate>
<enclosure type="image/jpeg" url="https://www.arihaber.net/images/haberler/2025/02/araklida-demirbag-baskan-yardimciligina-getirildi-1739219399.webp"/>
</item> bu item
bu entry olarak girilmiş
<entry>
<id>https://www.ntv.com.tr/turkiye/son-dakika-muglada-deprem-mi-oldu-az-once-deprem-muglada-nerede-oldu-mugla-deprem-kandilli-ve-afad-son-depremler-listesi-16-subat-2025,2jggwasz_kmM3HpUjBsJSA</id>
<title type="html">Son dakika Muğla'da deprem mi oldu? Az önce deprem Muğla'da nerede oldu? Muğla deprem Kandilli ve AFAD son depremler listesi 16 Şubat 2025</title>
<published>2025-02-16T11:45:12+03:00</published>
<updated>2025-02-16T11:45:12+03:00</updated>
<author>
<name>NTV</name>
</author>
<link rel="alternate" href="https://www.ntv.com.tr/turkiye/son-dakika-muglada-deprem-mi-oldu-az-once-deprem-muglada-nerede-oldu-mugla-deprem-kandilli-ve-afad-son-depremler-listesi-16-subat-2025,2jggwasz_kmM3HpUjBsJSA"/>
<content type="html">
<![CDATA[ <img src="https://cdn1.ntv.com.tr/gorsel/gk16R0Kdo0SBNfKp7AF_ig.jpg?width=1200&ampmode=crop&ampscale=both&ampv=20240801181943065" class="type:primaryImage" alt="Son dakika Muğla'da deprem mi oldu? Az önce deprem Muğla'da nerede oldu? Muğla deprem Kandilli ve AFAD son depremler listesi 16 Şubat 2025" /><p>Son dakika Muğla deprem haberleri..Muğla'da deprem mi oldu? Az önce deprem Muğla'da nerede oldu? Muğla Kandilli ve AFAD son depremler.. 16 Şubat 2025 Muğla deprem son dakika haberleri haberin detayında...Artçı deprem mi oldu Muğla'da? Muğla son deprem büyüklüğü ne kadar? Muğla'da ve Muğla yakınındaki depremler nelerdir? Muğla'da anlık deprem mi oldu? Son dakika Muğla canlı deprem haritası..Kandilli rasathanesi ve deprem araştırma enstitüsü ve AFAD Muğla deprem haberleri.. Muğla'da hangi ilçelerde deprem oldu ve hangi ilçelerde en çok hissedildi? Bugün Muğla'da deprem mi oldu? Deprem Muğla'da ne zaman ve kaç şiddetinde oldu? En son Muğla'da nerede deprem oldu? Muğla deprem haberleriyle ilgili en çok merak edilenlerin cevabı haberde..</p>Tarih-saat 16 Şubat 2025 11:23:06 itibariyle Ege Denizi, Yamurgi Adası (Amorgos) - [127.08 km] Bodrum (Muğla) 3,8 şiddetinde bir deprem olmuştur.Son dakika Muğla deprem haberleri 16 Şubat 2025..Muğla AFAD son depremler ve Muğla Kandilli son dakika deprem listesi.. ]]>
</content>
</entry>
içerik çekme kodumuzda bu
<?php
/*
Plugin Name: RSS Haber Scraper - 61Saat Trabzon & Trabzonspor
Description: 61Saat Trabzon ve Trabzonspor haberlerini RSS ile çeker ve WordPress’e ekler.
Version: 1.5
Author: Örnek Geliştirici
License: GPL2
*/

if (!defined('ABSPATH')) {
    exit;
}

class RSS_Haber_Scraper {
    private $rss_sources = [
        'https://www.61saat.com/rss/trabzon' => 'Trabzon',
        'https://www.61saat.com/rss/trabzonspor' => 'Trabzonspor'
    ];

    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_page'));
        add_action('wp_ajax_rss_scrape', array($this, 'handle_scrape_request'));
        add_action('init', array($this, 'fetch_single_news_on_page_load'));
    }

    // Admin panelinde haber çekme sayfası
    public function add_admin_page() {
        add_menu_page(
            'RSS Haber Scraper',
            'RSS Haber Scraper',
            'manage_options',
            'rss-haber-scraper',
            array($this, 'admin_page_content'),
            'dashicons-rss',
            20
        );
    }

    public function admin_page_content() {
        ?>
        <div class="wrap">
            <h1>RSS Haber Scraper</h1>
            <p>Manuel olarak haber çekmek için aşağıdaki butona tıklayın.</p>
            <button id="fetch-rss-news" class="button button-primary">Haberleri Çek</button>
            <div id="rss-news-log" style="margin-top: 20px; padding: 10px; background: #f9f9f9; border: 1px solid #ddd; max-height: 300px; overflow-y: auto;"></div>
        </div>
        <script>
        document.getElementById("fetch-rss-news").addEventListener("click", function() {
            let log = document.getElementById("rss-news-log");
            log.innerHTML += "<p>Haberler çekiliyor...</p>";

            fetch(ajaxurl, {
                method: "POST",
                headers: { "Content-Type": "application/x-www-form-urlencoded" },
                body: "action=rss_scrape"
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    log.innerHTML += "<p style='color: green;'>" + data.message + "</p>";
                } else {
                    log.innerHTML += "<p style='color: red;'>" + data.message + "</p>";
                }
            })
            .catch(error => {
                log.innerHTML += "<p style='color: red;'>Bağlantı hatası!</p>";
            });
        });
        </script>
        <?php
    }

    public function fetch_single_news_on_page_load() {
        if (!is_admin() && !is_feed()) { 
            $this->fetch_one_rss_news();
        }
    }

    public function handle_scrape_request() {
        $this->fetch_one_rss_news();
        wp_send_json_success(array('message' => 'Bir haber çekildi.'));
    }

    private function fetch_one_rss_news() {
        require_once(ABSPATH . 'wp-admin/includes/post.php'); // 🛠️ post_exists() için gerekli!

        static $last_rss_index = 0;

        $rss_keys = array_keys($this->rss_sources);
        $rss_url = $rss_keys[$last_rss_index];
        $category_name = $this->rss_sources[$rss_url];

        $last_rss_index = ($last_rss_index + 1) % count($rss_keys);

        // RSS verisini kontrol et
        $rss_feed = @simplexml_load_file($rss_url);
        if (!$rss_feed) {
            error_log('RSS yüklenemedi: ' . $rss_url);
            return;
        }

        $category_id = get_cat_ID($category_name);
        if ($category_id == 0) {
            $category_id = wp_create_category($category_name);
        }

        foreach ($rss_feed->channel->item as $item) {
            $title = (string) $item->title;
            $link = (string) $item->link;
            $description = (string) strip_tags($item->description);
            $content = (string) strip_tags($item->children('content', true)->encoded);
            $image_url = isset($item->enclosure['url']) ? (string) $item->enclosure['url'] : '';

            if (post_exists($title)) { // 🔄 Önceden eklenen haberleri atla!
                continue;
            }

            $tags = $this->extract_tags_from_content($description . ' ' . $content);

            if (empty($title) || empty($content)) {
                continue;
            }

            $post_content = '<p>' . esc_html($description) . '</p><p>' . esc_html($content) . '</p>';
            $post_id = wp_insert_post(array(
                'post_title'   => wp_strip_all_tags($title),
                'post_content' => $post_content,
                'post_status'  => 'publish',
                'post_author'  => get_current_user_id(),
                'post_type'    => 'post',
                'post_category' => array($category_id)
            ));

            if (!is_wp_error($post_id)) {
                if (!empty($tags)) wp_set_post_tags($post_id, $tags);

                if (!empty($image_url)) {
                    require_once(ABSPATH . 'wp-admin/includes/media.php');
                    require_once(ABSPATH . 'wp-admin/includes/file.php');
                    require_once(ABSPATH . 'wp-admin/includes/image.php');
                    $attachment_id = media_sideload_image($image_url, $post_id, $title, 'id');
                    if (!is_wp_error($attachment_id)) set_post_thumbnail($post_id, $attachment_id);
                }

                return;
            }
        }
    }

    private function extract_tags_from_content($content) {
        $words = explode(' ', $content);
        $tags = [];

        foreach ($words as $word) {
            $word = trim($word, ".,!?()[]{}\"'");

            if (preg_match('/^[A-ZĞÜŞİÖÇ]+$/u', $word) && strlen($word) > 2) {
                $tags[] = strtolower($word);
            } elseif (preg_match('/^[A-ZĞÜŞİÖÇ][a-zğüşıöç]+$/u', $word)) {
                $tags[] = strtolower($word);
            }
        }

        return array_slice(array_unique($tags), 0, 5);
    }
}

new RSS_Haber_Scraper();
 ayrıca .js dosyamız sayfa her yenilendiğinde bir tane haber çekiyor
jQuery(document).ready(function($) {
    function fetchRssNews() {
        $.ajax({
            url: rssScraperAjax.ajax_url,
            type: 'POST',
            data: { action: 'rss_scrape' },
            success: function(response) {
                if (response.success) {
                    console.log("RSS Haber Eklendi:", response.message);
                } else {
                    console.log("RSS Haber Bulunamadı:", response.message);
                }
            },
            error: function() {
                console.log("RSS Bağlantı Hatası");
            }
        });
    }

    // Sayfa her yüklendiğinde RSS haberleri kontrol et
    fetchRssNews();

    // Kullanıcı sayfada gezindikçe kontrol et (Örneğin: 60 saniyede bir)
    setInterval(fetchRssNews, 60000);
});
muratca61
Site Admin
Mesajlar: 35964
Kayıt: Cmt Ara 21, 2024 7:56 am

Re: genel rss ekleme uygulaması wordpress

Mesaj gönderen muratca61 »

dosya yapısı

Kod:Tümünü seç

genel-rss-haber-scraper/
├── genel-rss-haber-scraper.php    // Eklentinin ana dosyası (PHP kodları burada)
├── js/
│   ├── genel-rss-admin.js         // Admin panelindeki dinamik satır ekleme/silme işlemleri
│   └── genel-rss-frontend.js      // Ön yüzde otomatik haber çekme işlemleri
└── readme.txt                     // Eklenti hakkında bilgi ve kullanım talimatları (isteğe bağlı)

Kod:Tümünü seç

genel-rss-haber-scraper.php

Kod:Tümünü seç

<?php
/*
Plugin Name: Genel RSS Haber Scraper
Description: Admin panelinden RSS kaynaklarını ekleyip kaldırarak, RSS/Atom haberlerini çeker. Her satırda RSS URL ve haberin içeriğinin hangi tag içerisinde (<item> veya <entry>) bulunduğu ayarlanabilir.
Version: 1.0
Author: Örnek Geliştirici
License: GPL2
*/

if (!defined('ABSPATH')) {
    exit;
}

class Genel_RSS_Haber_Scraper {
    private $option_name = 'genel_rss_haber_scraper_sources';

    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));
        add_action('wp_ajax_genel_rss_scrape', array($this, 'handle_scrape_request'));
        add_action('init', array($this, 'fetch_news_on_page_load'));

        // Admin panelinde dinamik satır eklemek için script
        add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'));
        // Ön yüzde otomatik haber çekimi için script
        add_action('wp_enqueue_scripts', array($this, 'frontend_enqueue_scripts'));
    }

    public function add_admin_menu() {
        add_menu_page(
            'Genel RSS Haber Scraper',
            'RSS Haber Scraper',
            'manage_options',
            'genel-rss-haber-scraper',
            array($this, 'admin_page'),
            'dashicons-rss',
            20
        );
    }

    public function register_settings() {
        register_setting('genel_rss_haber_scraper_options', $this->option_name);
    }

    public function admin_enqueue_scripts($hook) {
        if ($hook == 'toplevel_page_genel-rss-haber-scraper') {
            wp_enqueue_script(
                'genel-rss-admin',
                plugin_dir_url(__FILE__) . 'genel-rss-admin.js',
                array('jquery'),
                '1.0',
                true
            );
        }
    }

    public function frontend_enqueue_scripts() {
        wp_enqueue_script(
            'genel-rss-frontend',
            plugin_dir_url(__FILE__) . 'genel-rss-frontend.js',
            array('jquery'),
            '1.0',
            true
        );
        wp_localize_script('genel-rss-frontend', 'genelRssAjax', array(
            'ajax_url' => admin_url('admin-ajax.php')
        ));
    }

    public function admin_page() {
        // Kayıtlı RSS kaynaklarını alıyoruz
        $sources = get_option($this->option_name, array());
        ?>
        <div class="wrap">
            <h1>Genel RSS Haber Scraper</h1>
            <form method="post" action="options.php">
                <?php settings_fields('genel_rss_haber_scraper_options'); ?>
                <table class="form-table" id="rss-sources-table">
                    <thead>
                        <tr>
                            <th>RSS URL</th>
                            <th>Tag (<code>item</code> veya <code>entry</code>)</th>
                            <th>İşlem</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        if (!empty($sources)) {
                            foreach ($sources as $index => $source) {
                                ?>
                                <tr>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][url]" value="<?php echo esc_attr($source['url']); ?>" size="50" />
                                    </td>
                                    <td>
                                        <select name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][tag]">
                                            <option value="item" <?php selected($source['tag'], 'item'); ?>>item</option>
                                            <option value="entry" <?php selected($source['tag'], 'entry'); ?>>entry</option>
                                        </select>
                                    </td>
                                    <td>
                                        <button class="button remove-row">Kaldır</button>
                                    </td>
                                </tr>
                                <?php
                            }
                        }
                        ?>
                    </tbody>
                </table>
                <p>
                    <button type="button" class="button" id="add-row">Yeni Kaynak Ekle</button>
                </p>
                <?php submit_button(); ?>
            </form>
            <hr>
            <h2>Manuel Haber Çekme</h2>
            <p>RSS haberlerini çekmek için aşağıdaki butona tıklayın.</p>
            <button id="fetch-rss-news" class="button button-primary">Haberleri Çek</button>
            <div id="rss-news-log" style="margin-top: 20px; padding: 10px; background: #f9f9f9; border: 1px solid #ddd; max-height: 300px; overflow-y: auto;"></div>
            <script>
            jQuery(document).ready(function($) {
                $('#fetch-rss-news').on('click', function() {
                    let log = $('#rss-news-log');
                    log.append('<p>Haberler çekiliyor...</p>');
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: { action: 'genel_rss_scrape' },
                        success: function(response) {
                            if(response.success) {
                                log.append('<p style="color: green;">' + response.data.message + '</p>');
                            } else {
                                log.append('<p style="color: red;">' + response.data.message + '</p>');
                            }
                        },
                        error: function() {
                            log.append('<p style="color: red;">Bağlantı hatası!</p>');
                        }
                    });
                });
            });
            </script>
        </div>
        <?php
    }

    public function handle_scrape_request() {
        $result = $this->fetch_one_news();
        if ($result) {
            wp_send_json_success(array('message' => 'Bir haber çekildi.'));
        } else {
            wp_send_json_error(array('message' => 'Yeni haber bulunamadı veya RSS yüklenemedi.'));
        }
    }

    public function fetch_news_on_page_load() {
        // Yalnızca admin ve feed sayfalarında değilse (front-end) arka planda haber çek
        if (!is_admin() && !is_feed()){
            $this->fetch_one_news();
        }
    }

    private function fetch_one_news() {
        require_once(ABSPATH . 'wp-admin/includes/post.php'); // post_exists() için

        $sources = get_option($this->option_name, array());
        if (empty($sources)) {
            return false;
        }

        // Kayıtlı RSS kaynakları arasında dönüyoruz
        foreach ($sources as $source) {
            $rss_url = trim($source['url']);
            $tag = trim($source['tag']);
            if (empty($rss_url) || empty($tag)) {
                continue;
            }

            $rss_feed = @simplexml_load_file($rss_url);
            if (!$rss_feed) {
                error_log('RSS yüklenemedi: ' . $rss_url);
                continue;
            }

            // Ayarlanan tag'e göre haber öğelerini alıyoruz
            if ($tag === 'item' && isset($rss_feed->channel->item)) {
                $items = $rss_feed->channel->item;
                foreach ($items as $item) {
                    $title = (string)$item->title;
                    $link = (string)$item->link;
                    $description = (string)strip_tags($item->description);
                    $content = '';
                    if (isset($item->children('content', true)->encoded)) {
                        $content = (string)strip_tags($item->children('content', true)->encoded);
                    }
                    $image_url = isset($item->enclosure['url']) ? (string)$item->enclosure['url'] : '';

                    if (post_exists($title)) {
                        continue;
                    }

                    if (empty($title) || (empty($content) && empty($description))) {
                        continue;
                    }

                    $post_content = '<p>' . esc_html($description) . '</p><p>' . esc_html($content) . '</p>';
                    $post_id = wp_insert_post(array(
                        'post_title'   => wp_strip_all_tags($title),
                        'post_content' => $post_content,
                        'post_status'  => 'publish',
                        'post_author'  => 1, // Gerekirse uygun yazar ID'sini ayarlayın
                        'post_type'    => 'post'
                    ));

                    if (!is_wp_error($post_id)) {
                        // Görsel ekleme (varsa)
                        if (!empty($image_url)) {
                            require_once(ABSPATH . 'wp-admin/includes/media.php');
                            require_once(ABSPATH . 'wp-admin/includes/file.php');
                            require_once(ABSPATH . 'wp-admin/includes/image.php');
                            $attachment_id = media_sideload_image($image_url, $post_id, $title, 'id');
                            if (!is_wp_error($attachment_id)) {
                                set_post_thumbnail($post_id, $attachment_id);
                            }
                        }
                        return true;
                    }
                }
            } elseif ($tag === 'entry' && isset($rss_feed->entry)) {
                $entries = $rss_feed->entry;
                foreach ($entries as $entry) {
                    $title = (string)$entry->title;
                    // Atom feed'de link elemanı birden çok olabilir; rel="alternate" olanı alıyoruz
                    $link = '';
                    if (isset($entry->link)) {
                        foreach ($entry->link as $l) {
                            $attributes = $l->attributes();
                            if (isset($attributes['rel']) && (string)$attributes['rel'] === 'alternate') {
                                $link = (string)$attributes['href'];
                                break;
                            }
                        }
                        if (empty($link)) {
                            $link = (string)$entry->link;
                        }
                    }
                    $description = '';
                    if (isset($entry->summary)) {
                        $description = (string)strip_tags($entry->summary);
                    }
                    $content = '';
                    if (isset($entry->content)) {
                        $content = (string)strip_tags($entry->content);
                    }
                    $image_url = ''; // Atom feed'lerde varsayılan olarak görsel yok

                    if (post_exists($title)) {
                        continue;
                    }

                    if (empty($title) || (empty($content) && empty($description))) {
                        continue;
                    }

                    $post_content = '<p>' . esc_html($description) . '</p><p>' . esc_html($content) . '</p>';
                    $post_id = wp_insert_post(array(
                        'post_title'   => wp_strip_all_tags($title),
                        'post_content' => $post_content,
                        'post_status'  => 'publish',
                        'post_author'  => 1,
                        'post_type'    => 'post'
                    ));

                    if (!is_wp_error($post_id)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

new Genel_RSS_Haber_Scraper();

Kod:Tümünü seç

genel-rss-admin.js

Kod:Tümünü seç

jQuery(document).ready(function($) {
    $('#add-row').on('click', function(e) {
        e.preventDefault();
        var index = $('#rss-sources-table tbody tr').length;
        var row = '<tr>' +
            '<td><input type="text" name="genel_rss_haber_scraper_sources['+index+'][url]" value="" size="50" /></td>' +
            '<td><select name="genel_rss_haber_scraper_sources['+index+'][tag]">' +
            '<option value="item">item</option>' +
            '<option value="entry">entry</option>' +
            '</select></td>' +
            '<td><button class="button remove-row">Kaldır</button></td>' +
            '</tr>';
        $('#rss-sources-table tbody').append(row);
    });

    $('#rss-sources-table').on('click', '.remove-row', function(e) {
        e.preventDefault();
        $(this).closest('tr').remove();
    });
});

Kod:Tümünü seç

genel-rss-frontend.js

Kod:Tümünü seç

jQuery(document).ready(function($) {
    function fetchRssNews() {
        $.ajax({
            url: genelRssAjax.ajax_url,
            type: 'POST',
            data: { action: 'genel_rss_scrape' },
            success: function(response) {
                if(response.success) {
                    console.log("RSS Haber Eklendi:", response.data.message);
                } else {
                    console.log("RSS Haber Bulunamadı:", response.data.message);
                }
            },
            error: function() {
                console.log("RSS Bağlantı Hatası");
            }
        });
    }

    // Sayfa her yüklendiğinde bir haber çek
    fetchRssNews();

    // Örneğin, her 60 saniyede bir kontrol et
    setInterval(fetchRssNews, 60000);
});
muratca61
Site Admin
Mesajlar: 35964
Kayıt: Cmt Ara 21, 2024 7:56 am

Re: genel rss ekleme uygulaması wordpress

Mesaj gönderen muratca61 »

yeni dosya yapısı

Kod:Tümünü seç

genel-rss-haber-scraper/
├── genel-rss-haber-scraper.php    // Eklentinin ana PHP dosyası (ayarlar, haber çekme, AJAX işlemleri vs.)
├── js/
│   ├── genel-rss-admin.js         // Admin panelindeki tablo (satır ekleme/silme ve bağlantı kontrolü) işlemleri
│   └── genel-rss-frontend.js      // Ön yüzde otomatik RSS haber çekme işlemleri
└── readme.txt                     // Eklenti hakkında bilgi (isteğe bağlı)
muratca61
Site Admin
Mesajlar: 35964
Kayıt: Cmt Ara 21, 2024 7:56 am

Re: genel rss ekleme uygulaması wordpress

Mesaj gönderen muratca61 »

Kod:Tümünü seç

genel-rss-haber-scraper.php

Kod:Tümünü seç

<?php
/*
Plugin Name: Genel RSS Haber Scraper
Description: Excel benzeri tablo üzerinden RSS kaynaklarını ekleyip, RSS haberlerini çekmenize olanak tanır. Ayarlarda; RSS adresi, kategoriler, haber etiket kodu, link eklenip eklenmeyeceği, resim HTML kodu ve bağlantı kontrolü yapabilirsiniz.
Version: 1.0
Author: Örnek Geliştirici
License: GPL2
*/

if (!defined('ABSPATH')) {
    exit;
}

class Genel_RSS_Haber_Scraper {
    private $option_name = 'genel_rss_haber_scraper_sources';

    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));
        add_action('wp_ajax_genel_rss_scrape', array($this, 'handle_scrape_request'));
        add_action('wp_ajax_genel_rss_connection_check', array($this, 'handle_connection_check'));
        add_action('init', array($this, 'fetch_news_on_page_load'));

        add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'));
        add_action('wp_enqueue_scripts', array($this, 'frontend_enqueue_scripts'));
    }

    public function add_admin_menu() {
        add_menu_page(
            'Genel RSS Haber Scraper',
            'RSS Haber Scraper',
            'manage_options',
            'genel-rss-haber-scraper',
            array($this, 'admin_page'),
            'dashicons-rss',
            20
        );
    }

    public function register_settings() {
        register_setting('genel_rss_haber_scraper_options', $this->option_name);
    }

    public function admin_enqueue_scripts($hook) {
        if ($hook == 'toplevel_page_genel-rss-haber-scraper') {
            wp_enqueue_script(
                'genel-rss-admin',
                plugin_dir_url(__FILE__) . 'js/genel-rss-admin.js',
                array('jquery'),
                '1.0',
                true
            );
            wp_localize_script('genel-rss-admin', 'genelRssAdmin', array(
                'ajax_url' => admin_url('admin-ajax.php')
            ));
        }
    }

    public function frontend_enqueue_scripts() {
        wp_enqueue_script(
            'genel-rss-frontend',
            plugin_dir_url(__FILE__) . 'js/genel-rss-frontend.js',
            array('jquery'),
            '1.0',
            true
        );
        wp_localize_script('genel-rss-frontend', 'genelRssAjax', array(
            'ajax_url' => admin_url('admin-ajax.php')
        ));
    }

    public function admin_page() {
        // Kayıtlı RSS kaynaklarını alıyoruz
        $sources = get_option($this->option_name, array());
        ?>
        <div class="wrap">
            <h1>Genel RSS Haber Scraper</h1>
            <form method="post" action="options.php">
                <?php settings_fields('genel_rss_haber_scraper_options'); ?>
                <table class="widefat" id="rss-sources-table">
                    <thead>
                        <tr>
                            <th>RSS Adresi</th>
                            <th>Kategoriler (virgülle ayrılmış)</th>
                            <th>RSS Haber Etiket</th>
                            <th>Link Eklensin mi?</th>
                            <th>Resim HTML Kodu</th>
                            <th>Bağlantı Kontrol</th>
                            <th>İşlem</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        if (!empty($sources)) {
                            foreach ($sources as $index => $source) {
                                $rss_url    = isset($source['rss_url']) ? $source['rss_url'] : '';
                                $categories = isset($source['categories']) ? $source['categories'] : '';
                                $tag        = isset($source['tag']) ? $source['tag'] : '';
                                $add_link   = isset($source['add_link']) ? $source['add_link'] : '';
                                $image_html = isset($source['image_html']) ? $source['image_html'] : '';
                                ?>
                                <tr>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][rss_url]" value="<?php echo esc_attr($rss_url); ?>" size="40" />
                                    </td>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][categories]" value="<?php echo esc_attr($categories); ?>" size="30" placeholder="Kategori1,Kategori2" />
                                    </td>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][tag]" value="<?php echo esc_attr($tag); ?>" size="10" placeholder="item veya entry" />
                                    </td>
                                    <td>
                                        <input type="checkbox" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][add_link]" value="1" <?php checked($add_link, 1); ?> />
                                    </td>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][image_html]" value="<?php echo esc_attr($image_html); ?>" size="30" placeholder="<img src='...' />" />
                                    </td>
                                    <td>
                                        <button class="button connection-check" data-row-index="<?php echo $index; ?>">Bağlantıyı Kontrol Et</button>
                                        <span class="connection-result" id="conn-result-<?php echo $index; ?>"></span>
                                    </td>
                                    <td>
                                        <button class="button remove-row">Kaldır</button>
                                    </td>
                                </tr>
                                <?php
                            }
                        }
                        ?>
                    </tbody>
                </table>
                <p>
                    <button type="button" class="button" id="add-row">Yeni Satır Ekle</button>
                </p>
                <?php submit_button(); ?>
            </form>
            <hr>
            <h2>Manuel Haber Çekme</h2>
            <p>RSS haberlerini çekmek için aşağıdaki butona tıklayın.</p>
            <button id="fetch-rss-news" class="button button-primary">Haberleri Çek</button>
            <div id="rss-news-log" style="margin-top:20px;padding:10px;background:#f9f9f9;border:1px solid #ddd;max-height:300px;overflow-y:auto;"></div>
            <script>
            jQuery(document).ready(function($) {
                $('#fetch-rss-news').on('click', function() {
                    let log = $('#rss-news-log');
                    log.append('<p>Haberler çekiliyor...</p>');
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: { action: 'genel_rss_scrape' },
                        success: function(response) {
                            if(response.success) {
                                log.append('<p style="color:green;">' + response.data.message + '</p>');
                            } else {
                                log.append('<p style="color:red;">' + response.data.message + '</p>');
                            }
                        },
                        error: function() {
                            log.append('<p style="color:red;">Bağlantı hatası!</p>');
                        }
                    });
                });
            });
            </script>
        </div>
        <?php
    }

    // AJAX ile manuel haber çekme işlemi
    public function handle_scrape_request() {
        $result = $this->fetch_one_news();
        if ($result) {
            wp_send_json_success(array('message' => 'Bir haber çekildi.'));
        } else {
            wp_send_json_error(array('message' => 'Yeni haber bulunamadı veya RSS yüklenemedi.'));
        }
    }

    // AJAX: Bağlantı kontrolü için RSS adresini ve etiket bilgisini kontrol eder
    public function handle_connection_check() {
        $rss_url = isset($_POST['rss_url']) ? esc_url_raw($_POST['rss_url']) : '';
        $tag     = isset($_POST['tag']) ? sanitize_text_field($_POST['tag']) : '';

        if (empty($rss_url) || empty($tag)) {
            wp_send_json_error(array('message' => 'RSS URL ve Etiket bilgisi gerekli.'));
        }

        $rss_feed = @simplexml_load_file($rss_url);
        if (!$rss_feed) {
            wp_send_json_error(array('message' => 'RSS beslemesi yüklenemedi.'));
        }

        if ($tag === 'item' && isset($rss_feed->channel->item)) {
            wp_send_json_success(array('message' => 'Bağlantı başarılı: <item> bulundu.'));
        } elseif ($tag === 'entry' && isset($rss_feed->entry)) {
            wp_send_json_success(array('message' => 'Bağlantı başarılı: <entry> bulundu.'));
        } else {
            wp_send_json_error(array('message' => 'Belirtilen etiket bulunamadı.'));
        }
    }

    // Sayfa yüklenirken (frontend) otomatik haber çekme
    public function fetch_news_on_page_load() {
        if (!is_admin() && !is_feed()){
            $this->fetch_one_news();
        }
    }

    // RSS kaynağına göre haber çekme işlemleri (hem item hem entry destekli)
    private function fetch_one_news() {
        require_once(ABSPATH . 'wp-admin/includes/post.php');
        $sources = get_option($this->option_name, array());
        if (empty($sources)) {
            return false;
        }
        foreach ($sources as $source) {
            $rss_url       = isset($source['rss_url']) ? trim($source['rss_url']) : '';
            $categories_str= isset($source['categories']) ? trim($source['categories']) : '';
            $tag           = isset($source['tag']) ? trim($source['tag']) : '';
            $add_link      = isset($source['add_link']) ? $source['add_link'] : 0;
            $image_html    = isset($source['image_html']) ? trim($source['image_html']) : '';

            if (empty($rss_url) || empty($tag)) {
                continue;
            }

            $rss_feed = @simplexml_load_file($rss_url);
            if (!$rss_feed) {
                error_log('RSS yüklenemedi: ' . $rss_url);
                continue;
            }

            if ($tag === 'item' && isset($rss_feed->channel->item)) {
                foreach ($rss_feed->channel->item as $item) {
                    $title       = (string)$item->title;
                    $link        = (string)$item->link;
                    $description = (string)strip_tags($item->description);
                    $content     = isset($item->children('content', true)->encoded) ? (string)strip_tags($item->children('content', true)->encoded) : '';

                    if (post_exists($title)) { continue; }
                    if (empty($title) || (empty($content) && empty($description))) { continue; }

                    $post_content = '<p>' . esc_html($description) . '</p><p>' . esc_html($content) . '</p>';
                    if ($add_link) {
                        $post_content .= '<p><a href="' . esc_url($link) . '">Kaynak</a></p>';
                    }
                    $category_ids = array();
                    if (!empty($categories_str)) {
                        $categories = array_map('trim', explode(',', $categories_str));
                        foreach ($categories as $cat_name) {
                            $cat_id = get_cat_ID($cat_name);
                            if (!$cat_id) { $cat_id = wp_create_category($cat_name); }
                            $category_ids[] = $cat_id;
                        }
                    }
                    $post_id = wp_insert_post(array(
                        'post_title'    => wp_strip_all_tags($title),
                        'post_content'  => $post_content,
                        'post_status'   => 'publish',
                        'post_author'   => 1,
                        'post_category' => $category_ids,
                        'post_type'     => 'post'
                    ));
                    if (!is_wp_error($post_id)) {
                        if (!empty($image_html)) {
                            $post_content .= "\n" . $image_html;
                            wp_update_post(array(
                                'ID'           => $post_id,
                                'post_content' => $post_content
                            ));
                        }
                        return true;
                    }
                }
            } elseif ($tag === 'entry' && isset($rss_feed->entry)) {
                foreach ($rss_feed->entry as $entry) {
                    $title       = (string)$entry->title;
                    $link        = '';
                    if (isset($entry->link)) {
                        foreach ($entry->link as $l) {
                            $attributes = $l->attributes();
                            if (isset($attributes['rel']) && (string)$attributes['rel'] === 'alternate') {
                                $link = (string)$attributes['href'];
                                break;
                            }
                        }
                        if (empty($link)) { $link = (string)$entry->link; }
                    }
                    $description = isset($entry->summary) ? (string)strip_tags($entry->summary) : '';
                    $content     = isset($entry->content) ? (string)strip_tags($entry->content) : '';

                    if (post_exists($title)) { continue; }
                    if (empty($title) || (empty($content) && empty($description))) { continue; }

                    $post_content = '<p>' . esc_html($description) . '</p><p>' . esc_html($content) . '</p>';
                    if ($add_link) {
                        $post_content .= '<p><a href="' . esc_url($link) . '">Kaynak</a></p>';
                    }
                    $category_ids = array();
                    if (!empty($categories_str)) {
                        $categories = array_map('trim', explode(',', $categories_str));
                        foreach ($categories as $cat_name) {
                            $cat_id = get_cat_ID($cat_name);
                            if (!$cat_id) { $cat_id = wp_create_category($cat_name); }
                            $category_ids[] = $cat_id;
                        }
                    }
                    $post_id = wp_insert_post(array(
                        'post_title'    => wp_strip_all_tags($title),
                        'post_content'  => $post_content,
                        'post_status'   => 'publish',
                        'post_author'   => 1,
                        'post_category' => $category_ids,
                        'post_type'     => 'post'
                    ));
                    if (!is_wp_error($post_id)) { return true; }
                }
            }
        }
        return false;
    }
}

new Genel_RSS_Haber_Scraper();
muratca61
Site Admin
Mesajlar: 35964
Kayıt: Cmt Ara 21, 2024 7:56 am

Re: genel rss ekleme uygulaması wordpress

Mesaj gönderen muratca61 »

Kod:Tümünü seç

genel-rss-admin.js

Kod:Tümünü seç

jQuery(document).ready(function($) {
    // Yeni satır ekleme
    $('#add-row').on('click', function(e) {
        e.preventDefault();
        var index = $('#rss-sources-table tbody tr').length;
        var row = '<tr>' +
            '<td><input type="text" name="genel_rss_haber_scraper_sources['+index+'][rss_url]" value="" size="40" /></td>' +
            '<td><input type="text" name="genel_rss_haber_scraper_sources['+index+'][categories]" value="" size="30" placeholder="Kategori1,Kategori2" /></td>' +
            '<td><input type="text" name="genel_rss_haber_scraper_sources['+index+'][tag]" value="" size="10" placeholder="item veya entry" /></td>' +
            '<td><input type="checkbox" name="genel_rss_haber_scraper_sources['+index+'][add_link]" value="1" /></td>' +
            '<td><input type="text" name="genel_rss_haber_scraper_sources['+index+'][image_html]" value="" size="30" placeholder="<img src=\'...\' />" /></td>' +
            '<td><button class="button connection-check" data-row-index="'+index+'">Bağlantıyı Kontrol Et</button>' +
            '<span class="connection-result" id="conn-result-'+index+'"></span></td>' +
            '<td><button class="button remove-row">Kaldır</button></td>' +
            '</tr>';
        $('#rss-sources-table tbody').append(row);
    });

    // Satır silme
    $('#rss-sources-table').on('click', '.remove-row', function(e) {
        e.preventDefault();
        $(this).closest('tr').remove();
    });

    // Bağlantı kontrolü
    $('#rss-sources-table').on('click', '.connection-check', function(e) {
        e.preventDefault();
        var rowIndex = $(this).data('row-index');
        var row = $(this).closest('tr');
        var rss_url = row.find('input[name^="genel_rss_haber_scraper_sources"]')
                         .filter('[name*="[rss_url]"]').val();
        var tag = row.find('input[name^="genel_rss_haber_scraper_sources"]')
                     .filter('[name*="[tag]"]').val();
        var resultSpan = $('#conn-result-' + rowIndex);
        resultSpan.text('Kontrol ediliyor...');
        $.ajax({
            url: genelRssAdmin.ajax_url,
            type: 'POST',
            data: {
                action: 'genel_rss_connection_check',
                rss_url: rss_url,
                tag: tag
            },
            success: function(response) {
                if(response.success) {
                    resultSpan.text(response.data.message).css('color', 'green');
                } else {
                    resultSpan.text(response.data.message).css('color', 'red');
                }
            },
            error: function() {
                resultSpan.text('Bağlantı hatası!').css('color', 'red');
            }
        });
    });
});
muratca61
Site Admin
Mesajlar: 35964
Kayıt: Cmt Ara 21, 2024 7:56 am

Re: genel rss ekleme uygulaması wordpress

Mesaj gönderen muratca61 »

Kod:Tümünü seç

genel-rss-frontend.js

Kod:Tümünü seç

jQuery(document).ready(function($) {
    function fetchRssNews() {
        $.ajax({
            url: genelRssAjax.ajax_url,
            type: 'POST',
            data: { action: 'genel_rss_scrape' },
            success: function(response) {
                if(response.success) {
                    console.log("RSS Haber Eklendi:", response.data.message);
                } else {
                    console.log("RSS Haber Bulunamadı:", response.data.message);
                }
            },
            error: function() {
                console.log("RSS Bağlantı Hatası");
            }
        });
    }

    // Sayfa yüklendiğinde bir haber çek
    fetchRssNews();

    // Örneğin, her 60 saniyede bir RSS haberlerini kontrol et
    setInterval(fetchRssNews, 60000);
});
muratca61
Site Admin
Mesajlar: 35964
Kayıt: Cmt Ara 21, 2024 7:56 am

Re: genel rss ekleme uygulaması wordpress

Mesaj gönderen muratca61 »

otomatik resim eklemeli

Kod:Tümünü seç

<?php
/*
Plugin Name: Genel RSS Haber Scraper
Description: Excel benzeri tablo üzerinden RSS kaynaklarını ekleyip, RSS haberlerini çekmenize olanak tanır. Ayarlarda; RSS adresi, kategoriler, haber etiket kodu, link eklenip eklenmeyeceği, resim HTML kodu ve bağlantı kontrolü yapabilirsiniz.
Version: 1.0
Author: Örnek Geliştirici
License: GPL2
*/

if (!defined('ABSPATH')) {
    exit;
}

class Genel_RSS_Haber_Scraper {
    private $option_name = 'genel_rss_haber_scraper_sources';

    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));
        add_action('wp_ajax_genel_rss_scrape', array($this, 'handle_scrape_request'));
        add_action('wp_ajax_genel_rss_connection_check', array($this, 'handle_connection_check'));
        add_action('init', array($this, 'fetch_news_on_page_load'));

        add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'));
        add_action('wp_enqueue_scripts', array($this, 'frontend_enqueue_scripts'));
    }

    public function add_admin_menu() {
        add_menu_page(
            'Genel RSS Haber Scraper',
            'RSS Haber Scraper',
            'manage_options',
            'genel-rss-haber-scraper',
            array($this, 'admin_page'),
            'dashicons-rss',
            20
        );
    }

    public function register_settings() {
        register_setting('genel_rss_haber_scraper_options', $this->option_name);
    }

    public function admin_enqueue_scripts($hook) {
        if ($hook == 'toplevel_page_genel-rss-haber-scraper') {
            wp_enqueue_script(
                'genel-rss-admin',
                plugin_dir_url(__FILE__) . 'js/genel-rss-admin.js',
                array('jquery'),
                '1.0',
                true
            );
            wp_localize_script('genel-rss-admin', 'genelRssAdmin', array(
                'ajax_url' => admin_url('admin-ajax.php')
            ));
        }
    }

    public function frontend_enqueue_scripts() {
        wp_enqueue_script(
            'genel-rss-frontend',
            plugin_dir_url(__FILE__) . 'js/genel-rss-frontend.js',
            array('jquery'),
            '1.0',
            true
        );
        wp_localize_script('genel-rss-frontend', 'genelRssAjax', array(
            'ajax_url' => admin_url('admin-ajax.php')
        ));
    }

    public function admin_page() {
        // Kayıtlı RSS kaynaklarını alıyoruz
        $sources = get_option($this->option_name, array());
        ?>
        <div class="wrap">
            <h1>Genel RSS Haber Scraper</h1>
            <form method="post" action="options.php">
                <?php settings_fields('genel_rss_haber_scraper_options'); ?>
                <table class="widefat" id="rss-sources-table">
                    <thead>
                        <tr>
                            <th>RSS Adresi</th>
                            <th>Kategoriler (virgülle ayrılmış)</th>
                            <th>RSS Haber Etiket</th>
                            <th>Link Eklensin mi?</th>
                            <th>Resim HTML Kodu</th>
                            <th>Bağlantı Kontrol</th>
                            <th>İşlem</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        if (!empty($sources)) {
                            foreach ($sources as $index => $source) {
                                $rss_url    = isset($source['rss_url']) ? $source['rss_url'] : '';
                                $categories = isset($source['categories']) ? $source['categories'] : '';
                                $tag        = isset($source['tag']) ? $source['tag'] : '';
                                $add_link   = isset($source['add_link']) ? $source['add_link'] : '';
                                $image_html = isset($source['image_html']) ? $source['image_html'] : '';
                                ?>
                                <tr>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][rss_url]" value="<?php echo esc_attr($rss_url); ?>" size="40" />
                                    </td>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][categories]" value="<?php echo esc_attr($categories); ?>" size="30" placeholder="Kategori1,Kategori2" />
                                    </td>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][tag]" value="<?php echo esc_attr($tag); ?>" size="10" placeholder="item veya entry" />
                                    </td>
                                    <td>
                                        <input type="checkbox" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][add_link]" value="1" <?php checked($add_link, 1); ?> />
                                    </td>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][image_html]" value="<?php echo esc_attr($image_html); ?>" size="30" placeholder="<img src='...' />" />
                                    </td>
                                    <td>
                                        <button class="button connection-check" data-row-index="<?php echo $index; ?>">Bağlantıyı Kontrol Et</button>
                                        <span class="connection-result" id="conn-result-<?php echo $index; ?>"></span>
                                    </td>
                                    <td>
                                        <button class="button remove-row">Kaldır</button>
                                    </td>
                                </tr>
                                <?php
                            }
                        }
                        ?>
                    </tbody>
                </table>
                <p>
                    <button type="button" class="button" id="add-row">Yeni Satır Ekle</button>
                </p>
                <?php submit_button(); ?>
            </form>
            <hr>
            <h2>Manuel Haber Çekme</h2>
            <p>RSS haberlerini çekmek için aşağıdaki butona tıklayın.</p>
            <button id="fetch-rss-news" class="button button-primary">Haberleri Çek</button>
            <div id="rss-news-log" style="margin-top:20px;padding:10px;background:#f9f9f9;border:1px solid #ddd;max-height:300px;overflow-y:auto;"></div>
            <script>
            jQuery(document).ready(function($) {
                $('#fetch-rss-news').on('click', function() {
                    let log = $('#rss-news-log');
                    log.append('<p>Haberler çekiliyor...</p>');
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: { action: 'genel_rss_scrape' },
                        success: function(response) {
                            if(response.success) {
                                log.append('<p style="color:green;">' + response.data.message + '</p>');
                            } else {
                                log.append('<p style="color:red;">' + response.data.message + '</p>');
                            }
                        },
                        error: function() {
                            log.append('<p style="color:red;">Bağlantı hatası!</p>');
                        }
                    });
                });
            });
            </script>
        </div>
        <?php
    }

    // AJAX ile manuel haber çekme işlemi
    public function handle_scrape_request() {
        $result = $this->fetch_one_news();
        if ($result) {
            wp_send_json_success(array('message' => 'Bir haber çekildi.'));
        } else {
            wp_send_json_error(array('message' => 'Yeni haber bulunamadı veya RSS yüklenemedi.'));
        }
    }

    // AJAX: Bağlantı kontrolü için RSS adresi ve etiket bilgisini kontrol eder
    public function handle_connection_check() {
        $rss_url = isset($_POST['rss_url']) ? esc_url_raw($_POST['rss_url']) : '';
        $tag     = isset($_POST['tag']) ? sanitize_text_field($_POST['tag']) : '';

        if (empty($rss_url) || empty($tag)) {
            wp_send_json_error(array('message' => 'RSS URL ve Etiket bilgisi gerekli.'));
        }

        $rss_feed = @simplexml_load_file($rss_url);
        if (!$rss_feed) {
            wp_send_json_error(array('message' => 'RSS beslemesi yüklenemedi.'));
        }

        if ($tag === 'item' && isset($rss_feed->channel->item)) {
            wp_send_json_success(array('message' => 'Bağlantı başarılı: <item> bulundu.'));
        } elseif ($tag === 'entry' && isset($rss_feed->entry)) {
            wp_send_json_success(array('message' => 'Bağlantı başarılı: <entry> bulundu.'));
        } else {
            wp_send_json_error(array('message' => 'Belirtilen etiket bulunamadı.'));
        }
    }

    // Sayfa yüklenirken (frontend) otomatik haber çekme
    public function fetch_news_on_page_load() {
        if (!is_admin() && !is_feed()){
            $this->fetch_one_news();
        }
    }

    // RSS kaynağına göre haber çekme işlemleri (hem item hem entry destekli)
    private function fetch_one_news() {
        require_once(ABSPATH . 'wp-admin/includes/post.php');
        $sources = get_option($this->option_name, array());
        if (empty($sources)) {
            return false;
        }
        foreach ($sources as $source) {
            $rss_url        = isset($source['rss_url']) ? trim($source['rss_url']) : '';
            $categories_str = isset($source['categories']) ? trim($source['categories']) : '';
            $tag            = isset($source['tag']) ? trim($source['tag']) : '';
            $add_link       = isset($source['add_link']) ? $source['add_link'] : 0;
            $image_html     = isset($source['image_html']) ? trim($source['image_html']) : '';

            if (empty($rss_url) || empty($tag)) {
                continue;
            }

            $rss_feed = @simplexml_load_file($rss_url);
            if (!$rss_feed) {
                error_log('RSS yüklenemedi: ' . $rss_url);
                continue;
            }

            if ($tag === 'item' && isset($rss_feed->channel->item)) {
                foreach ($rss_feed->channel->item as $item) {
                    $title       = (string)$item->title;
                    $link        = (string)$item->link;
                    $description = (string)strip_tags($item->description);
                    $content     = isset($item->children('content', true)->encoded) ? (string)strip_tags($item->children('content', true)->encoded) : '';
                    $image_url   = isset($item->enclosure['url']) ? (string)$item->enclosure['url'] : '';

                    // Eğer enclosure ile görsel alınamadıysa, description veya content içinde arama yapalım.
                    if (empty($image_url)) {
                        $combined_text = $description . ' ' . $content;
                        if (preg_match('/https?:\/\/[^\s"\']+\.(png|jpg|wrp)/i', $combined_text, $matches)) {
                            $image_url = $matches[0];
                        }
                    }

                    if (post_exists($title)) { 
                        continue; 
                    }
                    if (empty($title) || (empty($content) && empty($description))) { 
                        continue; 
                    }

                    $post_content = '<p>' . esc_html($description) . '</p><p>' . esc_html($content) . '</p>';
                    if ($add_link) {
                        $post_content .= '<p><a href="' . esc_url($link) . '">Kaynak</a></p>';
                    }
                    $category_ids = array();
                    if (!empty($categories_str)) {
                        $categories = array_map('trim', explode(',', $categories_str));
                        foreach ($categories as $cat_name) {
                            $cat_id = get_cat_ID($cat_name);
                            if (!$cat_id) { 
                                $cat_id = wp_create_category($cat_name); 
                            }
                            $category_ids[] = $cat_id;
                        }
                    }
                    $post_id = wp_insert_post(array(
                        'post_title'    => wp_strip_all_tags($title),
                        'post_content'  => $post_content,
                        'post_status'   => 'publish',
                        'post_author'   => 1,
                        'post_category' => $category_ids,
                        'post_type'     => 'post'
                    ));
                    if (!is_wp_error($post_id)) {
                        // Görsel ekleme işlemi
                        if (!empty($image_url)) {
                            require_once(ABSPATH . 'wp-admin/includes/media.php');
                            require_once(ABSPATH . 'wp-admin/includes/file.php');
                            require_once(ABSPATH . 'wp-admin/includes/image.php');
                            $attachment_id = media_sideload_image($image_url, $post_id, $title, 'id');
                            if (!is_wp_error($attachment_id)) {
                                set_post_thumbnail($post_id, $attachment_id);
                            }
                        }
                        // Resim HTML kodunu ekleme (varsa)
                        if (!empty($image_html)) {
                            $post_content .= "\n" . $image_html;
                            wp_update_post(array(
                                'ID'           => $post_id,
                                'post_content' => $post_content
                            ));
                        }
                        return true;
                    }
                }
            } elseif ($tag === 'entry' && isset($rss_feed->entry)) {
                foreach ($rss_feed->entry as $entry) {
                    $title       = (string)$entry->title;
                    $link        = '';
                    if (isset($entry->link)) {
                        foreach ($entry->link as $l) {
                            $attributes = $l->attributes();
                            if (isset($attributes['rel']) && (string)$attributes['rel'] === 'alternate') {
                                $link = (string)$attributes['href'];
                                break;
                            }
                        }
                        if (empty($link)) { 
                            $link = (string)$entry->link; 
                        }
                    }
                    $description = isset($entry->summary) ? (string)strip_tags($entry->summary) : '';
                    $content     = isset($entry->content) ? (string)strip_tags($entry->content) : '';
                    $image_url   = ''; // Atom feed'lerde varsayılan olarak enclosure yok

                    // İçerik içinde .png, .jpg veya .wrp uzantılı bir URL arayalım
                    if (empty($image_url)) {
                        $combined_text = $description . ' ' . $content;
                        if (preg_match('/https?:\/\/[^\s"\']+\.(png|jpg|wrp)/i', $combined_text, $matches)) {
                            $image_url = $matches[0];
                        }
                    }

                    if (post_exists($title)) { 
                        continue; 
                    }
                    if (empty($title) || (empty($content) && empty($description))) { 
                        continue; 
                    }

                    $post_content = '<p>' . esc_html($description) . '</p><p>' . esc_html($content) . '</p>';
                    if ($add_link) {
                        $post_content .= '<p><a href="' . esc_url($link) . '">Kaynak</a></p>';
                    }
                    $category_ids = array();
                    if (!empty($categories_str)) {
                        $categories = array_map('trim', explode(',', $categories_str));
                        foreach ($categories as $cat_name) {
                            $cat_id = get_cat_ID($cat_name);
                            if (!$cat_id) { 
                                $cat_id = wp_create_category($cat_name); 
                            }
                            $category_ids[] = $cat_id;
                        }
                    }
                    $post_id = wp_insert_post(array(
                        'post_title'    => wp_strip_all_tags($title),
                        'post_content'  => $post_content,
                        'post_status'   => 'publish',
                        'post_author'   => 1,
                        'post_category' => $category_ids,
                        'post_type'     => 'post'
                    ));
                    if (!is_wp_error($post_id)) {
                        if (!empty($image_url)) {
                            require_once(ABSPATH . 'wp-admin/includes/media.php');
                            require_once(ABSPATH . 'wp-admin/includes/file.php');
                            require_once(ABSPATH . 'wp-admin/includes/image.php');
                            $attachment_id = media_sideload_image($image_url, $post_id, $title, 'id');
                            if (!is_wp_error($attachment_id)) {
                                set_post_thumbnail($post_id, $attachment_id);
                            }
                        }
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

new Genel_RSS_Haber_Scraper();
muratca61
Site Admin
Mesajlar: 35964
Kayıt: Cmt Ara 21, 2024 7:56 am

Re: genel rss ekleme uygulaması wordpress

Mesaj gönderen muratca61 »

bunlar çalışıyor ama etiketlemede sorun var

Kod:Tümünü seç

genel-rss-admin.js

Kod:Tümünü seç

jQuery(document).ready(function($) {
    // Yeni satır ekleme
    $('#add-row').on('click', function(e) {
        e.preventDefault();
        var index = $('#rss-sources-table tbody tr').length;
        var row = '<tr>' +
            '<td><input type="text" name="genel_rss_haber_scraper_sources['+index+'][rss_url]" value="" size="40" /></td>' +
            '<td><input type="text" name="genel_rss_haber_scraper_sources['+index+'][categories]" value="" size="30" placeholder="Kategori1,Kategori2" /></td>' +
            '<td><input type="text" name="genel_rss_haber_scraper_sources['+index+'][tag]" value="" size="10" placeholder="item veya entry" /></td>' +
            '<td><input type="checkbox" name="genel_rss_haber_scraper_sources['+index+'][add_link]" value="1" /></td>' +
            '<td><input type="text" name="genel_rss_haber_scraper_sources['+index+'][image_html]" value="" size="30" placeholder="<img src=\'...\' />" /></td>' +
            '<td><button class="button connection-check" data-row-index="'+index+'">Bağlantıyı Kontrol Et</button>' +
            '<span class="connection-result" id="conn-result-'+index+'"></span></td>' +
            '<td><button class="button remove-row">Kaldır</button></td>' +
            '</tr>';
        $('#rss-sources-table tbody').append(row);
    });

    // Satır silme
    $('#rss-sources-table').on('click', '.remove-row', function(e) {
        e.preventDefault();
        $(this).closest('tr').remove();
    });

    // Bağlantı kontrolü
    $('#rss-sources-table').on('click', '.connection-check', function(e) {
        e.preventDefault();
        var rowIndex = $(this).data('row-index');
        var row = $(this).closest('tr');
        var rss_url = row.find('input[name^="genel_rss_haber_scraper_sources"]').filter('[name*="[rss_url]"]').val();
        var tag = row.find('input[name^="genel_rss_haber_scraper_sources"]').filter('[name*="[tag]"]').val();
        var resultSpan = $('#conn-result-' + rowIndex);
        resultSpan.text('Kontrol ediliyor...');
        $.ajax({
            url: genelRssAdmin.ajax_url,
            type: 'POST',
            data: {
                action: 'genel_rss_connection_check',
                rss_url: rss_url,
                tag: tag
            },
            success: function(response) {
                if(response.success) {
                    resultSpan.text(response.data.message).css('color', 'green');
                } else {
                    resultSpan.text(response.data.message).css('color', 'red');
                }
            },
            error: function() {
                resultSpan.text('Bağlantı hatası!').css('color', 'red');
            }
        });
    });
});

Kod:Tümünü seç

genel-rss-frontend.js

Kod:Tümünü seç

jQuery(document).ready(function($) {
    function fetchRssNews() {
        $.ajax({
            url: genelRssAjax.ajax_url,
            type: 'POST',
            data: { action: 'genel_rss_scrape' },
            success: function(response) {
                if(response.success) {
                    console.log("RSS Haber Eklendi:", response.data.message);
                } else {
                    console.log("RSS Haber Bulunamadı:", response.data.message);
                }
            },
            error: function() {
                console.log("RSS Bağlantı Hatası");
            }
        });
    }

    // Sayfa yüklendiğinde bir haber çek
    fetchRssNews();

    // Örneğin, her 60 saniyede bir RSS haberlerini kontrol et
    setInterval(fetchRssNews, 60000);
});

Kod:Tümünü seç

<?php
/*
Plugin Name: Genel RSS Haber Scraper
Description: Excel benzeri tablo üzerinden RSS kaynaklarını ekleyip, RSS haberlerini çekmenize olanak tanır. Ayarlarda; RSS adresi, kategoriler, RSS haber etiket kodu, link eklenip eklenmeyeceği, resim HTML kodu ve bağlantı kontrolü yapabilirsiniz. Ayrıca, yazı içeriğinden cümle başları hariç büyük harfli olan ve en çok geçen kelimelerden otomatik 5 etiket oluşturur.
Version: 1.0
Author: Örnek Geliştirici
License: GPL2
*/

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Genel_RSS_Haber_Scraper {
    private $option_name = 'genel_rss_haber_scraper_sources';

    public function __construct() {
        add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        add_action( 'wp_ajax_genel_rss_scrape', array( $this, 'handle_scrape_request' ) );
        add_action( 'wp_ajax_genel_rss_connection_check', array( $this, 'handle_connection_check' ) );
        add_action( 'init', array( $this, 'fetch_news_on_page_load' ) );

        add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
        add_action( 'wp_enqueue_scripts', array( $this, 'frontend_enqueue_scripts' ) );
    }

    public function add_admin_menu() {
        add_menu_page(
            'Genel RSS Haber Scraper',
            'RSS Haber Scraper',
            'manage_options',
            'genel-rss-haber-scraper',
            array( $this, 'admin_page' ),
            'dashicons-rss',
            20
        );
    }

    public function register_settings() {
        register_setting( 'genel_rss_haber_scraper_options', $this->option_name );
    }

    public function admin_enqueue_scripts( $hook ) {
        if ( $hook == 'toplevel_page_genel-rss-haber-scraper' ) {
            wp_enqueue_script(
                'genel-rss-admin',
                plugin_dir_url( __FILE__ ) . 'js/genel-rss-admin.js',
                array( 'jquery' ),
                '1.0',
                true
            );
            wp_localize_script( 'genel-rss-admin', 'genelRssAdmin', array(
                'ajax_url' => admin_url( 'admin-ajax.php' )
            ) );
        }
    }

    public function frontend_enqueue_scripts() {
        wp_enqueue_script(
            'genel-rss-frontend',
            plugin_dir_url( __FILE__ ) . 'js/genel-rss-frontend.js',
            array( 'jquery' ),
            '1.0',
            true
        );
        wp_localize_script( 'genel-rss-frontend', 'genelRssAjax', array(
            'ajax_url' => admin_url( 'admin-ajax.php' )
        ) );
    }

    public function admin_page() {
        // Kayıtlı RSS kaynaklarını alıyoruz
        $sources = get_option( $this->option_name, array() );
        ?>
        <div class="wrap">
            <h1>Genel RSS Haber Scraper</h1>
            <form method="post" action="options.php">
                <?php settings_fields( 'genel_rss_haber_scraper_options' ); ?>
                <table class="widefat" id="rss-sources-table">
                    <thead>
                        <tr>
                            <th>RSS Adresi</th>
                            <th>Kategoriler (virgülle ayrılmış)</th>
                            <th>RSS Haber Etiket</th>
                            <th>Link Eklensin mi?</th>
                            <th>Resim HTML Kodu</th>
                            <th>Bağlantı Kontrol</th>
                            <th>İşlem</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        if ( ! empty( $sources ) ) {
                            foreach ( $sources as $index => $source ) {
                                $rss_url    = isset( $source['rss_url'] ) ? $source['rss_url'] : '';
                                $categories = isset( $source['categories'] ) ? $source['categories'] : '';
                                $tag        = isset( $source['tag'] ) ? $source['tag'] : '';
                                $add_link   = isset( $source['add_link'] ) ? $source['add_link'] : '';
                                $image_html = isset( $source['image_html'] ) ? $source['image_html'] : '';
                                ?>
                                <tr>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][rss_url]" value="<?php echo esc_attr( $rss_url ); ?>" size="40" />
                                    </td>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][categories]" value="<?php echo esc_attr( $categories ); ?>" size="30" placeholder="Kategori1,Kategori2" />
                                    </td>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][tag]" value="<?php echo esc_attr( $tag ); ?>" size="10" placeholder="item veya entry" />
                                    </td>
                                    <td>
                                        <input type="checkbox" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][add_link]" value="1" <?php checked( $add_link, 1 ); ?> />
                                    </td>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][image_html]" value="<?php echo esc_attr( $image_html ); ?>" size="30" placeholder="<img src='...' />" />
                                    </td>
                                    <td>
                                        <button class="button connection-check" data-row-index="<?php echo $index; ?>">Bağlantıyı Kontrol Et</button>
                                        <span class="connection-result" id="conn-result-<?php echo $index; ?>"></span>
                                    </td>
                                    <td>
                                        <button class="button remove-row">Kaldır</button>
                                    </td>
                                </tr>
                                <?php
                            }
                        }
                        ?>
                    </tbody>
                </table>
                <p>
                    <button type="button" class="button" id="add-row">Yeni Satır Ekle</button>
                </p>
                <?php submit_button(); ?>
            </form>
            <hr>
            <h2>Manuel Haber Çekme</h2>
            <p>RSS haberlerini çekmek için aşağıdaki butona tıklayın.</p>
            <button id="fetch-rss-news" class="button button-primary">Haberleri Çek</button>
            <div id="rss-news-log" style="margin-top:20px;padding:10px;background:#f9f9f9;border:1px solid #ddd;max-height:300px;overflow-y:auto;"></div>
            <script>
            jQuery(document).ready(function($) {
                $('#fetch-rss-news').on('click', function() {
                    let log = $('#rss-news-log');
                    log.append('<p>Haberler çekiliyor...</p>');
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: { action: 'genel_rss_scrape' },
                        success: function(response) {
                            if(response.success) {
                                log.append('<p style="color:green;">' + response.data.message + '</p>');
                            } else {
                                log.append('<p style="color:red;">' + response.data.message + '</p>');
                            }
                        },
                        error: function() {
                            log.append('<p style="color:red;">Bağlantı hatası!</p>');
                        }
                    });
                });
            });
            </script>
        </div>
        <?php
    }

    // AJAX ile manuel haber çekme işlemi
    public function handle_scrape_request() {
        $result = $this->fetch_one_news();
        if ( $result ) {
            wp_send_json_success( array( 'message' => 'Bir haber çekildi.' ) );
        } else {
            wp_send_json_error( array( 'message' => 'Yeni haber bulunamadı.' ) );
        }
    }

    // AJAX: Bağlantı kontrolü için RSS adresi ve etiket bilgisini kontrol eder
    public function handle_connection_check() {
        $rss_url = isset( $_POST['rss_url'] ) ? esc_url_raw( $_POST['rss_url'] ) : '';
        $tag     = isset( $_POST['tag'] ) ? sanitize_text_field( $_POST['tag'] ) : '';

        if ( empty( $rss_url ) || empty( $tag ) ) {
            wp_send_json_error( array( 'message' => 'RSS URL ve Etiket bilgisi gerekli.' ) );
        }

        $rss_feed = @simplexml_load_file( $rss_url );
        if ( ! $rss_feed ) {
            wp_send_json_error( array( 'message' => 'RSS beslemesi yüklenemedi.' ) );
        }

        if ( $tag === 'item' && isset( $rss_feed->channel->item ) ) {
            wp_send_json_success( array( 'message' => 'Bağlantı başarılı: <item> bulundu.' ) );
        } elseif ( $tag === 'entry' && isset( $rss_feed->entry ) ) {
            wp_send_json_success( array( 'message' => 'Bağlantı başarılı: <entry> bulundu.' ) );
        } else {
            wp_send_json_error( array( 'message' => 'Belirtilen etiket bulunamadı.' ) );
        }
    }

    // Sayfa yüklenirken (frontend) otomatik haber çekme
    public function fetch_news_on_page_load() {
        if ( ! is_admin() && ! is_feed() ) {
            $this->fetch_one_news();
        }
    }

    // RSS kaynağından haber çekme işlemi
    private function fetch_one_news() {
        require_once( ABSPATH . 'wp-admin/includes/post.php' );
        $sources = get_option( $this->option_name, array() );
        if ( empty( $sources ) ) {
            return false;
        }
        $new_post_added = false;
        foreach ( $sources as $source ) {
            $rss_url        = isset( $source['rss_url'] ) ? trim( $source['rss_url'] ) : '';
            $categories_str = isset( $source['categories'] ) ? trim( $source['categories'] ) : '';
            $tag            = isset( $source['tag'] ) ? trim( $source['tag'] ) : '';
            $add_link       = isset( $source['add_link'] ) ? $source['add_link'] : 0;
            $image_html     = isset( $source['image_html'] ) ? trim( $source['image_html'] ) : '';

            if ( empty( $rss_url ) || empty( $tag ) ) {
                continue;
            }

            $rss_feed = @simplexml_load_file( $rss_url );
            if ( ! $rss_feed ) {
                error_log( 'RSS yüklenemedi: ' . $rss_url );
                continue;
            }

            // --- RSS item yapısı ---
            if ( $tag === 'item' && isset( $rss_feed->channel->item ) ) {
                foreach ( $rss_feed->channel->item as $item ) {
                    $title = (string) $item->title;
                    // Aynı başlık varsa bu haberi çekme
                    if ( post_exists( $title ) ) {
                        continue;
                    }
                    $link        = (string) $item->link;
                    $description = (string) strip_tags( $item->description );
                    $content     = isset( $item->children( 'content', true )->encoded ) ? (string) strip_tags( $item->children( 'content', true )->encoded ) : '';
                    $image_url   = isset( $item->enclosure['url'] ) ? (string) $item->enclosure['url'] : '';

                    // Görsel enclosure yoksa, description veya content içinde arama yapalım
                    if ( empty( $image_url ) ) {
                        $combined_text = $description . ' ' . $content;
                        if ( preg_match( '/https?:\/\/[^\s"\']+\.(png|jpg|wrp)/i', $combined_text, $matches ) ) {
                            $image_url = $matches[0];
                        }
                    }

                    if ( empty( $title ) || ( empty( $content ) && empty( $description ) ) ) {
                        continue;
                    }

                    $post_content = '<p>' . esc_html( $description ) . '</p><p>' . esc_html( $content ) . '</p>';
                    if ( $add_link ) {
                        $post_content .= '<p><a href="' . esc_url( $link ) . '">Kaynak</a></p>';
                    }
                    $category_ids = array();
                    if ( ! empty( $categories_str ) ) {
                        $categories = array_map( 'trim', explode( ',', $categories_str ) );
                        foreach ( $categories as $cat_name ) {
                            $cat_id = get_cat_ID( $cat_name );
                            if ( ! $cat_id ) {
                                $cat_id = wp_create_category( $cat_name );
                            }
                            $category_ids[] = $cat_id;
                        }
                    }
                    $post_id = wp_insert_post( array(
                        'post_title'    => wp_strip_all_tags( $title ),
                        'post_content'  => $post_content,
                        'post_status'   => 'publish',
                        'post_author'   => 1,
                        'post_category' => $category_ids,
                        'post_type'     => 'post'
                    ) );
                    if ( ! is_wp_error( $post_id ) ) {
                        // Görsel ekleme işlemi
                        if ( ! empty( $image_url ) ) {
                            require_once( ABSPATH . 'wp-admin/includes/media.php' );
                            require_once( ABSPATH . 'wp-admin/includes/file.php' );
                            require_once( ABSPATH . 'wp-admin/includes/image.php' );
                            $attachment_id = media_sideload_image( $image_url, $post_id, $title, 'id' );
                            if ( ! is_wp_error( $attachment_id ) ) {
                                set_post_thumbnail( $post_id, $attachment_id );
                            }
                        }
                        // Ekstra resim HTML kodunu ekleme (varsa)
                        if ( ! empty( $image_html ) ) {
                            $post_content .= "\n" . $image_html;
                            wp_update_post( array(
                                'ID'           => $post_id,
                                'post_content' => $post_content
                            ) );
                        }
                        // Yazı içeriğinden otomatik etiket oluşturma (cümle başları hariç)
                        $tags = $this->extract_tags_from_content( $description . ' ' . $content );
                        if ( ! empty( $tags ) ) {
                            wp_set_post_tags( $post_id, $tags );
                        }
                        $new_post_added = true;
                        break 2; // Bir yeni haber eklendiğinde döngüden çıkıyoruz.
                    }
                }
            }
            // --- RSS entry yapısı ---
            elseif ( $tag === 'entry' && isset( $rss_feed->entry ) ) {
                foreach ( $rss_feed->entry as $entry ) {
                    $title = (string) $entry->title;
                    if ( post_exists( $title ) ) {
                        continue;
                    }
                    $link = '';
                    if ( isset( $entry->link ) ) {
                        foreach ( $entry->link as $l ) {
                            $attributes = $l->attributes();
                            if ( isset( $attributes['rel'] ) && (string) $attributes['rel'] === 'alternate' ) {
                                $link = (string) $attributes['href'];
                                break;
                            }
                        }
                        if ( empty( $link ) ) {
                            $link = (string) $entry->link;
                        }
                    }
                    $description = isset( $entry->summary ) ? (string) strip_tags( $entry->summary ) : '';
                    $content     = isset( $entry->content ) ? (string) strip_tags( $entry->content ) : '';
                    $image_url   = '';

                    if ( empty( $image_url ) ) {
                        $combined_text = $description . ' ' . $content;
                        if ( preg_match( '/https?:\/\/[^\s"\']+\.(png|jpg|wrp)/i', $combined_text, $matches ) ) {
                            $image_url = $matches[0];
                        }
                    }

                    if ( empty( $title ) || ( empty( $content ) && empty( $description ) ) ) {
                        continue;
                    }

                    $post_content = '<p>' . esc_html( $description ) . '</p><p>' . esc_html( $content ) . '</p>';
                    if ( $add_link ) {
                        $post_content .= '<p><a href="' . esc_url( $link ) . '">Kaynak</a></p>';
                    }
                    $category_ids = array();
                    if ( ! empty( $categories_str ) ) {
                        $categories = array_map( 'trim', explode( ',', $categories_str ) );
                        foreach ( $categories as $cat_name ) {
                            $cat_id = get_cat_ID( $cat_name );
                            if ( ! $cat_id ) {
                                $cat_id = wp_create_category( $cat_name );
                            }
                            $category_ids[] = $cat_id;
                        }
                    }
                    $post_id = wp_insert_post( array(
                        'post_title'    => wp_strip_all_tags( $title ),
                        'post_content'  => $post_content,
                        'post_status'   => 'publish',
                        'post_author'   => 1,
                        'post_category' => $category_ids,
                        'post_type'     => 'post'
                    ) );
                    if ( ! is_wp_error( $post_id ) ) {
                        if ( ! empty( $image_url ) ) {
                            require_once( ABSPATH . 'wp-admin/includes/media.php' );
                            require_once( ABSPATH . 'wp-admin/includes/file.php' );
                            require_once( ABSPATH . 'wp-admin/includes/image.php' );
                            $attachment_id = media_sideload_image( $image_url, $post_id, $title, 'id' );
                            if ( ! is_wp_error( $attachment_id ) ) {
                                set_post_thumbnail( $post_id, $attachment_id );
                            }
                        }
                        // Otomatik etiket oluşturma
                        $tags = $this->extract_tags_from_content( $description . ' ' . $content );
                        if ( ! empty( $tags ) ) {
                            wp_set_post_tags( $post_id, $tags );
                        }
                        $new_post_added = true;
                        break 2;
                    }
                }
            }
        }
        return $new_post_added;
    }

    /**
     * Yazı içeriğinden, cümle başları hariç, ilk kelimeyi atlayarak
     * büyük harfli (ilk harfi büyük) kelimelerin frekansını hesaplar ve
     * en çok geçen 5 kelimeyi etiket olarak döndürür.
     */
    private function extract_tags_from_content( $content ) {
        // Cümleleri nokta, soru veya ünlem işaretinden sonra ayır.
        $sentences = preg_split( '/(?<=[.?!])\s+/', $content, -1, PREG_SPLIT_NO_EMPTY );
        $words = array();
        foreach ( $sentences as $sentence ) {
            // Her cümleyi kelimelere böl; cümledeki ilk kelimeyi atla
            $sentence_words = preg_split( '/\s+/', $sentence, -1, PREG_SPLIT_NO_EMPTY );
            if ( count( $sentence_words ) > 1 ) {
                for ( $i = 1; $i < count( $sentence_words ); $i++ ) {
                    $words[] = $sentence_words[$i];
                }
            }
        }
        $filtered = array();
        // Sadece ilk harfi büyük ve sonrasında küçük harfler içeren kelimeleri filtrele
        foreach ( $words as $word ) {
            $clean = trim( $word, ".,!?()[]{}\"'" );
            // Eğer kelime uzunluğu 2'den büyükse ve ilk harfi büyük ise
            if ( strlen( $clean ) > 2 && ctype_upper( substr( $clean, 0, 1 ) ) ) {
                $filtered[] = $clean;
            }
        }
        // Kelimeleri küçük harfe çevirerek frekans hesapla
        $freq = array();
        foreach ( $filtered as $w ) {
            $key = strtolower( $w );
            if ( isset( $freq[ $key ] ) ) {
                $freq[ $key ]++;
            } else {
                $freq[ $key ] = 1;
            }
        }
        // En çok geçenleri sıralayalım
        arsort( $freq );
        // En çok geçen 5 kelimeyi al
        $top_tags = array_slice( array_keys( $freq ), 0, 5 );
        return $top_tags;
    }
}

new Genel_RSS_Haber_Scraper();
muratca61
Site Admin
Mesajlar: 35964
Kayıt: Cmt Ara 21, 2024 7:56 am

Re: genel rss ekleme uygulaması wordpress

Mesaj gönderen muratca61 »

son çalışan kod

Kod:Tümünü seç

<?php
/*
Plugin Name: Genel RSS Haber Scraper
Description: Excel benzeri tablo üzerinden RSS kaynaklarını ekleyip, RSS haberlerini çekmenize olanak tanır. Ayarlarda; RSS adresi, kategoriler, RSS haber etiket kodu, link eklenip eklenmeyeceği, resim HTML kodu ve bağlantı kontrolü yapabilirsiniz. Ayrıca, yazı içeriğinden cümle başları hariç büyük harfli olan ve en çok geçen kelimelerden otomatik 5 etiket oluşturur. Görsel URL’leri için <img src="..."> içindeki .jpg gibi URL’lerde, query string kısmı hariç çekilir.
Version: 1.0
Author: Örnek Geliştirici
License: GPL2
*/

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Genel_RSS_Haber_Scraper {
    private $option_name = 'genel_rss_haber_scraper_sources';

    public function __construct() {
        add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        add_action( 'wp_ajax_genel_rss_scrape', array( $this, 'handle_scrape_request' ) );
        add_action( 'wp_ajax_genel_rss_connection_check', array( $this, 'handle_connection_check' ) );
        add_action( 'init', array( $this, 'fetch_news_on_page_load' ) );

        add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
        add_action( 'wp_enqueue_scripts', array( $this, 'frontend_enqueue_scripts' ) );
    }

    public function add_admin_menu() {
        add_menu_page(
            'Genel RSS Haber Scraper',
            'RSS Haber Scraper',
            'manage_options',
            'genel-rss-haber-scraper',
            array( $this, 'admin_page' ),
            'dashicons-rss',
            20
        );
    }

    public function register_settings() {
        register_setting( 'genel_rss_haber_scraper_options', $this->option_name );
    }

    public function admin_enqueue_scripts( $hook ) {
        if ( $hook == 'toplevel_page_genel-rss-haber-scraper' ) {
            wp_enqueue_script(
                'genel-rss-admin',
                plugin_dir_url( __FILE__ ) . 'js/genel-rss-admin.js',
                array( 'jquery' ),
                '1.0',
                true
            );
            wp_localize_script( 'genel-rss-admin', 'genelRssAdmin', array(
                'ajax_url' => admin_url( 'admin-ajax.php' )
            ) );
        }
    }

    public function frontend_enqueue_scripts() {
        wp_enqueue_script(
            'genel-rss-frontend',
            plugin_dir_url( __FILE__ ) . 'js/genel-rss-frontend.js',
            array( 'jquery' ),
            '1.0',
            true
        );
        wp_localize_script( 'genel-rss-frontend', 'genelRssAjax', array(
            'ajax_url' => admin_url( 'admin-ajax.php' )
        ) );
    }

    public function admin_page() {
        // Kayıtlı RSS kaynaklarını alıyoruz
        $sources = get_option( $this->option_name, array() );
        ?>
        <div class="wrap">
            <h1>Genel RSS Haber Scraper</h1>
            <form method="post" action="options.php">
                <?php settings_fields( 'genel_rss_haber_scraper_options' ); ?>
                <table class="widefat" id="rss-sources-table">
                    <thead>
                        <tr>
                            <th>RSS Adresi</th>
                            <th>Kategoriler (virgülle ayrılmış)</th>
                            <th>RSS Haber Etiket</th>
                            <th>Link Eklensin mi?</th>
                            <th>Resim HTML Kodu</th>
                            <th>Bağlantı Kontrol</th>
                            <th>İşlem</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        if ( ! empty( $sources ) ) {
                            foreach ( $sources as $index => $source ) {
                                $rss_url    = isset( $source['rss_url'] ) ? $source['rss_url'] : '';
                                $categories = isset( $source['categories'] ) ? $source['categories'] : '';
                                $tag        = isset( $source['tag'] ) ? $source['tag'] : '';
                                $add_link   = isset( $source['add_link'] ) ? $source['add_link'] : '';
                                $image_html = isset( $source['image_html'] ) ? $source['image_html'] : '';
                                ?>
                                <tr>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][rss_url]" value="<?php echo esc_attr( $rss_url ); ?>" size="40" />
                                    </td>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][categories]" value="<?php echo esc_attr( $categories ); ?>" size="30" placeholder="Kategori1,Kategori2" />
                                    </td>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][tag]" value="<?php echo esc_attr( $tag ); ?>" size="10" placeholder="item veya entry" />
                                    </td>
                                    <td>
                                        <input type="checkbox" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][add_link]" value="1" <?php checked( $add_link, 1 ); ?> />
                                    </td>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][image_html]" value="<?php echo esc_attr( $image_html ); ?>" size="30" placeholder="<img src='...' />" />
                                    </td>
                                    <td>
                                        <button class="button connection-check" data-row-index="<?php echo $index; ?>">Bağlantıyı Kontrol Et</button>
                                        <span class="connection-result" id="conn-result-<?php echo $index; ?>"></span>
                                    </td>
                                    <td>
                                        <button class="button remove-row">Kaldır</button>
                                    </td>
                                </tr>
                                <?php
                            }
                        }
                        ?>
                    </tbody>
                </table>
                <p>
                    <button type="button" class="button" id="add-row">Yeni Satır Ekle</button>
                </p>
                <?php submit_button(); ?>
            </form>
            <hr>
            <h2>Manuel Haber Çekme</h2>
            <p>RSS haberlerini çekmek için aşağıdaki butona tıklayın.</p>
            <button id="fetch-rss-news" class="button button-primary">Haberleri Çek</button>
            <div id="rss-news-log" style="margin-top:20px;padding:10px;background:#f9f9f9;border:1px solid #ddd;max-height:300px;overflow-y:auto;"></div>
            <script>
            jQuery(document).ready(function($) {
                $('#fetch-rss-news').on('click', function() {
                    let log = $('#rss-news-log');
                    log.append('<p>Haberler çekiliyor...</p>');
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: { action: 'genel_rss_scrape' },
                        success: function(response) {
                            if(response.success) {
                                log.append('<p style="color:green;">' + response.data.message + '</p>');
                            } else {
                                log.append('<p style="color:red;">' + response.data.message + '</p>');
                            }
                        },
                        error: function() {
                            log.append('<p style="color:red;">Bağlantı hatası!</p>');
                        }
                    });
                });
            });
            </script>
        </div>
        <?php
    }

    // AJAX ile manuel haber çekme işlemi
    public function handle_scrape_request() {
        $result = $this->fetch_one_news();
        if ( $result ) {
            wp_send_json_success( array( 'message' => 'Bir haber çekildi.' ) );
        } else {
            wp_send_json_error( array( 'message' => 'Yeni haber bulunamadı.' ) );
        }
    }

    // AJAX: Bağlantı kontrolü için RSS adresi ve etiket bilgisini kontrol eder
    public function handle_connection_check() {
        $rss_url = isset( $_POST['rss_url'] ) ? esc_url_raw( $_POST['rss_url'] ) : '';
        $tag     = isset( $_POST['tag'] ) ? sanitize_text_field( $_POST['tag'] ) : '';

        if ( empty( $rss_url ) || empty( $tag ) ) {
            wp_send_json_error( array( 'message' => 'RSS URL ve Etiket bilgisi gerekli.' ) );
        }

        $rss_feed = @simplexml_load_file( $rss_url );
        if ( ! $rss_feed ) {
            wp_send_json_error( array( 'message' => 'RSS beslemesi yüklenemedi.' ) );
        }

        if ( $tag === 'item' && isset( $rss_feed->channel->item ) ) {
            wp_send_json_success( array( 'message' => 'Bağlantı başarılı: <item> bulundu.' ) );
        } elseif ( $tag === 'entry' && isset( $rss_feed->entry ) ) {
            wp_send_json_success( array( 'message' => 'Bağlantı başarılı: <entry> bulundu.' ) );
        } else {
            wp_send_json_error( array( 'message' => 'Belirtilen etiket bulunamadı.' ) );
        }
    }

    // Sayfa yüklenirken (frontend) otomatik haber çekme
    public function fetch_news_on_page_load() {
        if ( ! is_admin() && ! is_feed() ) {
            $this->fetch_one_news();
        }
    }

    // RSS kaynağından haber çekme işlemi
    private function fetch_one_news() {
        require_once( ABSPATH . 'wp-admin/includes/post.php' );
        $sources = get_option( $this->option_name, array() );
        if ( empty( $sources ) ) {
            return false;
        }
        $new_post_added = false;
        foreach ( $sources as $source ) {
            $rss_url        = isset( $source['rss_url'] ) ? trim( $source['rss_url'] ) : '';
            $categories_str = isset( $source['categories'] ) ? trim( $source['categories'] ) : '';
            $tag            = isset( $source['tag'] ) ? trim( $source['tag'] ) : '';
            $add_link       = isset( $source['add_link'] ) ? $source['add_link'] : 0;
            $image_html     = isset( $source['image_html'] ) ? trim( $source['image_html'] ) : '';

            if ( empty( $rss_url ) || empty( $tag ) ) {
                continue;
            }

            $rss_feed = @simplexml_load_file( $rss_url );
            if ( ! $rss_feed ) {
                error_log( 'RSS yüklenemedi: ' . $rss_url );
                continue;
            }

            // --- RSS item yapısı ---
            if ( $tag === 'item' && isset( $rss_feed->channel->item ) ) {
                foreach ( $rss_feed->channel->item as $item ) {
                    $title = (string) $item->title;
                    // Aynı başlık varsa bu haberi çekme
                    if ( post_exists( $title ) ) {
                        continue;
                    }
                    $link        = (string) $item->link;
                    $description = (string) strip_tags( $item->description );
                    $content     = isset( $item->children( 'content', true )->encoded ) ? (string) strip_tags( $item->children( 'content', true )->encoded ) : '';
                    $image_url   = isset( $item->enclosure['url'] ) ? (string) $item->enclosure['url'] : '';

                    // Görsel enclosure yoksa, description veya content içinde arama yapalım.
                    if ( empty( $image_url ) ) {
                        $combined_text = $description . ' ' . $content;
                        // Regex: URL'nin .png, .jpg veya .wrp ile biten kısmını yakala (query string hariç)
                        if ( preg_match( '/(https?:\/\/[^\s"\']+\.(?:png|jpg|wrp))(\?[^\s"\']*)?/i', $combined_text, $matches ) ) {
                            $image_url = $matches[1];
                        }
                    }

                    if ( empty( $title ) || ( empty( $content ) && empty( $description ) ) ) {
                        continue;
                    }

                    $post_content = '<p>' . esc_html( $description ) . '</p><p>' . esc_html( $content ) . '</p>';
                    if ( $add_link ) {
                        $post_content .= '<p><a href="' . esc_url( $link ) . '">Kaynak</a></p>';
                    }
                    $category_ids = array();
                    if ( ! empty( $categories_str ) ) {
                        $categories = array_map( 'trim', explode( ',', $categories_str ) );
                        foreach ( $categories as $cat_name ) {
                            $cat_id = get_cat_ID( $cat_name );
                            if ( ! $cat_id ) {
                                $cat_id = wp_create_category( $cat_name );
                            }
                            $category_ids[] = $cat_id;
                        }
                    }
                    $post_id = wp_insert_post( array(
                        'post_title'    => wp_strip_all_tags( $title ),
                        'post_content'  => $post_content,
                        'post_status'   => 'publish',
                        'post_author'   => 1,
                        'post_category' => $category_ids,
                        'post_type'     => 'post'
                    ) );
                    if ( ! is_wp_error( $post_id ) ) {
                        // Görsel ekleme işlemi
                        if ( ! empty( $image_url ) ) {
                            require_once( ABSPATH . 'wp-admin/includes/media.php' );
                            require_once( ABSPATH . 'wp-admin/includes/file.php' );
                            require_once( ABSPATH . 'wp-admin/includes/image.php' );
                            $attachment_id = media_sideload_image( $image_url, $post_id, $title, 'id' );
                            if ( ! is_wp_error( $attachment_id ) ) {
                                set_post_thumbnail( $post_id, $attachment_id );
                            }
                        }
                        // Ekstra resim HTML kodunu ekleme (varsa)
                        if ( ! empty( $image_html ) ) {
                            $post_content .= "\n" . $image_html;
                            wp_update_post( array(
                                'ID'           => $post_id,
                                'post_content' => $post_content
                            ) );
                        }
                        // Yazı içeriğinden otomatik etiket oluşturma (cümle başları hariç)
                        $tags = $this->extract_tags_from_content( $description . ' ' . $content );
                        if ( ! empty( $tags ) ) {
                            wp_set_post_tags( $post_id, $tags );
                        }
                        $new_post_added = true;
                        break 2; // Bir yeni haber eklendiğinde döngüden çıkıyoruz.
                    }
                }
            }
            // --- RSS entry yapısı ---
            elseif ( $tag === 'entry' && isset( $rss_feed->entry ) ) {
                foreach ( $rss_feed->entry as $entry ) {
                    $title = (string) $entry->title;
                    if ( post_exists( $title ) ) {
                        continue;
                    }
                    $link = '';
                    if ( isset( $entry->link ) ) {
                        foreach ( $entry->link as $l ) {
                            $attributes = $l->attributes();
                            if ( isset( $attributes['rel'] ) && (string) $attributes['rel'] === 'alternate' ) {
                                $link = (string) $attributes['href'];
                                break;
                            }
                        }
                        if ( empty( $link ) ) {
                            $link = (string) $entry->link;
                        }
                    }
                    $description = isset( $entry->summary ) ? (string) strip_tags( $entry->summary ) : '';
                    $content     = isset( $entry->content ) ? (string) strip_tags( $entry->content ) : '';
                    $image_url   = '';

                    if ( empty( $image_url ) ) {
                        $combined_text = $description . ' ' . $content;
                        if ( preg_match( '/(https?:\/\/[^\s"\']+\.(?:png|jpg|wrp))(\?[^\s"\']*)?/i', $combined_text, $matches ) ) {
                            $image_url = $matches[1];
                        }
                    }

                    if ( empty( $title ) || ( empty( $content ) && empty( $description ) ) ) {
                        continue;
                    }

                    $post_content = '<p>' . esc_html( $description ) . '</p><p>' . esc_html( $content ) . '</p>';
                    if ( $add_link ) {
                        $post_content .= '<p><a href="' . esc_url( $link ) . '">Kaynak</a></p>';
                    }
                    $category_ids = array();
                    if ( ! empty( $categories_str ) ) {
                        $categories = array_map( 'trim', explode( ',', $categories_str ) );
                        foreach ( $categories as $cat_name ) {
                            $cat_id = get_cat_ID( $cat_name );
                            if ( ! $cat_id ) {
                                $cat_id = wp_create_category( $cat_name );
                            }
                            $category_ids[] = $cat_id;
                        }
                    }
                    $post_id = wp_insert_post( array(
                        'post_title'    => wp_strip_all_tags( $title ),
                        'post_content'  => $post_content,
                        'post_status'   => 'publish',
                        'post_author'   => 1,
                        'post_category' => $category_ids,
                        'post_type'     => 'post'
                    ) );
                    if ( ! is_wp_error( $post_id ) ) {
                        if ( ! empty( $image_url ) ) {
                            require_once( ABSPATH . 'wp-admin/includes/media.php' );
                            require_once( ABSPATH . 'wp-admin/includes/file.php' );
                            require_once( ABSPATH . 'wp-admin/includes/image.php' );
                            $attachment_id = media_sideload_image( $image_url, $post_id, $title, 'id' );
                            if ( ! is_wp_error( $attachment_id ) ) {
                                set_post_thumbnail( $post_id, $attachment_id );
                            }
                        }
                        // Otomatik etiket oluşturma
                        $tags = $this->extract_tags_from_content( $description . ' ' . $content );
                        if ( ! empty( $tags ) ) {
                            wp_set_post_tags( $post_id, $tags );
                        }
                        $new_post_added = true;
                        break 2;
                    }
                }
            }
        }
        return $new_post_added;
    }

    /**
     * Yazı içeriğinden, cümle başları hariç, ilk kelimeyi atlayarak
     * büyük harfli (ilk harfi büyük) kelimelerin frekansını hesaplar ve
     * en çok geçen 5 kelimeyi etiket olarak döndürür.
     */
    private function extract_tags_from_content( $content ) {
        // Cümleleri nokta, soru veya ünlem işaretinden sonra ayır.
        $sentences = preg_split( '/(?<=[.?!])\s+/', $content, -1, PREG_SPLIT_NO_EMPTY );
        $words = array();
        foreach ( $sentences as $sentence ) {
            // Her cümleyi kelimelere böl; cümledeki ilk kelimeyi atla
            $sentence_words = preg_split( '/\s+/', $sentence, -1, PREG_SPLIT_NO_EMPTY );
            if ( count( $sentence_words ) > 1 ) {
                for ( $i = 1; $i < count( $sentence_words ); $i++ ) {
                    $words[] = $sentence_words[$i];
                }
            }
        }
        $filtered = array();
        // Sadece ilk harfi büyük ve sonrasında küçük harfler içeren kelimeleri filtrele
        foreach ( $words as $word ) {
            $clean = trim( $word, ".,!?()[]{}\"'" );
            if ( strlen( $clean ) > 2 && ctype_upper( substr( $clean, 0, 1 ) ) ) {
                $filtered[] = $clean;
            }
        }
        // Kelimeleri küçük harfe çevirerek frekans hesapla
        $freq = array();
        foreach ( $filtered as $w ) {
            $key = strtolower( $w );
            if ( isset( $freq[ $key ] ) ) {
                $freq[ $key ]++;
            } else {
                $freq[ $key ] = 1;
            }
        }
        // En çok geçenleri sıralayalım
        arsort( $freq );
        // En çok geçen 5 kelimeyi al
        $top_tags = array_slice( array_keys( $freq ), 0, 5 );
        return $top_tags;
    }
}

new Genel_RSS_Haber_Scraper();
muratca61
Site Admin
Mesajlar: 35964
Kayıt: Cmt Ara 21, 2024 7:56 am

Re: genel rss ekleme uygulaması wordpress

Mesaj gönderen muratca61 »

bu en son çalışan ama sistemin ağırlaşmasına neden olan kod

Kod:Tümünü seç

<?php
/*
Plugin Name: Genel RSS Haber Scraper
Description: Excel benzeri tablo üzerinden RSS kaynaklarını ekleyip, RSS haberlerini çekmenize olanak tanır. Ayarlarda; RSS adresi, kategoriler, RSS haber etiket kodu, link eklenip eklenmeyeceği, resim HTML kodu ve bağlantı kontrolü yapabilirsiniz. Ayrıca, yazı içeriğinden cümle başları hariç büyük harfli olan ve en çok geçen kelimelerden otomatik 5 etiket oluşturur. Görsel URL’leri için <img src="..."> içindeki .jpg gibi URL’lerde, query string kısmı hariç çekilir.
Version: 1.0
Author: Örnek Geliştirici
License: GPL2
*/

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Genel_RSS_Haber_Scraper {
    private $option_name = 'genel_rss_haber_scraper_sources';

    public function __construct() {
        add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        add_action( 'wp_ajax_genel_rss_scrape', array( $this, 'handle_scrape_request' ) );
        add_action( 'wp_ajax_genel_rss_connection_check', array( $this, 'handle_connection_check' ) );
        add_action( 'init', array( $this, 'fetch_news_on_page_load' ) );

        add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
        add_action( 'wp_enqueue_scripts', array( $this, 'frontend_enqueue_scripts' ) );
    }

    public function add_admin_menu() {
        add_menu_page(
            'Genel RSS Haber Scraper',
            'RSS Haber Scraper',
            'manage_options',
            'genel-rss-haber-scraper',
            array( $this, 'admin_page' ),
            'dashicons-rss',
            20
        );
    }

    public function register_settings() {
        register_setting( 'genel_rss_haber_scraper_options', $this->option_name );
    }

    public function admin_enqueue_scripts( $hook ) {
        if ( $hook == 'toplevel_page_genel-rss-haber-scraper' ) {
            wp_enqueue_script(
                'genel-rss-admin',
                plugin_dir_url( __FILE__ ) . 'js/genel-rss-admin.js',
                array( 'jquery' ),
                '1.0',
                true
            );
            wp_localize_script( 'genel-rss-admin', 'genelRssAdmin', array(
                'ajax_url' => admin_url( 'admin-ajax.php' )
            ) );
        }
    }

    public function frontend_enqueue_scripts() {
        wp_enqueue_script(
            'genel-rss-frontend',
            plugin_dir_url( __FILE__ ) . 'js/genel-rss-frontend.js',
            array( 'jquery' ),
            '1.0',
            true
        );
        wp_localize_script( 'genel-rss-frontend', 'genelRssAjax', array(
            'ajax_url' => admin_url( 'admin-ajax.php' )
        ) );
    }

    public function admin_page() {
        // Kayıtlı RSS kaynaklarını alıyoruz
        $sources = get_option( $this->option_name, array() );
        ?>
        <div class="wrap">
            <h1>Genel RSS Haber Scraper</h1>
            <form method="post" action="options.php">
                <?php settings_fields( 'genel_rss_haber_scraper_options' ); ?>
                <table class="widefat" id="rss-sources-table">
                    <thead>
                        <tr>
                            <th>RSS Adresi</th>
                            <th>Kategoriler (virgülle ayrılmış)</th>
                            <th>RSS Haber Etiket</th>
                            <th>Link Eklensin mi?</th>
                            <th>Resim HTML Kodu</th>
                            <th>Bağlantı Kontrol</th>
                            <th>İşlem</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        if ( ! empty( $sources ) ) {
                            foreach ( $sources as $index => $source ) {
                                $rss_url    = isset( $source['rss_url'] ) ? $source['rss_url'] : '';
                                $categories = isset( $source['categories'] ) ? $source['categories'] : '';
                                $tag        = isset( $source['tag'] ) ? $source['tag'] : '';
                                $add_link   = isset( $source['add_link'] ) ? $source['add_link'] : '';
                                $image_html = isset( $source['image_html'] ) ? $source['image_html'] : '';
                                ?>
                                <tr>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][rss_url]" value="<?php echo esc_attr( $rss_url ); ?>" size="40" />
                                    </td>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][categories]" value="<?php echo esc_attr( $categories ); ?>" size="30" placeholder="Kategori1,Kategori2" />
                                    </td>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][tag]" value="<?php echo esc_attr( $tag ); ?>" size="10" placeholder="item veya entry" />
                                    </td>
                                    <td>
                                        <input type="checkbox" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][add_link]" value="1" <?php checked( $add_link, 1 ); ?> />
                                    </td>
                                    <td>
                                        <input type="text" name="<?php echo $this->option_name; ?>[<?php echo $index; ?>][image_html]" value="<?php echo esc_attr( $image_html ); ?>" size="30" placeholder="<img src='...' />" />
                                    </td>
                                    <td>
                                        <button class="button connection-check" data-row-index="<?php echo $index; ?>">Bağlantıyı Kontrol Et</button>
                                        <span class="connection-result" id="conn-result-<?php echo $index; ?>"></span>
                                    </td>
                                    <td>
                                        <button class="button remove-row">Kaldır</button>
                                    </td>
                                </tr>
                                <?php
                            }
                        }
                        ?>
                    </tbody>
                </table>
                <p>
                    <button type="button" class="button" id="add-row">Yeni Satır Ekle</button>
                </p>
                <?php submit_button(); ?>
            </form>
            <hr>
            <h2>Manuel Haber Çekme</h2>
            <p>RSS haberlerini çekmek için aşağıdaki butona tıklayın.</p>
            <button id="fetch-rss-news" class="button button-primary">Haberleri Çek</button>
            <div id="rss-news-log" style="margin-top:20px;padding:10px;background:#f9f9f9;border:1px solid #ddd;max-height:300px;overflow-y:auto;"></div>
            <script>
            jQuery(document).ready(function($) {
                $('#fetch-rss-news').on('click', function() {
                    let log = $('#rss-news-log');
                    log.append('<p>Haberler çekiliyor...</p>');
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: { action: 'genel_rss_scrape' },
                        success: function(response) {
                            if(response.success) {
                                log.append('<p style="color:green;">' + response.data.message + '</p>');
                            } else {
                                log.append('<p style="color:red;">' + response.data.message + '</p>');
                            }
                        },
                        error: function() {
                            log.append('<p style="color:red;">Bağlantı hatası!</p>');
                        }
                    });
                });
            });
            </script>
        </div>
        <?php
    }

    // AJAX ile manuel haber çekme işlemi
    public function handle_scrape_request() {
        $result = $this->fetch_one_news();
        if ( $result ) {
            wp_send_json_success( array( 'message' => 'Bir haber çekildi.' ) );
        } else {
            wp_send_json_error( array( 'message' => 'Yeni haber bulunamadı.' ) );
        }
    }

    // AJAX: Bağlantı kontrolü için RSS adresi ve etiket bilgisini kontrol eder
    public function handle_connection_check() {
        $rss_url = isset( $_POST['rss_url'] ) ? esc_url_raw( $_POST['rss_url'] ) : '';
        $tag     = isset( $_POST['tag'] ) ? sanitize_text_field( $_POST['tag'] ) : '';

        if ( empty( $rss_url ) || empty( $tag ) ) {
            wp_send_json_error( array( 'message' => 'RSS URL ve Etiket bilgisi gerekli.' ) );
        }

        $rss_feed = @simplexml_load_file( $rss_url );
        if ( ! $rss_feed ) {
            wp_send_json_error( array( 'message' => 'RSS beslemesi yüklenemedi.' ) );
        }

        if ( $tag === 'item' && isset( $rss_feed->channel->item ) ) {
            wp_send_json_success( array( 'message' => 'Bağlantı başarılı: <item> bulundu.' ) );
        } elseif ( $tag === 'entry' && isset( $rss_feed->entry ) ) {
            wp_send_json_success( array( 'message' => 'Bağlantı başarılı: <entry> bulundu.' ) );
        } else {
            wp_send_json_error( array( 'message' => 'Belirtilen etiket bulunamadı.' ) );
        }
    }

    // Sayfa yüklenirken (frontend) otomatik haber çekme
    public function fetch_news_on_page_load() {
        if ( ! is_admin() && ! is_feed() ) {
            $this->fetch_one_news();
        }
    }

    // RSS kaynağından haber çekme işlemi
    private function fetch_one_news() {
        require_once( ABSPATH . 'wp-admin/includes/post.php' );
        $sources = get_option( $this->option_name, array() );
        if ( empty( $sources ) ) {
            return false;
        }
        $new_post_added = false;
        foreach ( $sources as $source ) {
            $rss_url        = isset( $source['rss_url'] ) ? trim( $source['rss_url'] ) : '';
            $categories_str = isset( $source['categories'] ) ? trim( $source['categories'] ) : '';
            $tag            = isset( $source['tag'] ) ? trim( $source['tag'] ) : '';
            $add_link       = isset( $source['add_link'] ) ? $source['add_link'] : 0;
            $image_html     = isset( $source['image_html'] ) ? trim( $source['image_html'] ) : '';

            if ( empty( $rss_url ) || empty( $tag ) ) {
                continue;
            }

            $rss_feed = @simplexml_load_file( $rss_url );
            if ( ! $rss_feed ) {
                error_log( 'RSS yüklenemedi: ' . $rss_url );
                continue;
            }

            // --- RSS item yapısı ---
            if ( $tag === 'item' && isset( $rss_feed->channel->item ) ) {
                foreach ( $rss_feed->channel->item as $item ) {
                    $title = (string) $item->title;
                    // Aynı başlık varsa bu haberi çekme
                    if ( post_exists( $title ) ) {
                        continue;
                    }
                    $link        = (string) $item->link;
                    $description = (string) strip_tags( $item->description );
                    $content     = isset( $item->children( 'content', true )->encoded ) ? (string) strip_tags( $item->children( 'content', true )->encoded ) : '';
                    $image_url   = isset( $item->enclosure['url'] ) ? (string) $item->enclosure['url'] : '';

                    // Görsel enclosure yoksa, description veya content içinde arama yapalım.
                    if ( empty( $image_url ) ) {
                        $combined_text = $description . ' ' . $content;
                        // Regex: URL'nin .png, .jpg veya .wrp ile biten kısmını yakala (query string hariç)
                        if ( preg_match( '/(https?:\/\/[^\s"\']+\.(?:png|jpg|wrp))(\?[^\s"\']*)?/i', $combined_text, $matches ) ) {
                            $image_url = $matches[1];
                        }
                    }

                    if ( empty( $title ) || ( empty( $content ) && empty( $description ) ) ) {
                        continue;
                    }

                    $post_content = '<p>' . esc_html( $description ) . '</p><p>' . esc_html( $content ) . '</p>';
                    if ( $add_link ) {
                        $post_content .= '<p><a href="' . esc_url( $link ) . '" target="_blank" rel="noopener noreferrer">Kaynak</a></p>';
                    }
                    $category_ids = array();
                    if ( ! empty( $categories_str ) ) {
                        $categories = array_map( 'trim', explode( ',', $categories_str ) );
                        foreach ( $categories as $cat_name ) {
                            $cat_id = get_cat_ID( $cat_name );
                            if ( ! $cat_id ) {
                                $cat_id = wp_create_category( $cat_name );
                            }
                            $category_ids[] = $cat_id;
                        }
                    }
                    $post_id = wp_insert_post( array(
                        'post_title'    => wp_strip_all_tags( $title ),
                        'post_content'  => $post_content,
                        'post_status'   => 'publish',
                        'post_author'   => 1,
                        'post_category' => $category_ids,
                        'post_type'     => 'post'
                    ) );
                    if ( ! is_wp_error( $post_id ) ) {
                        // Görsel ekleme işlemi
                        if ( ! empty( $image_url ) ) {
                            require_once( ABSPATH . 'wp-admin/includes/media.php' );
                            require_once( ABSPATH . 'wp-admin/includes/file.php' );
                            require_once( ABSPATH . 'wp-admin/includes/image.php' );
                            $attachment_id = media_sideload_image( $image_url, $post_id, $title, 'id' );
                            if ( ! is_wp_error( $attachment_id ) ) {
                                set_post_thumbnail( $post_id, $attachment_id );
                            }
                        }
                        // Ekstra resim HTML kodunu ekleme (varsa)
                        if ( ! empty( $image_html ) ) {
                            $post_content .= "\n" . $image_html;
                            wp_update_post( array(
                                'ID'           => $post_id,
                                'post_content' => $post_content
                            ) );
                        }
                        // Yazı içeriğinden otomatik etiket oluşturma (cümle başları hariç)
                        $tags = $this->extract_tags_from_content( $description . ' ' . $content );
                        if ( ! empty( $tags ) ) {
                            wp_set_post_tags( $post_id, $tags );
                        }
                        $new_post_added = true;
                        break 2; // Bir yeni haber eklendiğinde döngüden çıkıyoruz.
                    }
                }
            }
            // --- RSS entry yapısı ---
            elseif ( $tag === 'entry' && isset( $rss_feed->entry ) ) {
                foreach ( $rss_feed->entry as $entry ) {
                    $title = (string) $entry->title;
                    if ( post_exists( $title ) ) {
                        continue;
                    }
                    $link = '';
                    if ( isset( $entry->link ) ) {
                        foreach ( $entry->link as $l ) {
                            $attributes = $l->attributes();
                            if ( isset( $attributes['rel'] ) && (string) $attributes['rel'] === 'alternate' ) {
                                $link = (string) $attributes['href'];
                                break;
                            }
                        }
                        if ( empty( $link ) ) {
                            $link = (string) $entry->link;
                        }
                    }
                    $description = isset( $entry->summary ) ? (string) strip_tags( $entry->summary ) : '';
                    $content     = isset( $entry->content ) ? (string) strip_tags( $entry->content ) : '';
                    $image_url   = '';

                    if ( empty( $image_url ) ) {
                        $combined_text = $description . ' ' . $content;
                        if ( preg_match( '/(https?:\/\/[^\s"\']+\.(?:png|jpg|wrp))(\?[^\s"\']*)?/i', $combined_text, $matches ) ) {
                            $image_url = $matches[1];
                        }
                    }

                    if ( empty( $title ) || ( empty( $content ) && empty( $description ) ) ) {
                        continue;
                    }

                    $post_content = '<p>' . esc_html( $description ) . '</p><p>' . esc_html( $content ) . '</p>';
                    if ( $add_link ) {
                        $post_content .= '<p><a href="' . esc_url( $link ) . '">Kaynak</a></p>';
                    }
                    $category_ids = array();
                    if ( ! empty( $categories_str ) ) {
                        $categories = array_map( 'trim', explode( ',', $categories_str ) );
                        foreach ( $categories as $cat_name ) {
                            $cat_id = get_cat_ID( $cat_name );
                            if ( ! $cat_id ) {
                                $cat_id = wp_create_category( $cat_name );
                            }
                            $category_ids[] = $cat_id;
                        }
                    }
                    $post_id = wp_insert_post( array(
                        'post_title'    => wp_strip_all_tags( $title ),
                        'post_content'  => $post_content,
                        'post_status'   => 'publish',
                        'post_author'   => 1,
                        'post_category' => $category_ids,
                        'post_type'     => 'post'
                    ) );
                    if ( ! is_wp_error( $post_id ) ) {
                        if ( ! empty( $image_url ) ) {
                            require_once( ABSPATH . 'wp-admin/includes/media.php' );
                            require_once( ABSPATH . 'wp-admin/includes/file.php' );
                            require_once( ABSPATH . 'wp-admin/includes/image.php' );
                            $attachment_id = media_sideload_image( $image_url, $post_id, $title, 'id' );
                            if ( ! is_wp_error( $attachment_id ) ) {
                                set_post_thumbnail( $post_id, $attachment_id );
                            }
                        }
                        // Otomatik etiket oluşturma
                        $tags = $this->extract_tags_from_content( $description . ' ' . $content );
                        if ( ! empty( $tags ) ) {
                            wp_set_post_tags( $post_id, $tags );
                        }
                        $new_post_added = true;
                        break 2;
                    }
                }
            }
        }
        return $new_post_added;
    }

    /**
     * Yazı içeriğinden, cümle başları hariç, ilk kelimeyi atlayarak
     * büyük harfli (ilk harfi büyük) kelimelerin frekansını hesaplar ve
     * en çok geçen 5 kelimeyi etiket olarak döndürür.
     */
    private function extract_tags_from_content( $content ) {
        // Cümleleri nokta, soru veya ünlem işaretinden sonra ayır.
        $sentences = preg_split( '/(?<=[.?!])\s+/', $content, -1, PREG_SPLIT_NO_EMPTY );
        $words = array();
        foreach ( $sentences as $sentence ) {
            // Her cümleyi kelimelere böl; cümledeki ilk kelimeyi atla
            $sentence_words = preg_split( '/\s+/', $sentence, -1, PREG_SPLIT_NO_EMPTY );
            if ( count( $sentence_words ) > 1 ) {
                for ( $i = 1; $i < count( $sentence_words ); $i++ ) {
                    $words[] = $sentence_words[$i];
                }
            }
        }
        $filtered = array();
        // Sadece ilk harfi büyük ve sonrasında küçük harfler içeren kelimeleri filtrele
        foreach ( $words as $word ) {
            $clean = trim( $word, ".,!?()[]{}\"'" );
            if ( strlen( $clean ) > 2 && ctype_upper( substr( $clean, 0, 1 ) ) ) {
                $filtered[] = $clean;
            }
        }
        // Kelimeleri küçük harfe çevirerek frekans hesapla
        $freq = array();
        foreach ( $filtered as $w ) {
            $key = strtolower( $w );
            if ( isset( $freq[ $key ] ) ) {
                $freq[ $key ]++;
            } else {
                $freq[ $key ] = 1;
            }
        }
        // En çok geçenleri sıralayalım
        arsort( $freq );
        // En çok geçen 5 kelimeyi al
        $top_tags = array_slice( array_keys( $freq ), 0, 5 );
        return $top_tags;
    }
}

new Genel_RSS_Haber_Scraper();
Cevapla