仅来自XML提要的WP_INSERT_POST插入第一篇帖子

时间:2021-02-17 作者:Pbalazs89

我的目标是从WordPress安装中的文件夹导入所有XML文件(/data/*.XML)

为了实现这一点,我在函数中添加了action。php:

/**
 * Show \'insert posts\' button on backend
 */
add_action( "admin_notices", function() {
    echo "<div class=\'updated\'>";
    echo "<p>";
    echo "To insert the posts into the database, click the button to the right.";
    echo "<a class=\'button button-primary\' style=\'margin:0.25em 1em\' href=\'{$_SERVER["REQUEST_URI"]}&insert_mti_posts\'>Insert Posts</a>";
    echo "</p>";
    echo "</div>";
});
这是我的代码:

/**
 * Create and insert posts from CSV files
 */
add_action( "admin_init", function() {
    global $wpdb;

    // I\'d recommend replacing this with your own code to make sure
    //  the post creation _only_ happens when you want it to.
    if ( ! isset( $_GET["insert_mti_posts"] ) ) {
        return;
    }

    // Change these to whatever you set
    $getposttype = array(
        "custom-post-type" => "cikkek"
    );

    // Get the data from all those XMLs!
    $posts = function() {
        $xmlfiles =  glob( __DIR__ . "/data/*.xml" );
        $data = array();
        $errors = array();

        // Get array of XML files
        foreach ( $xmlfiles as $key=>$xmlfile ) {
            
            $xml = simplexml_load_file($xmlfile);
            $xmldata = json_decode(json_encode($xml), true);
    
            $posttitle = $xmldata[\'THIR\'][\'CIM\'];
            $postlead =  $xmldata[\'THIR\'][\'LEAD\'];
            $postcontent =  $xmldata[\'THIR\'][\'HIRSZOVEG\'];
            
            $data = array(
    
                $key => array(
                
               "title" =>       $posttitle,
               "description" => $postlead,
               "content" =>     $postcontent
                )
                
            );

            $data[] = $post;
    
                };

        if ( ! empty( $errors ) ) {
            // ... do stuff with the errors
        }

        return $data;
        
    };


    // Simple check to see if the current post exists within the
    //  database. This isn\'t very efficient, but it works.
    $post_exists = function( $title ) use ( $wpdb, $getposttype ) {

    // Get an array of all posts within our custom post type
    $posts = $wpdb->get_col( "SELECT post_title FROM {$wpdb->posts} WHERE post_type = \'{$getposttype["custom-post-type"]}\'" );

    // Check if the passed title exists in array
    return in_array( $title, $posts );
    };

    foreach ( $posts() as $post ) {

        // If the post exists, skip this post and go to the next one
        if ( $post_exists( $post["title"] ) ) {
            continue;
        }

        // Insert the post into the database
        $post["id"] = wp_insert_post( array(
            "post_title" => $post["title"],
            "post_content" => $post["content"],
            "post_type" => $getposttype["custom-post-type"],
            "post_status" => "draft"
        ));

    }

});

Issue 1:

代码是可行的,但它only inserts the first .XML 进入WordPress数据库。我不明白为什么,因为我遍历了所有这些文件并发回了一个数组。

Issue 2: 代码检查给定XML的标题并将其与数据库匹配->;如果内容相同,则不应添加。不幸的是,确实如此。

Issue 3: 我认为这是因为admin\\u init操作,但不幸的是,每次我刷新admin时,导入都会运行。我只希望它运行,如果我在管理中单击插入帖子按钮。有没有其他更适合这个的钩子?

2 个回复
SO网友:Tom J Nowell

You 一re do我ng级 t型h类我s t型o 一dd post型s t型o t型h类e $d一t型一 一rr一y:

&#x个A.;
$d一t型一 = ...&#x个A.;
&#x个A.;

Th类我s 我s not型 h类ow you 一dd som级et型h类我ng级 t型o 一n 一rr一y. You w一nt型 t型o 一ppend, not型 一ss我g级n.

&#x个A.;

Th类我nk of 我t型 l我ke wr我t型我ng级 一 l我st型 of 5. t型h类我ng级s, wh类ere for e一ch类 我t型em级 you t型h类row t型h类e l我st型 我n t型h类e t型r一sh类, g级et型 一 new p我ece of p一per, 一nd wr我t型e t型h类e 我t型em级 一t型 t型h类e t型op. A.t型 t型h类e end you w我ll h类一ve 一 l我st型 w我t型h类 only t型h类e l一st型 我t型em级.

&#x个A.;&#x个A.;

A.s 一n 一s我de, you\'ve 一sked sever一l quest型我ons 一bout型 t型h类我s code, but型 h类一ve not型 ref一ct型ored 我t型, even t型h类oug级h类 我t型 我s st型ruct型ured 我n 一 very com级pl我c一t型ed w一y.

&#x个A.;

我nst型e一d, 我t型 would be m级uch类 e一s我er 一nd f一st型er t型o rewr我t型e 我t型 l我ke t型h类我s:

&#x个A.;
f我les = x个m级l f我les 我n folder&#x个A.;fore一ch类 f我le&#x个A.;    x个m级lf我le = lo一d t型h类e 十、ML f我le&#x个A.;    我f t型h类e post型 does not型 ex个我st型&#x个A.;        wp_我nsert型_post型( [ .... st型uff from级 t型h类e 十、ML f我le ... ] )&#x个A.;
&#x个A.;

我nst型e一d of wh类一t型 you h类一ve r我g级h类t型 now:

&#x个A.;
d一t型一 = em级pt型y 一rr一y&#x个A.;g级et型 x个m级l f我les funct型我on &#x个A.;    f我les = x个m级l f我les 我n folder&#x个A.;    fore一ch类 f我le&#x个A.;        x个m级lf我le = lo一d t型h类e 十、ML f我le&#x个A.;        一dd t型h类e det型一我ls t型o 一n 一rr一y&#x个A.;        一dd t型h类一t型 一rr一y t型o d一t型一&#x个A.;c一ll t型h类e g级et型 x个m级l f我les funct型我on 一nd for e一ch类 t型h类我ng级 我n t型h类e 一rr一y 我t型 ret型urns&#x个A.;    我f t型h类e post型 does not型 ex个我st型&#x个A.;        c一ll wp_我nsert型_post型 w我t型h类 t型h类e det型一我ls&#x个A.;
&#x个A.;

SO网友:Pbalazs89

谢谢大家的帮助。我可以这样解决它:

在我添加的原始代码中,data[]变量没有用post数据填充。

部分原因是语法错误(例如,循环返回错误的数据时,不需要key)。

此外,XML返回了额外的空间,因此需要添加一些正则表达式,这在json变量中得到了处理。

一旦数据[]变量正确地填充了XML帖子,导入工作就完美无缺了。

/**
 * Show insert posts button on backend
 */
add_action( "admin_notices", function() {
    echo "<div class=\'updated\'>";
    echo "<p>";
    echo "To insert the posts into the database, click the button to the right.";
    echo "<a class=\'button button-primary\' style=\'margin:0.25em 1em\' href=\'{$_SERVER["REQUEST_URI"]}&insert_sitepoint_posts\'>Insert Posts</a>";
    echo "</p>";
    echo "</div>";
});

/**
 * Create and insert posts from CSV files
 */
add_action( "admin_init", function() {
    global $wpdb;

    // I\'d recommend replacing this with your own code to make sure
    //  the post creation _only_ happens when you want it to.
    if ( ! isset( $_GET["insert_sitepoint_posts"] ) ) {
        return;
    }

    // Change these to whatever you set
    $sitepoint = array(

        "custom-post-type" => "cikkek"
    );

    $posts = function() {
        $xmlfiles =  glob( __DIR__ . "/data/*.xml" );
        $data = array();
        $errors = array();

        // Get array of XML files
        foreach ( $xmlfiles as $key=>$xmlfile ) {
            
            $xml = simplexml_load_file($xmlfile);
            $json = preg_replace("/^\\s+/", "", json_encode($xml));

        
            $xmldata = json_decode($json, true);
    
            $posttitle = $xmldata[\'THIR\'][\'CIM\'];
            $postlead =  $xmldata[\'THIR\'][\'LEAD\'];
            $postcontent =  $xmldata[\'THIR\'][\'HIRSZOVEG\'];


            $post = array(

                "title" =>       $posttitle,
                "description" => $postlead,
                "content" =>     $postcontent
                
                );

             array_push($data, $post);
    
                };

        if ( ! empty( $errors ) ) {
            // ... do stuff with the errors
        }

        return $data;
        
    };

    // Simple check to see if the current post exists within the
    //  database. This isn\'t very efficient, but it works.
    $post_exists = function( $title ) use ( $wpdb, $sitepoint ) {

        // Get an array of all posts within our custom post type
        $posts = $wpdb->get_col( "SELECT post_title FROM {$wpdb->posts} WHERE post_type = \'{$sitepoint["custom-post-type"]}\'" );

        // Check if the passed title exists in array
        return in_array( $title, $posts );
    };

    foreach ( $posts() as $post ) {

        // If the post exists, skip this post and go to the next one
        if ( $post_exists( $post["title"] ) ) {
            continue;
        }

        // Insert the post into the database
        $post["id"] = wp_insert_post( array(
            "post_title" => $post["title"],
            "post_content" => $post["content"],
            "post_type" => $sitepoint["custom-post-type"],
            "post_status" => "draft"
        ));

        
    }

});

相关推荐

是否从带有ACF字段的CPT发布XML提要?

他们正在为一家招聘机构开发一个网站,并希望将他们的工作公告板与事实同步。通过与代表聊天,他们说我们需要以以下格式向提供XML提要:https://www.indeed.com/intl/en/xmlinfo.html假设我要创建一个自定义的post类型,并为每个XML节点创建一个ACF字段,那么如何将该post类型中的所有post转换为XML字段呢?