Create post on a wordpress and bring in other wordpress automatically

Asked

Viewed 1,759 times

5

Options:

  • Create a new POST on a wordpress-1, from another wordpress-2.

or

  • Everything that is created in wordpress-2 be "copied" to wordpress-1

or

  • Create/Register a product in a store(site)-1, from another store(site)-2. [RESOLVED]

I’ve used multsite integrated with Threewp-Broadcast, but it has strange bugs, such as automatically dislodging from admin when changing Dashboard.

[UPDATE] Using the same bank, changing there in wp-config, does not work! Yeah wordpress works with permanent links and will bring a fixed URL and in case, I should not access the site 1 through the site 2, but only should have the same post!

  • managed to solve this problem? I was curious

  • No, @Caiofelipepereira, but I’ll look at your answer. I just saw.

  • 1

    Are you talking about Multisite or two independent WP?

  • WP independent.

3 answers

4

Doing this automatically seems a little complicated, but I think it’s possible. The solution I’m going to suggest has not been tested but, in theory, I think it should work. I’ll call w1 the Wordpress in which you want to create the post, and w2the Wordpress that will receive the posts, as soon as they are created in the first.

  1. Maintain integrity between the two sites

    This I believe should be the zero step, but anyway. If you have some kind of customization in the posts w1, as meta data, custom fields and stuff like, and there’s no at least the same structure in the w2, the post you are looking to duplicate will not be duplicated 100% correctly. Therefore, ensure that w2 has at least all properties defined by you in w1.

  2. Create a action hook for the publication of w1

    The WP has a number of actions predefined, and attaching some extra functionality to them is taken as the creation of a hook. A action that we will use is the publish_post. Of Codex:

    publish_post is an action Triggered Whenever a post is Published, or if it is edited and the status is changed to Publish.

    That is, every time you publish a post, something (that you define) is going to happen. In terms of code, this is the skeleton that you put on functions.php:

    add_action('publish_post', 'replicar_post_em_w2');
    function replicar_post_em_w2(){
        # code...
    }
    

    Basically, replicar_posts_em_w2() will be called at the time of publication. I return to this method soon.

  3. Create a post insertion interface in w2

    There is more than one way you can do this, but one that I particularly like is by using the plugin JSON API (From that point on, my entire response is based on this plugin). It provides query methods - which return a JSON based on a URL and in its parameters - and also post creation methods (which interests us), which basically works in the same way. You call a URL of the kind http://w2.com/api/create_post/?nonce=123abc&content=blablabla, and it creates the post for you. Speaking specifically of this plugin, there is a method called get_nonce() that should be used to generate the nonce, which is a necessary parameter for the method create_post(). Read about the plugin details here.

  4. Call, inside the action hook, its method of insertion in w2

    Now that you have (or should have) ready, and tested, the post insertion structure in w2, It’s time to build the replication method itself. How you will work with a post, you must provide it as parameter for this method. Inside it, you will extract what you need from the post you just created in w1, mount a query string using this method, and call to URL of insertion of w2 to complete the process. In a very simple way, your code would be:

    function replicar_post_em_w2($post){
        $url_de_insercao = 'http://w2.com/api/create_post/?';
    
        $titulo = $post->title;
        $couteudo = $post->content;
        $nonce = '123abc'; 
        #... E por aí vai
    
        $query_params = array(
            'nonce' => $nonce,
            'title' => $title,
            'content' => $conteudo
        );
    
        $url_de_insercao .= http_build_query($query_params);
    
        $ch = curl_init();
    
        curl_setopt($ch, CURLOPT_URL, $url_de_insercao);
        curl_setopt($ch, CURLOPT_HEADER, 0);
    
        curl_exec($ch);
    
        curl_close($ch);
    
    }
    

    Note that I used cURL to call the insertion method in w2. Note also that the value of nonce was arbitrary. You can use the cURL to make the request in w2 to get the correct value. The list of parameters of all the plugin methods is found in documentation.

    Finally, as now your method receives a parameter, you have to change the add_action for:

    add_action('publish_post', 'replicar_post_em_w2', 10, 1);
    

    Where 10 is the priority, and 1 is the number of arguments of replicar_post_em_w2.

I believe that if you follow these steps, you will reach your goal. Of course you will have a good debug job ahead, and the insertion of the posts can be kind of boring, mainly on account of nonce. The construction of query can be a bit complex too, and if you are working with custom posts, maybe the insertion gets a little complicated. Anyway, that’s the theory. I hope I’ve helped.

3

According to (great) Frank Bueltge, there are three methods to do this:

  1. WP API (JSON)
  2. Feed (XML)
  3. XMLRPC API

And, also according to Bueltge, we should prioritize the WP JSON API because it is the most modern way and is about to be incorporated into the basic code of Wordpress. However, my answer is via XMLRPC, a classic WP method (to make trackbacks and pingbacks, publish from web or desktop apps), and that normally is recommended disable because it opens the door to several attempts of attack [see "safety" at the end].

Remarks:

  • this code is only a proof of concept; the source post is reproduced on the destination site, but this information is not stored on the source site;

  • a complete code would have to store the "mirror" post ID on the source site. And, when called again, instead of creating a new post again, would have to update the post "mirror" that was created first and whose ID we store as add_post_meta by making the reproduction;

  • the target site returns the ID of the mirror post that was created, so the above functionality is not too difficult, a little jQuery and AJAX are needed.

Destination Plugin

Installed on the site that will receive the duplicate post.

<?php
/**
 * Plugin Name: (SOpt) Plugin de Destino
 * Description: Publicações DE outro site
 * Plugin URI: /questions/66280
 * Version: 1.0
 * Author: brasofilo 
 */

add_filter( 'xmlrpc_methods', 'xmlrpc_sopt_66280' );

