Wordpress预填充帖子中的内容

时间:2015-03-12 17:21:30

标签: php wordpress-plugin wordpress

我有一个管理插件,其中包含一个带有按钮的文章列表"添加到帖子"一边。点击该按钮,我想重定向到" /wp-admin/post-new.php"填写表格。

我可以在网址中设置标题wp-admin/post-new.php?post_type=post&post_title=My Titlle。但是,我怎样才能预先填写内容?

我读了一些像this这样的文章,但它不是我想要的。

此外,每次内容都会有所不同,所以我不想将其设置为默认值。

我现在在做什么:

我点击按钮上的jQuery:

function add_to_post(id) {

    var data = {
        'action'    : 'add_to_post',
        'id'    : id
    };

    $.ajax({
        type    : 'POST',
        url     : ajaxurl,
        data    : data
    })
    .done(function(){

        var title   = $(document.getElementById('title_'+id)).text(); 
        var link    = host+"/wp-admin/post-new.php?post_type=post&post_title="+title;
        window.open(link,"_blank");
    })
    ;
}

我的动作插件代码

add_action('wp_ajax_add_to_post','add_to_post_callback');

function add_to_post_callback() {

    add_filter( 'default_content', 'my_editor_content', 10 , 2 );

    wp_die();
}

function my_editor_content( $content ) {

    $content = "This is some custom content I'm adding to the post editor because I hate re-typing it.";

    return $content;
}

但是当我点击"添加到帖子"按钮,内容仍为空 我将不胜感激任何帮助。

阿曼。

2 个答案:

答案 0 :(得分:2)

WordPress有一个默认内容的过滤器:

add_filter( 'default_content', 'set_default_content', 10, 2 );
function set_default_content( $content, $post ) {
    $content = ...your content...;
    return $content;
}

您可以只为内容使用变量,并随时更改。

答案 1 :(得分:0)

这就是我最终做的事情:

在jQuery中:

function add_to_post(feed_id) {

    var title   = $(document.getElementById('title_'+feed_id)).text(); 
    var content = $(document.getElementById('summary_'+feed_id)).text(); 
    var link    = host+"/wp-admin/post-new.php";

    var data = {
        'post_title'    : title,
        'pre_content'   : content,
        'post_type'     : 'post'
    };

    $.extend({
        redirectPost: function(location, args) {
            var form = '';
            $.each( args, function( key, value ) {
                form += '<input type="hidden" name="'+key+'" value="'+value+'">';
            });
            $('<form target = "_blank" action="'+location+'" method="POST">'+form+'</form>').appendTo('body').submit();
        }
    });
    // sending content as post because Get request has character limit of 2048. Just taking no chances.
    $.redirectPost(link,data);
}

在PHP中

//To add content to your post.
add_filter( 'default_content', 'my_editor_content', 10 , 2 );

function my_editor_content( $content , $post ) {

    if(isset($_POST['pre_content'])) {
        $content = $_POST['pre_content'];
    }

    return $content;
}