I needed to pull database records into a page but couldn’t use PHP directly on that page (it was limited by the CMS used).
So what I did was to get the content I needed using a PHP file (‘get-posts.php’):
1 2 3 4 5 6 7 8 9 10 11 |
<?php require($_SERVER['DOCUMENT_ROOT'].'/blog/wp-blog-header.php'); $args = array( 'numberposts' => 5, 'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date"); $postslist = get_posts( $args ); $i=0; foreach ($postslist as $post) : setup_postdata($post); $result[$i]="<a href='".get_permalink()."' title='".get_the_title()."'>".get_the_title()."</a>"; $i++; endforeach; header('HTTP/1.1 200 OK'); echo json_encode($result); ?> |
Above is the final code used for this file, but when I initially tried the integration I kept getting a 404 error message in JavaScript for the php file I was trying to access.
The solution was adding the header code which started the output with an “OK this page exists”.
The jQuery code I used to read the data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$.ajax({ type: 'POST', url: '/get-posts.php', data: 'noNeed', dataType: 'json', cache: false, // using the output in DIV elements: success: function(result) { $('#div1').html(result[0]); $('#div2').html(result[1]); $('#div3').html(result[2]); $('#div4').html(result[3]); $('#div5').html(result[4]); }, }); |