function xmlrpc_sopt_66280( $methods ) {
    /* BLOQUEIO DE TODOS OS MÉTODOS, remova a seguinte linha para habilitar todos os métodos padão do WP */
    $methods = array();
    $methods['postFromOutside'] = 'outside_sopt_66280';
    return $methods;
}

function outside_sopt_66280( $args ) {
    // A ordem dos argumentos é importante!
    $username   = $args[0];
    $password   = $args[1];
    $data = $args[2];  
    global $wp_xmlrpc_server;

    // Usuário correto?
    if ( !$user = $wp_xmlrpc_server->login( $username, $password ) ) {
        return $wp_xmlrpc_server->error;
    }

    // Titulo e custom fields do post
    $title = $data["title"];
    $custom_fields = $data["custom_fields"];

    // Formatar o novo post
    $new_post = array(
        'post_status' => 'draft',
        'post_title' => $title,
        'post_type' => 'post',
    );

    // Faz o insert do novo post
    $new_post_id = wp_insert_post( $new_post );
    foreach( $custom_fields as $meta_key => $values )
        foreach ( $values as $meta_value )
            add_post_meta( $new_post_id, $meta_key, $meta_value );
    // Devolve ID do novo post
    return $new_post_id;
}

Origin Plugin

Installed on the site that will create duplicate post.

/wp-content/plugins/xml-post/xml-post.php

<?php
/**
 * Plugin Name: (SOpt) Plugin de Origem
 * Description: Publicações PARA outro site. CONFIGURAR 'user' e 'password' do Site Destino.
 * Plugin URI: https://wordpress.stackexchange.com/a/54875/12615
 * Version: 1.0
 * Author: brasofilo 
 */

add_action( 'add_meta_boxes', 'wpse_54822_add_custom_box' );
add_action( 'admin_head', 'wpse_54822_script_enqueuer' );
add_action( 'wp_ajax_wpse_54822_custom_query', 'wpse_54822_custom_query' );
add_action( 'wp_ajax_nopriv_wpse_54822_custom_query', 'wpse_54822_custom_query' );

function wpse_54822_add_custom_box() {
    add_meta_box(
        'wpse_54822_sectionid',
        __( 'Page Attachments' ), 
        'wpse_54822_inner_custom_box',
        'page'
    );
}

function wpse_54822_inner_custom_box() {
    global $post;
    ?>
        <a href="#" id="post-me" class="dettach" title="Cross post" >Post Me</a>
    <?php
}

function wpse_54822_script_enqueuer() {
    global $current_screen;
    if( 'page' != $current_screen->id )
        return;
    wp_register_script( 'my-js', plugin_dir_url(__FILE__) . '/ajax-xmlrpc.js' );
    wp_enqueue_script( 'my-js' );
    wp_localize_script( 'my-js', 'wp_ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); 
}

function wpse_54822_custom_query() {
    // Dados a enviar na chamada XML-RPC
    $data = array(
        "title" => 'titulo',
        "custom_fields" => 'custom_fields'
    );    
    // Considerando que user e password são "admin" e "admin"
    // E que o método postFromOutside é o que está definido no Plugin Destino
    $params = array( 'admin', 'admin', $data );
    $params = xmlrpc_encode_request( 'postFromOutside', $params );   
    // Iniciar a requisição HTTP
    $request = new WP_Http;
    $result = $request->request(
        'http://plugins.dev/xmlrpc.php',
        array('method' => 'POST', 'body' => $params )
    );
    // O retorno XML é EXTREMAMENTE ESPECÍFICO e depende do Plugin de Origem
    $xml = simplexml_load_string( $result['body'] );
    wp_send_json_success( $xml->params->param->value->int );
}

/wp-content/plugins/xml-post/ajax-xmlrpc.js

/**
 * Arquivo JS que acompanha o plugin XML-POST.PHP
 * O objeto wp_ajax é enviado pelo wp_localize_script
 * A propriedade the_id é somente ilustrativa 
 */
jQuery(document).ready(function($) {    
    $('#post-me').click(function(){
        $.post( 
            wp_ajax.ajaxurl, 
            { 
                action: 'wpse_54822_custom_query', 
                the_id: 'toast' 
            }, 
            function(data){
                console.log('Novo Post:',data.data[0]);
            }
        );
    });
});

[Security]

  • Create a user on the Target Site only for the XMLRPC connection; can use name and password type 128bits; ie, very complicated.
  • You might want to store user and password in a configuration file outside the folder public_html and make a require/include to pull this .
  • From what I’ve seen, there are some methods specific which are preferred targets of Ddos attacks and prevention is to do the unset() of these methods. With the line $methods = array(); in the Target Plugin we are deleting all the standard methods and adding only our soon after.
  • I suggest two security tools: the plugin Wordfence and the rules of .htaccess 5G Blacklist 2013.

References:

  • Perfect. Solved.

0

You can edit the file wp-config.php in the two Wordpress installations so that they point to the same database.

That way, everything created through one will automatically appear in the other.

  • But how will they point to the same database if they have different Urls? I mean... When it is an internal one, for example, I will go to the url in the database. Site 1: www.site.com.br/wordpress - Site 2 :www.site.com.br/wordpress/mobile - CAN UPDATE THE ANSWER?

  • @Lollipop instead of the bank address pointing to localhost it can point to the other URL.

  • Bro, understand... Are two wordpress. When I get the bank post, NO SITE 2, it will bring me www.site.com.br/contato that belongs to site1 and will redirect me to it. But the problem is that site 1 should never be opened by site 2. But everything on site 1 should be on site 2. Ta of course?

  • See the update of my question.

  • 3

    Without further details, this answer is a perfect recipe for a very big problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.