Disable wordpress parameters - php

I am currently using the 's' parameter for my pages.
Wordpress automatically makes it a search.
I want to disable the 's' parameter. I dont need the search function on my site.
Tried to find an answer or a direction to go into, but no luck.

If you cant write it yourself there is a plugin for that, it unsets all the s parameters and the sets a 404:
<?php
/**
* Unsets all search-related variables in WP_Query object and sets the
* request as a 404 if a search was attempted.
*
* #param object $obj A WP_Query object
* #return null
*/
public static function parse_query( $obj ) {
if ( $obj->is_search && $obj->is_main_query() ) {
unset( $_GET['s'] );
unset( $_POST['s'] );
unset( $_REQUEST['s'] );
unset( $obj->query['s'] );
$obj->set( 's', '' );
$obj->is_search = false;
$obj->set_404();
}
}
?>

Related

How to use $_GET in wordpress pages

Here's the thing...
I have created a button which on click opens a link like
https://www.something.com/something/?term=something
or [at first, I thought this is a URL problem... so I tried some other] Like:-
https://www.something.com/something.php?term=something
https://www.something.com/something?term=something
and else
now on this link, I want to echo $_GET['term']... which not happening, there is no error in the console... how to be able to echo it
I know the answer is in this document but I don't know how to use this thing... can anyone please describe the right way step by step...
https://codex.wordpress.org/Function_Reference/get_query_var
get_query_arg : Retrieve only public query variable in the WP_Query class of the global $wp_query object.
I propose for security , use rewrite class in Wordpress :
/**
* Add rewrite tags and rules
*
* #link https://codex.wordpress.org/Rewrite_API/add_rewrite_tag
* #link https://codex.wordpress.org/Rewrite_API/add_rewrite_rule
*/
/**
* Add rewrite tags and rules
*/
function myplugin_rewrite_tag_rule() {
add_rewrite_tag( '%city%', '([^&]+)' );
add_rewrite_rule( '^city/([^/]*)/?', 'index.php?city=$matches[1]','top' );
}
add_action('init', 'myplugin_rewrite_tag_rule', 10, 0);
for add to query arg :
/**
* Register custom query vars
*
* #param array $vars The array of available query variables
*
* #link https://codex.wordpress.org/Plugin_API/Filter_Reference/query_vars
*/
function myplugin_register_query_vars( $vars ) {
$vars[] = 'city';
return $vars;
}
add_filter( 'query_vars', 'myplugin_register_query_vars' );
example link in site : yoursite.com/city/45
get data in wordpress :
$city = get_query_var( 'city' );
echo $city;
That's quite simple
echo get_query_var( 'term', 'default_value');
Obviously you have to add this in functions.php for custom variables
function add_query_vars_filter( $vars ) {
$vars[] = "my_var";
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
read further details here

Unset data from WordPress API (wp-json)

I can already unset (remove specifics from normal posts) in the json returned from the WordPress API. I actually use the following below from this example: https://css-tricks.com/using-the-wp-api-to-fetch-posts/
What I am having trouble with and can't figure out, is how to change this so it unsets data from a Custom Post Type
Thoughts?
function qod_remove_extra_data( $data, $post, $context ) {
// We only want to modify the 'view' context, for reading posts
if ( $context !== 'view' || is_wp_error( $data ) ) {
return $data;
}
// Here, we unset any data we don't want to see on the front end:
unset( $data['author'] );
unset( $data['status'] );
unset( $data['featured_image'] );
//etc etc
return $data;
}
add_filter( 'json_prepare_post', 'qod_remove_extra_data', 12, 3 );
custom post type example filter:
function projectPost_remove_extra_data( $data, $post, $context ) {
if ( $context !== 'view' || is_wp_error( $data ) ) {
return $data;
}
// Here, we unset any data we don't want to see on the front end:
unset( $data['author'] );
return $data;
}
add_filter( 'json_prepare_project', 'projectPost_remove_extra_data', 12, 3 );
For wp-api v1.x, you need to extend WP_JSON_CustomPostType. There is an example in the pages file (class-wp-json-pages.php)
<?php
/**
* Page post type handlers
*
* #package WordPress
* #subpackage JSON API
*/
/**
* Page post type handlers
*
* This class serves as a small addition on top of the basic post handlers to
* add small functionality on top of the existing API.
*
* In addition, this class serves as a sample implementation of building on top
* of the existing APIs for custom post types.
*
* #package WordPress
* #subpackage JSON API
*/
class WP_JSON_Pages extends WP_JSON_CustomPostType {
/**
* Base route
*
* #var string
*/
protected $base = '/pages';
/**
* Post type
*
* #var string
*/
protected $type = 'page';
/**
* Register the page-related routes
*
* #param array $routes Existing routes
* #return array Modified routes
*/
public function register_routes( $routes ) {
$routes = parent::register_routes( $routes );
$routes = parent::register_revision_routes( $routes );
$routes = parent::register_comment_routes( $routes );
// Add post-by-path routes
$routes[ $this->base . '/(?P<path>.+)'] = array(
array( array( $this, 'get_post_by_path' ), WP_JSON_Server::READABLE ),
array( array( $this, 'edit_post_by_path' ), WP_JSON_Server::EDITABLE | WP_JSON_Server::ACCEPT_JSON ),
array( array( $this, 'delete_post_by_path' ), WP_JSON_Server::DELETABLE ),
);
return $routes;
}
/**
* Retrieve a page by path name
*
* #param string $path
* #param string $context
*
* #return array|WP_Error
*/
public function get_post_by_path( $path, $context = 'view' ) {
$post = get_page_by_path( $path, ARRAY_A );
if ( empty( $post ) ) {
return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
}
return $this->get_post( $post['ID'], $context );
}
/**
* Edit a page by path name
*
* #param $path
* #param $data
* #param array $_headers
*
* #return true|WP_Error
*/
public function edit_post_by_path( $path, $data, $_headers = array() ) {
$post = get_page_by_path( $path, ARRAY_A );
if ( empty( $post ) ) {
return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
}
return $this->edit_post( $post['ID'], $data, $_headers );
}
/**
* Delete a page by path name
*
* #param $path
* #param bool $force
*
* #return true|WP_Error
*/
public function delete_post_by_path( $path, $force = false ) {
$post = get_page_by_path( $path, ARRAY_A );
if ( empty( $post ) ) {
return new WP_Error( 'json_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
}
return $this->delete_post( $post['ID'], $force );
}
/**
* Prepare post data
*
* #param array $post The unprepared post data
* #param string $context The context for the prepared post. (view|view-revision|edit|embed|single-parent)
* #return array The prepared post data
*/
protected function prepare_post( $post, $context = 'view' ) {
$_post = parent::prepare_post( $post, $context );
// Override entity meta keys with the correct links
$_post['meta']['links']['self'] = json_url( $this->base . '/' . get_page_uri( $post['ID'] ) );
if ( ! empty( $post['post_parent'] ) ) {
$_post['meta']['links']['up'] = json_url( $this->base . '/' . get_page_uri( (int) $post['post_parent'] ) );
}
return apply_filters( 'json_prepare_page', $_post, $post, $context );
}
}
Replace "Pages" with "MyCustomPostTypes" and page with "mycustomposttype". Just be careful not to rename internal WordPress code that also uses the term page
Note: probably best to add this as a plugin rather than change the JSON-WP-API plugin
/**
* Plugin Name: MyCustom JSON App API
* Description: MyCustomPost handler for the JSON API
* Dependency: This plugin requires JSON-WP-API Plugin!!!!
* Author:
* Author URI:
* Version:
* Plugin URI:
*/
If possible, only the examples shown in internet is:
function qod_remove_extra_data ($ data, $ post, $ context) {
// We only want to modify the 'view' context, for reading posts
if ($ context! == 'view' || is_wp_error ($ data)) {
return $ data;
}
// Here, we unset any data we do not want to see on the front end:
unset ($data ['author']);
unset ($data ['status']);
// Continue unsetting whatever other fields you want return $ data;
}
add_filter ('json_prepare_post' 'qod remove extra_data', 12, 3);
and right is:
qod_remove_extra_data function ($ data, $ post, $ context) {
// We only want to modify the 'view' context, for reading posts
if ($ context! == 'view' || is_wp_error ($ data)) {
unset ( $data->data ['excerpt']); //Example
unset ($data->data ['content']); //Example
unset ($data->data ['name field to remove'])
//or
unset ($data->data ['name field to remove'] ['name subfield if you only want to delete the sub-field of field' ])
return $data;
}
}
add_filter ('rest_prepare_post' 'qod_remove_extra_data', 12, 3);
IMPORTANT:
Is:
add_filter ('rest_prepare_post' 'qod_remove_extra_data', 12, 3);
Not:
add_filter ('json_prepare_post' 'qod remove extra_data', 12, 3); //WRONG
If is Custom Post Type:
add_filter ('rest_prepare_{$post_type}' 'qod_remove_extra_data', 12, 3);
EXAMPLE: Name post type = product;
add_filter ('rest_prepare_product' 'qod_remove_extra_data', 12, 3);
With this code can remove the fields that you want the JSON. By using rest_prepare} _ {$ post_type decide that you eliminated every post_type fields, thus only affected the post_type you want and not all.
It should be no different to remove data from custom post types than from the built-in post types. Have you confirmed that your API call is actually returning your CPTs? First, you should look at the value of what is returned from: http://yourwebsite.com/wp-json/posts/types. Assuming that your CPT type shows up there, you should be able to query for items of that type, e.g. product, by calling: http://yourwebsite.com/wp-json/posts?type=product.
In other words, you should not change the name of the filter: you still want to tie into json_prepare_post. If you want to make your filter sensitive to post type and only remove certain fields if you have a CPT you could do something like:
function my_remove_extra_product_data( $data, $post, $context ) {
// make sure you've got the right custom post type
if ( 'product' !== $data[ 'type' ] ) {
return $data;
}
// now proceed as you saw in the other examples
if ( $context !== 'view' || is_wp_error( $data ) ) {
return $data;
}
// unset unwanted fields
unset( $data[ 'author' ] );
// finally, return the filtered data
return $data;
}
// make sure you use the SAME filter hook as for regular posts
add_filter( 'json_prepare_post', 'my_remove_extra_product_data', 12, 3 );
You can find more documentation in the WP API Getting Started Guide.

How to Overwrite WP core function get_comments_number comepletely

Due to some requirement I need to completely change the behavior of the get_comments_number();
A wp core function that returns the number of comments !
What I want is to change its behavior and instead of reading the comment I want it to override with the following function;
function get_review_numbers( $post_id = 0 ) {
$post = get_post( $post_id );
if ( ! $post ) {
$count = 0;
} else {
$count = get_rev_count($post->ID);
$post_id = $post->ID;
}
/**
* Filter the returned comment count for a post.
*
* #since 1.5.0
*
* #param int $count Number of comments a post has.
* #param int $post_id Post ID.
*/
return apply_filters( 'get_review_numbers', $count, $post_id );
}
Please guide me I want when ever I write some where get_comments_number it should execute the above function instead of executing its core function.
you can't overwrite functions in php. (theme devs test if function exists then create function to allow new functions to be created if run before that point)
However there is a filter in get_comments_number
return apply_filters( 'get_comments_number', $count, $post_id );
so you can filter the result with:
add_filter('get_comments_number', 'your_custom_funct');
function your_custom_funct($count){
$count++; // example you can add one to the count, etc
return $count; //return it when finished!
}

how do i get the Comment-ID with the comment_post_form

I´m searching for a way to hook into comment_post_form and update_comment_meta, if something, but i can´t figure out how to get the comment-ID.
The function is in the functions.php
function add_comment_drawing() {
$drawingsave = $_POST['drawinginput'];
if ($drawingsave == 'Das Bild wird gespeichert'){
update_comment_meta( $comment->ID, 'drawingurl', 'Brad' );
}
}
add_action('comment_post', 'add_comment_drawing');
Thanks in advance
Comment Actions:
comment_post
Runs just after a comment is saved in the database. Action function arguments: comment ID, approval status ("spam", or 0/1 for disapproved/approved).
function add_comment_drawing($comment_id){
$drawingsave = isset($_POST['drawinginput']) ? $_POST['drawinginput'] : false;
if($drawingsave == 'Das Bild wird gespeichert'){
update_comment_meta($comment_id, 'drawingurl', 'Brad' );
}
}
add_action('comment_post', 'add_comment_drawing', 10, 1);
You're missing the arguments in your function.
function add_comment_drawing( $comment_id, $approval_status ) {
$drawingsave = $_POST['drawinginput'];
if ($drawingsave == 'Das Bild wird gespeichert'){
update_comment_meta( $comment_id, 'drawingurl', 'Brad' );
}
}
add_action( 'comment_post', 'add_comment_drawing', 10, 2 );
" i can´t figure out how to get the comment-ID"
add_action: adds an action to the queue
do_action: somewhere in the code where the queued actions are executed (Find it!)
in this case: /wp-includes/comment.php line 1811.
about 10 lines above you see:
$comment_ID = wp_insert_comment($commentdata);
if ( ! $comment_ID ) {
return false;
}
So your comment_ID is what is provided BY the "add_action" (in this case by the wp_insert_comment method/function; so that you can use it in your function, not the other way around. E.g. log the comment_ID to a file or something.
"How does add_action work / parameters ? "
Open /wp-includes/plugin.php, search for "add_action" and around line 400 you see:
**
* Hooks a function on to a specific action.
*
* Actions are the hooks that the WordPress core launches at specific points
* during execution, or when specific events occur. Plugins can specify that
* one or more of its PHP functions are executed at these points, using the
* Action API.
*
* #uses add_filter() Adds an action. Parameter list and functionality are the same.
*
* #since 1.2.0
*
* #param string $tag The name of the action to which the $function_to_add is hooked.
* #param callback $function_to_add The name of the function you wish to be called.
* #param int $priority optional. Used to specify the order in which the functions associated with a particular action are executed (default: 10). Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.
* #param int $accepted_args optional. The number of arguments the function accept (default 1).
*/
function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
return add_filter($tag, $function_to_add, $priority, $accepted_args);
}
"How does do _action work / parameters ? "
idem. Look in wp-includes/plugin.php and look around line 427:
/**
* Execute functions hooked on a specific action hook.
*
* This function invokes all functions attached to action hook $tag. It is
* possible to create new action hooks by simply calling this function,
* specifying the name of the new hook using the <tt>$tag</tt> parameter.
*
* You can pass extra arguments to the hooks, much like you can with
* apply_filters().
*
* #see apply_filters() This function works similar with the exception that
* nothing is returned and only the functions or methods are called.
*
* #since 1.2.0
*
* #global array $wp_filter Stores all of the filters
* #global array $wp_actions Increments the amount of times action was triggered.
*
* #param string $tag The name of the action to be executed.
* #param mixed $arg,... Optional additional arguments which are passed on to the functions hooked to the action.
* #return null Will return null if $tag does not exist in $wp_filter array
*/
function do_action($tag, $arg = '') {
global $wp_filter, $wp_actions, $merged_filters, $wp_current_filter;
if ( ! isset($wp_actions[$tag]) )
$wp_actions[$tag] = 1;
else
++$wp_actions[$tag];
// Do 'all' actions first
if ( isset($wp_filter['all']) ) {
$wp_current_filter[] = $tag;
$all_args = func_get_args();
_wp_call_all_hook($all_args);
}
if ( !isset($wp_filter[$tag]) ) {
if ( isset($wp_filter['all']) )
array_pop($wp_current_filter);
return;
}
if ( !isset($wp_filter['all']) )
$wp_current_filter[] = $tag;
$args = array();
if ( is_array($arg) && 1 == count($arg) && isset($arg[0]) && is_object($arg[0]) ) // array(&$this)
$args[] =& $arg[0];
else
$args[] = $arg;
for ( $a = 2; $a < func_num_args(); $a++ )
$args[] = func_get_arg($a);
// Sort
if ( !isset( $merged_filters[ $tag ] ) ) {
ksort($wp_filter[$tag]);
$merged_filters[ $tag ] = true;
}
reset( $wp_filter[ $tag ] );
do {
foreach ( (array) current($wp_filter[$tag]) as $the_ )
if ( !is_null($the_['function']) )
call_user_func_array($the_['function'], array_slice($args, 0, (int) $the_['accepted_args']));
} while ( next($wp_filter[$tag]) !== false );
array_pop($wp_current_filter);
}
So the main "trick" around add_action / do_action / filter is call_user_func_array() : http://php.net/manual/en/function.call-user-func-array.php , once you understand that function, you understand what these functions in WP do.
"How does do _???? work "
So in general : just look at the source code of WordPress (that is the advantage its opensource)
another tip is to use an IDE, something like Eclipse or Netbeans: they can show you a lot of info in the IDE, and on top of that: during "runtime" you get a lot of info through the debugger.

what is the difference between filters and hooks & how can i use them in child theme

What is the difference between filter and hooks in wordpress.
How can i use the following filter in child theme ?
<?php
foreach ( $results as $result ) {
// external plugins can modify or disable field
$result = apply_filters( 'cp_package_field', $result, 'ad' );
if ( ! $result )
continue;
?>
how can i use the following hook in child theme ?
/**
* called in cp_add_new_listing() to hook into inserting new ad process
*
* #since 3.2.1
* #param int $post_id
*
*/
function cp_action_add_new_listing( $post_id ) {
do_action( 'cp_action_add_new_listing', $post_id );
}
For the first part of your question, here is a link to an explanation I found a while back that was pretty comprehensive and it helped me to understand the difference.
https://wordpress.stackexchange.com/questions/1007/difference-between-filter-and-action-hooks
To use the hook in your child theme, you'd probably need to have the following piece of code in your child theme's functions.php file:
/**
* Our callback function to the hook
* #param int $post_id id of the post
* #return void
*/
function my_child_theme_new_listing_cb( $post_id ) {
if($post_id == 10) { //Or whatever you want
echo 'Hello World';
}
//We do not have the responsibility to return something as it is a hook
}
add_action( 'cp_action_add_new_listing', 'my_child_theme_new_listing_cb', 10, 1 );
Hope it helps.

Categories