Last active
February 27, 2017 16:42
-
-
Save morgyface/62522daa72f8444f0286d74c47b3e8b6 to your computer and use it in GitHub Desktop.
WordPress | Getting Posts from another WordPress site
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /* Here we grab posts from the main site */ | |
| function get_other_posts(){ | |
| $wpdb_old = wp_clone($GLOBALS['wpdb']); | |
| $wpdb_new = &$GLOBALS['wpdb']; | |
| $wpdb_new = new wpdb('your_db_username','db_password','new_db_name','localhost'); | |
| $wpdb_new->set_prefix('wp_'); | |
| $otherposts = get_posts(); | |
| if ( $otherposts ) { | |
| echo '<ul>'; | |
| foreach ( $otherposts as $post ) : setup_postdata( $post ); | |
| $posttitle = $post->post_title; | |
| $postdate = $post->post_date; | |
| // post_date is returned in this format Y-m-d H:i:s | |
| // So here we reformat. | |
| $date = date('F Y', strtotime($postdate)); | |
| $post_name = $post->post_name; | |
| $post_content = $post->post_content; | |
| $content = apply_filters( 'the_content', $post_content ); | |
| $content = str_replace( ']]>', ']]>', $content ); | |
| echo '<li>'; | |
| echo '<h3>' . $date . '</h3>'; | |
| echo '<h2>' . $posttitle . '</h2>'; | |
| echo $content; | |
| echo '</li>'; | |
| endforeach; | |
| echo '</ul>'; | |
| wp_reset_postdata(); | |
| } | |
| //We are done so lets take the old wpdb back on its position | |
| $wpdb_new = $wpdb_old; | |
| } | |
| ?> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Getting posts from another WordPress site.
I used this when a client had a sister site and didn't want to duplicate the posts.
You obviously need to enter the main sites database details to get it working and the function needs adding to your themes main functions.php file. Then to call it you simply use get_other_posts().
It's fairly crude at the moment, there probably should be additional checks to make sure the $post->post_status is publish.
I hope to develop it further soon.