I'm trying to ajaxify wordpress the clean way. The idea is this:
/wp/wp-admin/admin-ajax.php?action=my_plugin_fetch_page&page=http://example.com/about
).http://example.com/about
).I cannot figure out a good way to get contents of page by only knowing its url.
I have tried using wp_remote_get
. So I simply make another request from server to url http://example.com/about
. This works, but it's quite slow (slowing down a request about 2 seconds).
I have tried using url_to_postid
, which converts url to post_id
. Unfortunately this does not work for archive pages and probably would be useless anyways, since I need full response body from url http://example.com/about
, not just id of the equivalent page.
This is how it works currently with wp_remote_get
:
function my_plugin_fetch_page () {
/*
*
* Getting url of target page from GET parameters
*
*/
$url = $_GET['page'];
$title = '';
$content = '';
/*
*
* Url must be set in request parameters and it must be internal link
*
*/
if ( $url && my_plugin_is_internal_page( $url ) ) {
/*
*
* Format relative urls to absolute urls.
*
* test/example -> http://example.com/test/example
*
*/
$url = nolife_single_format_url( $url );
/*
*
* Make GET request.
*
*/
$page_response = wp_remote_get( $url, array(
'user-agent' => 'InternalRequester'
) );
if ( ! is_wp_error( $page_response ) ) {
/*
*
* Response contains title and page content seperated by some
* seperator. By splitting response from that seperator, we
* get title and contents of page in seperate values.
*
*/
$content_parts = explode( MY_PLUGIN_SEPERATOR, wp_remote_retrieve_body( $page_response ) );
// title comes first
$title = $content_parts[0];
// then content of page
$content = $content_parts[1];
}
}
wp_send_json( array(
'url' => $url,
'title' => $title,
'content' => $content
) );
die;
}
Can anyone please help me with this one?
This snippet checks to see if a string exists in any defined taxonomy, including custom ones:
$term = "maybe_a_term";
$taxonomies = get_taxonomies(['show_ui' => true]);
$term_exists = array_reduce($taxonomies, function($carry, $item) use ($term) {
return $carry || get_term_by('slug', $term, $item);
}, false);
The $taxonomies
array is reduced to a boolean, so $term_exists
will be true if the term is found. You could then use a taxonomy-based query to gather the posts you need.
Note: The argumement ['show_ui' => true]
hides internal taxonomies like post_format
and nav_menu
.
It's insane that WordPress can't reverse-parse its own permalinks.