I'm using Wordpress as headless CMS.
I use the following function to return a page based on the page title.
No code or Wordpress content has changed and suddenly it has stopped working...
Almost indentical code on the same server on a different site is working fine.
Anyone got any ideas what might have happened ?
// -- Get page based on page name -- //
function getWordpressPage($wordpressPageName){
$page = NULL;
$pageRequest = cleanUrlVar($wordpressPageName);
if($pageRequest){
$page = get_page_by_title( $pageRequest );
if($page != NULL){
setup_postdata($page);
return the_content();
}
}
if($page == ''){
header('Location: /');
exit();
}
}
FYI - var_dump($page) returns the data so Wordpress is returning something, it looks like it's falling over at the 'return the_content() stage...
CodePudding user response:
the_content()
will show the content by echo it. So if you want to get
variable to return, you should use get_the_content()
Update your codes to return it:
return get_the_content();
You can find out more here:
https://developer.wordpress.org/reference/functions/get_the_content/
CodePudding user response:
You don't even need setup_postdata
. By using get_page_by_title
, you'll get the entire page object
.
function getWordpressPage($wordpressPageName)
{
$page = NULL;
$pageRequest = cleanUrlVar($wordpressPageName);
if ($pageRequest) {
$page = get_page_by_title($pageRequest, ARRAY_A);
if ($page != NULL) {
return $page['post_content'];
}
}
if ($page == '') {
header('Location: /');
exit();
}
}
Note:
cleanUrlVar
is a custom function you're using, so make sure it works.- I used
ARRAY_A
inget_page_by_title
to get the results inarray
format
Possible alternative, using setup_postdata
setup_postdata
will accept post object
or post id
not page title
. So you could use the post
global variable and pass it to the setup_postdata
. Although this would work, but, probably you don't even need to do that.
function getWordpressPage($wordpressPageName=''){
global $post;
setup_postdata($post);
$content = get_the_content();
return $content;
}