I creating a small plugin to add <!--nextpage--> shortcode under some requirements.
For example , my plugin will check if the user agent is a bot, if yes it will not add <!--nextpage--> and if not it will add it.
What I achieved so far is I created a function to check user agent :
function test(){
if($_SERVER['HTTP_USER_AGENT'] == ' Bot i want '){
// here we dnt show <!--nextpage-->
} else {
do_shortcode('<!--nextpage-->');
}
}
add_shortcode('myshortcode','test');
So when I add the short code in the post editor it work fine, but the only problem is it doesn't add the <!--nextpage-->, it doesn't get executed, and if I try other short codes like [tweetme] or other registred short codes they work just fine.
To print out into your html page, you shouldn't not call
do_shortcode('<!--nextpage-->');
The above line will do nothing, since is not a valid shortcode format in Wordpress, and as a result, do_shortcode cannot parse it.
A valid shortcode in wordpress need to be wrapped with [ ] brackets.
To achieve what you are trying to do (printing out '' when web crawler detected), you can just change your test function to:
function test(){
if($_SERVER['HTTP_USER_AGENT'] == ' Bot i want '){
// here we dnt show <!--nextpage-->
} else {
echo '<!--nextpage-->';
}
}
Also, you can have a look at do_shortcode function documentation here: https://developer.wordpress.org/reference/functions/do_shortcode/
Related
I'm currently developing a plugin which takes a parameter from URL (example: example.com/product_id/1234 is converted to example.com) and passes it in WP_Query (supposedly this should be used instead of GET or POST) for later use. My code so far looks like this:
function shortcode_callback() {
echo get_query_var('product_id','not found<br>');
}
function prepare_rewrite() {
add_filter('query_vars','rewrite_add_var');
add_rewrite_rule('^product_id/([^/]*)/?$','index.php?page_id=18&product_id=$matches[1]','top');
flush_rewrite_rules();
}
function rewrite_add_var($q_vars) {
$q_vars[] = 'product_id';
return $q_vars;
}
add_action('init','prepare_rewrite');
add_shortcode('shortcode', 'shortcode_callback');
Unfortuantely, even though redirect works, the custom parameter does not exist. I've been trying to put this piece of code in functions.php file, but to no avail. I've been also trying to solve this issue by using add_rewrite_tag, but as far as I can tell it's only useful when it comes to post selection.
I have tried to implement the code which can get the user region when the user open the page but it is not working i have used this code inside the functions.php
function user_region() {
$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));
return '<div class="user-region">'.$details->region.'</div>';
}
add_shortcode("get-user-region", "user_region");
this is my shortcode inside the functions.php and i have used the shortcode inside the wordpress page
<?php echo get-user-region_callback(); ?>
<?php echo do_shortcode('[get-user-region]') ?>
I have tried both ways but both are not working no results are showing from this shortcode.
First of all, your URL to ipinfo is incorrect. If are treating the response as JSON, but the output of https://ipinfo.io/ip is HTML. You need to specify/json` at the end:
https://ipinfo.io/{$ip}/json
Other than that, you need to check that file_get_content is enabled on your platform and that it allows remote url loading (setting allow_url_fopen).
I'd like to use a custom post type archive as a site's front page, so that
http://the_site.com/
is a custom post type archive displayed according to my archive-{post-type}.php file.
Ideally I would like to alter the query using is_front_page() in my functions.php file. I tried the following, with a page called "Home" as my front page:
add_filter('pre_get_posts', 'my_get_posts');
function my_get_posts($query){
global $wp_the_query;
if(is_front_page()&&$wp_the_query===$query){
$query->set('post_type','album');
$query->set('posts_per_page',-1);
}
return $query;
}
but the front page is returning the content of "Home" and seems to be ignoring the custom query.
What am I doing wrong? Is there a better way, in general, of going about this?
Note: I did post this in WordPress Answers but that community is comparatively tiny.
Posting the final solution as an answer (Isaac placed it as a comment) just for anyone still looking.
Isaac was on the right track with adding a filter via functions.php. What he did wrong was call is_front_page(), which doesn't work yet because we're in pre_get_posts and the query hasn't been executed yet.
We do have the current page ID however. So we can still solve this, by looking into the WordPress option register for an option called page_on_front, which returns the ID of the page the user set as frontpage.
(For an overview of all WordPress options, just visit <yourwordpressinstallation>/wp-admin/options.php in your browser.)
Which makes for the following solution as suggested by Ijaas:
add_action("pre_get_posts", "custom_front_page");
function custom_front_page($wp_query) {
// Compare queried page ID to front page ID.
if(!is_admin() && $wp_query->get("page_id") == get_option("page_on_front")) {
// Set custom parameters (values based on Isaacs question).
$wp_query->set("post_type", "album");
$wp_query->set("posts_per_page", -1);
// WP_Query shouldn't actually fetch the page in our case.
$wp_query->set("page_id", "");
}
}
You might have to alter a few conditional tags to make sure all plugins still work, depending on how heavily the query gets altered.
Hope this helps someone.
Update: as noted below, add !is_admin() to the if-statement to make sure the function only runs on the frontend. If you only want this action to run for the initial query, you could also add the main query check $wp_query->is_main_query().
In response to Robberts solution:
answered May 6 '13 at 12:04
adding && !isAdmin() to the if function other wise it replaces the post type query for all admin pages as well.
Just in case anyone has issues with this.
edit:
also adding && $wp_query->is_main_query() to the if statement stops it affecting widgets and the menu
so total code I have
if($wp_query->get("page_id") == get_option("page_on_front") && !isAdmin() && $wp_query->is_main_query()) {}
In order to get that query to work, you're going to have to add that code to a page template, create a page, set your template as the template for the page you just created, and then set that page as the home page in Settings => Reading in the admin area.
By the way, the is_front_page() function only returns true if you're on a page that's been set as the home page from the admin menu.
The other option would be to modify index.php, but if you did that, is_front_page() would always return false. In that case, you'd want to use is_home() instead.
I hope that helps.
Isaac, you are correct, I didn't thoroughly read your question and I made the assumption that you were looking to do this the "easy" way.
Anyway, I put your code on my test site and, indeed, it didn't work. I looked at my SQL log and it turns out that your code produces this in the query wp_posts.post_status = 'private'.
So, I tried adding the line $query->set('post_status', 'public'); to your function, and it worked just fine.
In summary, try this:
add_filter('pre_get_posts', 'my_get_posts');
function my_get_posts($query){
global $wp_the_query;
if(is_front_page()&&$wp_the_query===$query){
$query->set('post_type','album');
$query->set('posts_per_page',-1);
$query->set('post_status', 'public');
}
return $query;
}
I want to make a plugin, that I will use for some jQuery AJAX loading of table data.
I have a function that prints the data correctly, but how do I "hook" into a specific url?
Like say, I want the function to be run, and the data to be printed whenever a request to /mycustomplugin/myurl.php is run? (Please note that the url/file should not exist)
I have no experience with WP plugins.
To filter your custom URL before Wordpress starts executing queries for other things use something like this:
add_action('parse_request', 'my_custom_url_handler');
function my_custom_url_handler() {
if($_SERVER["REQUEST_URI"] == '/custom_url') {
echo "<h1>TEST</h1>";
exit();
}
}
A simple
if ($_SERVER["REQUEST_URI"] == '/mycustomplugin/myurl.php') {
echo "<my ajax code>";
}
Should work wonders.
If you wanted to return regular wordpress data you could just include wp-blogheader.php into your custom php file like so
//Include Wordpress
define('WP_USE_THEMES', false);
require('Your_Word_Press_Directory/wp-blog-header.php');
query_posts('showposts=10&cat=2');
Just use regular theming tags to return the content you desire. This
Where is your table data coming from though? Are you trying to show this information on the admin side or the viewer side?
Also see for a full breakdown of calling hooked functions with wp_ajax http://codex.wordpress.org/AJAX_in_Plugins
add_action( 'init', 'my_url_handler' );
function my_url_handler() {
if( isset( $_GET['unique_hidden_field'] ) ) {
// process data here
}
}
using add_action( 'init', 'your_handler') is the most common way in plugins since this action is fired after WordPress has finished loading, but before any headers are sent. Most of WP is loaded at this stage, and the user is authenticated.
I was wondering what the filter was to change the search term in Wordpress?
For example, if someone types in xxx, how could I change that to yyy before it goes into the wordpress search engine?
Cheers.
Change it when it gets to WordPress, right before WP queries the database:
$search_replacements = array(
'find' => 'replace',
'find2' => 'replace2',
'var' => 'foo'
);
function modify_search_term($request_vars) {
global $search_replacements;
if (!empty($request_vars['s']) && !empty($search_replacements[$request_vars['s']])) {
$request_vars['s'] = $search_replacements[$request_vars['s']];
}
return $request_vars;
}
add_filter('request', 'modify_search_term');
This will allow you to handle as many conditions as you can think up and add to the $replacements array.
The 99 in the add_filter is to get it to run late so that you're the last one to make changes to the query (could be important depending upon what other plugins you have installed).
Your URL will still indicate the original term, but you save a page load. If you have a high traffic site then you don't want to redirect just to get a pretty url.
Your not going to be able to change it before it goes into wordpress without using htaccess rewrite rules. What you can do however is create a custom filter to manually redirect specific search terms into new search query's using a standard browser redirect. I had to use the javascript location function in my example because I couldn't figure out how to catch the search variable via a filter before anything was outputted to the browser (thus limiting my ability to use the built in wordpress redirect function or a standard php header redirect.)
The following code will take any searches for "test" and redirect it to a "smickie" search. This was put together pretty quick and dirty, so you'll want to modify it to suite your needs obviously, but hopefully this can get you started in the right direction.
function redirect_searchterm() {
if (is_search()) {
$search_query = get_search_query();
if ($search_query == "test") {
$new_searchquery = "smickie";
?>
<script type="text/javascript">
<!--
location.replace("<?php echo get_option('siteurl') . '/?s=' . $new_searchquery .'&submit=Search'; ?>");
-->
</script>
<?php
}
}
}
add_action('wp_head', 'redirect_searchterm', 1);