如何阻止wp_insert_post插入相同的帖子三次?

时间:2018-05-03 11:03:23

标签: wordpress

我使用了一个cron作业来触发一个从RSS提要URL每小时插入一个帖子的函数,但我的问题是它在三次前插入了同一个帖子。我做了所有必要的检查,看看是否在插入之前存在帖子,但仍然是同样的问题,它一次插入三个帖子。当我在实时Web服务器上时,问题发生在本地它工作正常。但是在我用来检查插入之前是否存在帖子的所有方法(自定义查询,相同的WordPress函数)中,WordPress函数post_exists()根本不起作用。那么任何人都可以帮我解决这个问题吗?

add_action('hourly', 'do_this_hourly'); // Cron Job

function do_this_hourly() {

    $feedUrl = www.example.com/rss;

    // Get RSS Feed(s)
    include_once( ABSPATH . WPINC . '/feed.php' );

    add_filter( 'wp_feed_cache_transient_lifetime' , 'filter_to_cache' ); // Filter cache
    // Get a SimplePie feed object from the specified feed source.  
    $rss = fetch_feed($feedUrl);
    remove_filter( 'wp_feed_cache_transient_lifetime' , 'filter_to_cache' ); // Filter cache

    $maxitems = 0;

    if ( ! is_wp_error( $rss ) ) : // Checks that the object is created correctly

     // Figure out how many total items there are, but limit it to 100. 
       $maxitems = $rss->get_item_quantity( 20 ); 

     // Build an array of all the items, starting with element 0 (first element).
     $rss_items = $rss->get_items( 0, $maxitems );

    endif;


    if ( $maxitems != 0 ) : 

        // Loop through each feed item and insert as post. 
        foreach ( $rss_items as $item ) : 

                     $tit = wp_specialchars_decode(wp_strip_all_tags($item->get_title()), ENT_QUOTES);
                     $des = wp_specialchars_decode(wp_strip_all_tags($item->get_description()), ENT_QUOTES);
                     $lin = $item->get_permalink();
                     $cate = 3;
                     $title_chec = get_page_by_title( $tit, OBJECT, 'post' );

                     if ($title_chec == NULL) :

                            $the_article = array (
                                    'post_title'     => $tit,
                                    'post_content'   => $des,
                                    'post_status'    => 'publish',
                                    'post_author'    => 1,
                                    'post_category'  => array($cate),
                                    'meta_input'     => array (
                                             'source_url'   =>  $lin
                                     )
                            );

                            $new_post = wp_insert_post( $the_article ); //Post the post now.

                     endif; // Insert poat only if it doesn't exist 

        endforeach;
   endif; 

}

0 个答案:

没有答案