0
votes

I'm having a bit of trouble trying to understand the Wordpress functions to display posts from a Wordpress blog to a website.

Basically I have a website www.site.com and a blog B with Wordpress structure located in www.site.com/blog. I want to learn to display B's recent posts in A.

I know I'll have to use PHP to call B's posts and display them in A as HTML elements. I messed around with the PHP functions but wasn't able to execute a solution correctly.

Can you help me please?

3
you can use jQuery's AJAX to get data from another website - Marcin
Do you want to display all the posts? - The One and Only ChemistryBlob
Marcin, I know Wordpress has its own PHP functions so I would like to avoid using jQuery. ChemistryBlob, no, just the recente ones! I'll have to use an array, right? Like, 3 would be a good start. - Luiz Cruz
might also want to look at the WP Rest API and just do it w javascript - Tom Woodward

3 Answers

3
votes

Load the wp-blog-header.php file from site B in site A.

Like this:

<?php 
    define('WP_USE_THEMES', false);
    require('./wp-blog-header.php');
?>

To load the posts:

<ul>
<?php

$args = array( 'posts_per_page' => -1 );

$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
    <li>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </li>
<?php endforeach; 
wp_reset_postdata();?>

</ul>
1
votes

Thanks for all the help.

As I said, I installed Wordpress on site.com/blog and I wanted site.com's homepage (index.php) to show, say, 3 Wordpress posts on the "News" section of the page.

So, for site.com I had to add:

<div id="news">
<p>Here you can see our latest News</p>
<?php 
define('WP_USE_THEMES', false);
require('blog/wp-blog-header.php'); //Note the folder hierarchy to find wp-blog-header.php
?>
<?php
$my_query = new WP_Query('showposts=3'); //"3" being the number of posts to be shown
while ($my_query->have_posts()): $my_query->the_post();
?>
<h3><?php the_title() ?></h3> //This makes the post title show inside a h3 tag
<p><?php the_excerpt() ?></p> //This makes the post excerpt show inside a p tag
<?php endwhile;
?>
</div>
0
votes

You shouold look into RSS feeds and parsing those out into the data you need. Most WP installations will have the RSS available, SEE HERE.

There are many ways to do this, but I have found that grabbing the data already available is simple and writing out a controller to parse and display the data you seek is simple enough. This is just one way, may or may not work for your application but I have had great luck.

Good luck and hope this can steer you in a direction toward your solution.