Create post in a wordpress and bring in another wordpress automatically

4

Options:

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

or

  • Everything you create in wordpress-2 be "copied" to wordpress-1

or

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

I have already used multsite integrated with ThreeWP-Broadcast, but it has strange bugs, such as automatically moving away from the admin when I alternate the dashboard.

  

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

    
asked by anonymous 27.05.2015 / 21:09

3 answers

3

Doing this automatically seems a bit complicated, but I think it's possible. The solution I'm suggesting has not been tested, but in theory I think it should work. I will call from w1 the WordPress in which you want to create the post, and from w2 the WordPress that will receive the posts, once they are created in the first one.

  • Maintain integrity between the two sites

    This one I believe should be step zero, but anyway. If you have some sort of customization in w1 posts, such as meta data , custom fields and things like, and do not have at least the same structure in w2 , the post that you are wanting to duplicate will not be duplicated 100% correctly. So make sure w2 has at least all the properties you set in w1 .

  • Create a action hook for posting in w1

    WP has a series of predefined actions , and tying some more functionality to them is taken as creating a hook. The action we're going to use is the publish_post . From 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 post a post, something (that you define) will happen. In terms of code, this is the skeleton you put in 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'm going back to this method soon.

  • Create a posts insertion interface in w2

    There is more than one way you can do this, but one that I particularly like is using the JSON API (From this point, my entire answer is based on this plugin). It provides query methods - which return a JSON based on URL and its parameters - as well as methods of creating posts (which interests us), which works basically the same way. You call a URL of type 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 nonce , which is a required parameter for the create_post() method. Read about the details of the plugin here .

  • Call, within the action hook , your insertion method 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. Since you are going to work with post , you should provide it as a parameter for this method. Inside it, you'll extract what you need from the post you just created in w1 , mount a query string using this method, and call the URL 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 insert method in w2 . Note also that the value of nonce was arbitrary. You can use cURL to make the request in w2 to get the correct value. The list of parameters for all methods of the plugin can be found at documentation .

    Finally, since your method is now given a parameter, you have to change the add_action to:

    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 achieve your goal. Of course you'll have a good debug job ahead of you, and post insertion can be a bit boring, mainly because of nonce . Constructing query can be a bit complex, too, and if you're working with custom posts , insertion may be a bit tricky. Anyway, the theory is this. I hope I have helped.

        
    29.05.2015 / 03:21
    2

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

  • WP API (JSON)
  • Feed (XML)
  • XMLRPC API
  • And, 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 WordPress base code. However, my answer is via XMLRPC, a classic WP method (for making trackbacks and pingbacks, publishing from web or desktop apps), and usually Disable because it opens the door to several attempts to attack [see" security "at the end] .

    Notes :

    • This code is just a proof of concept; the source post is played on the target site, but this information is not stored on the source site;

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

    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: http://pt.stackoverflow.com/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;
    }
    

    Source 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 128bit name and password; that is, very complicated.
    • You may want to store user and password in a configuration file outside the public_html folder and make require/include to pull it.
    • From what I've seen, there are some specific methods that are preferred targets for DDoS attacks and prevention is to do unset() of this methods. With the $methods = array(); line in the Destination Plugin we're deleting all the default methods and adding just our logo next.
    • I suggest two security tools: the WordFence plugin and the% rules of% 5G Blacklist 2013 .

    References:

    11.01.2016 / 15:06
    0

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

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

        
    28.05.2015 / 19:10