【问题标题】:Parse XML into Wordpress WYSIWYG editor ONLY for Posts仅将 XML 解析为 Wordpress 所见即所得编辑器
【发布时间】:2017-10-22 17:08:15
【问题描述】:

我遇到了一个希望可以解决的小情况。我的目标是从服务器获取现有的 XML 文件,对其进行解析,然后将其作为列表注入到 Wordpress 的原始 WYSIWYG 编辑器中,以便网站所有者在撰写新帖子时可以随时使用该列表。现在,我的 wp-admin/edit-form-advanced.php 文件中有这段代码:

/**
 * Fires after the title field.
 *
 * @since 3.5.0
 *
 * @param WP_Post $post Post object.
 */
do_action( 'edit_form_after_title', $post );

if ( post_type_supports($post_type, 'editor') ) {
?>
<div id="postdivrich" class="postarea<?php if ( $_wp_editor_expand ) { echo ' wp-editor-expand'; } ?>">
<?php

/** LOAD XML FROM SERVER AND PARSE AS UL INTO EACH NEW WP POST **/
    $xml = simplexml_load_file('../my-folder/file.xml');

    $product = "<br/><br/><h2 style='text-align:center; color:#003300;'><u>Products Available Now</u></h2><br/><ul style='text-align:center; list-style:none; color:#003300;'>";
    foreach( $xml as $value ) {
          $product .= "<li>";
          $product .= $value->Description .= " $";
          $product .= $value->Price .= " / ";
          $product .= $value->QtyUnit .= "\n";
          $product .= "</li>";
         };
?>


<?php wp_editor($product, 'content', array(
    '_content_editor_dfw' => $_content_editor_dfw,
    'drag_drop_upload' => true,
    'tabfocus_elements' => 'content-html,save-post',
    'editor_height' => 300,
    'tinymce' => array(
        'resize' => false,
        'wp_autoresize_on' => $_wp_editor_expand,
        'add_unload_trigger' => false,
    ),
) ); ?>

虽然它有效,但这会导致几个问题。

1) 它将数据注入到每个所见即所得编辑器中,包括我想避免的页面。如果可能,内容应该只出现在帖子编辑器中。

2) 它会导致一个非常严重的错误,只要重新加载特定的管理页面,就会删除列表以外的任何内容。我无法保存任何草稿,也无法编辑帖子或页面,除非我在编辑过程中保持该会话在浏览器中打开。

不确定是否可以解决这些问题,但衷心感谢任何和所有帮助!

【问题讨论】:

    标签: php xml wordpress wysiwyg wp-admin


    【解决方案1】:

    你应该never modify WP core files。建议您update or restore原始文件。

    这个小插件可以实现你所需要的:

    <?php
    /**
     * Plugin Name: Default Post Content
     */
    
    add_action( 'load-post-new.php', 'new_post_so_44123076' );
    
    function new_post_so_44123076() {
        # Only load if post type not defined (only occurs for Posts)
        if( isset($_GET['post_type']) ) 
            return;
        add_filter( 'default_content', 'default_content_so_44123076' );  
    }
    function default_content_so_44123076( $content ) {
        # Build your own custom content
        $content = "My html content.";
        return $content;
    }
    

    为插件创建一个文件夹,将代码放入文件 (custom-content.php) 并将 XML 放在同一文件夹中。

    可以这样检索:

    $xml = plugins_url( '/file.xml', __FILE__ );
    

    【讨论】:

    • 效果很好,非常感谢!我恢复了原始文件并个性化了插件代码。指定 XML 文件的绝对路径,因为它需要位于服务器上的特定文件夹中。非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多