Override a function with child themes functions.php - wordpress

As the title reads I'm trying to modify a function called by a parent theme in my child, I know that the child theme is set to be loaded beforehand so I'm curious if this is even possible?
My parent theme has a function called ajax_search_box() that I'd like to modify a query in, and I'd rather not modify the parent theme files in case I need to update it down the road.. what would be the best way to do this?
Also, for bonus points, how would I go about doing this with a widget as well? Thanks in advance!
function SearchFilter($query) {
// If 's' request variable is set but empty
if (isset($_GET['s']) && empty($_GET['s']) && $query->is_main_query()){
$query->is_search = true;
$query->is_home = false;
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
function ajax_search_box() {
if (isset($_GET["q"]))
{
$q = $_GET["q"];
global $wpdb;
$q = mysql_real_escape_string($q);
$q = $wpdb->escape($q);
$query = array(
'post_status' => 'publish',
'order' => 'DESC',
's' => $q
);
$get_posts = new WP_Query;
$posts = $get_posts->query( $query );
// Check if any posts were found.
if ( ! $get_posts->post_count )
die();
//Create an array with the results
foreach ( $posts as $post )
echo $post->post_title . "|" . $post->ID . "\n";
}
die();
}
// creating Ajax call for WordPress
add_action( 'wp_ajax_nopriv_ajax_search_box', 'ajax_search_box' );
add_action( 'wp_ajax_ajax_search_box', 'ajax_search_box' );

the parent theme needs to check if(function_exists('ajax_search_box')) and if it doesn't exist then it will declare it.
If the parent theme checks to see if the function exists, then you can declare it first and have it do what you want.
If the parent theme does not check, get in touch with the theme author to see if they will throw that change in for the next update....and code it yourself too. That way when the theme updates then you will still be good to go.

Break free of functions.php, write your own plugin.
<?php
/**
* Plugin Name: Manipulate the Parent
* Requires: PHP5.3+
*/
add_action( 'after_setup_theme', function()
{
remove_filter( 'pre_get_posts','SearchFilter' );
// now add your own filter
add_filter( 'pre_get_posts', 'your_callback_for_your_filter' );
});
function your_callback_for_your_filter()
{
// do stuff
}

Related

Exclude current post from "recent posts widget"

In a plugin for displaying recent posts in your sidebar widget, how can we apply a filter to the plugin's functions.php so that it won't include the current page/post in the display?
The plugin author replied, before he entered a long silence: "You can add custom parameter to the rpwe_default_query_arguments filter. Just add exclude => get_the_ID() to the filter."
Is it here, that we add it?
// Allow plugins/themes developer to filter the default query.
$query = apply_filters( 'rpwe_default_query_arguments', $query );
How?
This is the plugin: https://wordpress.org/plugins/recent-posts-widget-extended/
I found some guidance that appears to be quite simple
but then it results in errors in my site (localhost) while trying to correct the syntax. => seems to be not correctly used.
This is what I have so far:
add_filter( 'rpwe_default_query_arguments', 'rpwe_exclude_current' );
function rpwe_exclude_current ( $query ) {
'exclude' => get_the_ID()
$posts = new WP_Query( $query );
return $posts;
}
Here is the answer that worked in my situation:
add_filter( 'rpwe_default_query_arguments', 'my_function_name' );
function my_function_name( $args ) {
if( is_singular() && !isset( $args['post__in'] ) )
$args['post__not_in'] = array( get_the_ID() );
return $args;
}
Here is the site where I found it.

adding custom page template from plugin

I'm working on building my first plugin for wordpress and am needing it to dynamically add a custom page for a login screen among other things.
The only thing I've been able to find that's anywhere near what I'm needing is here: WP - Use file in plugin directory as custom Page Template? & Possible to add Custom Template Page in a WP plugin?, but they're still not quite what I'm looking for.
Here is the code that I currently have running in my plugin...
// Add callback to admin menu
add_action( 'template_redirect', 'uploadr_redirect' );
// Callback to add menu items
function uploadr_redirect() {
global $wp;
$plugindir = dirname( __FILE__ );
// A Specific Custom Post Type
if ( $wp->query_vars["post_type"] == 'uploadr' ) {
$templatefilename = 'custom-uploadr.php';
if ( file_exists( TEMPLATEPATH . '/' . $templatefilename )) {
$return_template = TEMPLATEPATH . '/' . $templatefilename;
} else {
$return_template = $plugindir . '/themefiles/' . $templatefilename;
}
do_theme_redirect( $return_template );
}
}
function do_theme_redirect( $url ) {
global $post, $wp_query;
if ( have_posts ()) {
include( $url );
die();
} else {
$wp_query->is_404 = true;
}
}
Using this would require that my client create new page... what I'm needing is for the pluging to auto create a custom page (with a customized path, meaning .com/custompathhere) using a template file from the plugin folder, which will then contain all actions the plugin performs.
Note: This plugin is designed to run on one page, therefore reducing load-time and etc.
Thanks in advance!
Here is my code solution for adding page templates from a Wordpress plugin (inspired by Tom McFarlin).
This is designed for a plugin (the template files are searched for in the root directory of the plugin). These files are also in exactly the same format as if they were to be included directly in a theme. This can be changed if desired - check out my full tutorial http://www.wpexplorer.com/wordpress-page-templates-plugin/ for greater detail on this solution.
To customise, simply edit the following code block within the __construct method;
$this->templates = array(
'goodtobebad-template.php' => 'It\'s Good to Be Bad',
);
Full code;
class PageTemplater {
/**
* A Unique Identifier
*/
protected $plugin_slug;
/**
* A reference to an instance of this class.
*/
private static $instance;
/**
* The array of templates that this plugin tracks.
*/
protected $templates;
/**
* Returns an instance of this class.
*/
public static function get_instance() {
if( null == self::$instance ) {
self::$instance = new PageTemplater();
}
return self::$instance;
}
/**
* Initializes the plugin by setting filters and administration functions.
*/
private function __construct() {
$this->templates = array();
// Add a filter to the attributes metabox to inject template into the cache.
add_filter(
'page_attributes_dropdown_pages_args',
array( $this, 'register_project_templates' )
);
// Add a filter to the save post to inject out template into the page cache
add_filter(
'wp_insert_post_data',
array( $this, 'register_project_templates' )
);
// Add a filter to the template include to determine if the page has our
// template assigned and return it's path
add_filter(
'template_include',
array( $this, 'view_project_template')
);
// Add your templates to this array.
$this->templates = array(
'goodtobebad-template.php' => 'It\'s Good to Be Bad',
);
}
/**
* Adds our template to the pages cache in order to trick WordPress
* into thinking the template file exists where it doens't really exist.
*
*/
public function register_project_templates( $atts ) {
// Create the key used for the themes cache
$cache_key = 'page_templates-' . md5( get_theme_root() . '/' . get_stylesheet() );
// Retrieve the cache list.
// If it doesn't exist, or it's empty prepare an array
$templates = wp_get_theme()->get_page_templates();
if ( empty( $templates ) ) {
$templates = array();
}
// New cache, therefore remove the old one
wp_cache_delete( $cache_key , 'themes');
// Now add our template to the list of templates by merging our templates
// with the existing templates array from the cache.
$templates = array_merge( $templates, $this->templates );
// Add the modified cache to allow WordPress to pick it up for listing
// available templates
wp_cache_add( $cache_key, $templates, 'themes', 1800 );
return $atts;
}
/**
* Checks if the template is assigned to the page
*/
public function view_project_template( $template ) {
global $post;
if (!isset($this->templates[get_post_meta(
$post->ID, '_wp_page_template', true
)] ) ) {
return $template;
}
$file = plugin_dir_path(__FILE__). get_post_meta(
$post->ID, '_wp_page_template', true
);
// Just to be safe, we check if the file exist first
if( file_exists( $file ) ) {
return $file;
}
else { echo $file; }
return $template;
}
}
add_action( 'plugins_loaded', array( 'PageTemplater', 'get_instance' ) );
Check out my tutorial on this for more info.
http://www.wpexplorer.com/wordpress-page-templates-plugin/
I hope this helps you in what you want to do :)
I actually was able to talk to a developer friend of mine after revising the code quite a bit.
Here it is...
<?php
register_activation_hook( __FILE__, 'create_uploadr_page' );
function create_uploadr_page() {
$post_id = -1;
// Setup custom vars
$author_id = 1;
$slug = 'event-photo-uploader';
$title = 'Event Photo Uploader';
// Check if page exists, if not create it
if ( null == get_page_by_title( $title )) {
$uploader_page = array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_name' => $slug,
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'page'
);
$post_id = wp_insert_post( $uploader_page );
if ( !$post_id ) {
wp_die( 'Error creating template page' );
} else {
update_post_meta( $post_id, '_wp_page_template', 'custom-uploadr.php' );
}
} // end check if
}
add_action( 'template_include', 'uploadr_redirect' );
function uploadr_redirect( $template ) {
$plugindir = dirname( __FILE__ );
if ( is_page_template( 'custom-uploadr.php' )) {
$template = $plugindir . '/templates/custom-uploadr.php';
}
return $template;
}
?>
I'm providing a general solution for those that want to add a template to a post from the their plugin. Use the single_template filter.
<?php
add_filter( 'single_template', 'add_custom_single_template', 99 );
function add_custom_single_template( $template ) {
return plugin_dir_path( __FILE__ ) . 'path-to-page-template-inside-plugin.php';
}
?>
Also, if you want to use the template in a specific post type, then:
<?php
add_filter( 'single_template', 'add_custom_single_template', 99 );
function add_custom_single_template( $template ) {
if ( get_post_type() == 'post-type-name'; ) {
return plugin_dir_path( __FILE__ ) . 'path-to-page-template-inside-plugin.php';
}
return $template;
}
?>

Wordpress Add custom permalink

I have a dynamic page setup in wordpress which uses a $_GET['id'] php variable to make a query to the database. The problem is that my url format looks like the following:
http://site.com/business/id?=123
What's the best way to make the url look like:
http://site.com/business/business-name-here
Is it done using rewrite rules in the .htaccess file?
Thanks in advance
I've found a great class to do just that by Kyle E try it.
<?php
/*
//Author Kyle E Gentile
//To use this class you must first include the file.
//After including the file, you need to create an options array. For example:
$options = array(
'query_vars' => array('var1', 'var2'),
'rules' => array('(.+?)/(.+?)/(.+?)/?$' => 'index.php?pagename=$matches[1]&var1=$matches[2]&var2=$matches[3]')
);
//After creating our $option array,
//we will need to create a new instance of the class as below:
$rewrite = new Add_rewrite_rules($options);
//You must pass the options array, this way. (If you don't there could be problems)
//Then you can call the filters and action functions as below:
add_action('wp_head', array(&$rewrite, 'flush_rules'));
add_action( 'generate_rewrite_rules', array(&$rewrite, 'add_rewrite_rules') );
add_filter( 'query_vars', array(&$rewrite, 'add_query_vars') );
//That is it.
*/
//prevent duplicate loading of the class if you are using this in multiply plugins
if(!class_exists('add_rewrite_rules')){
class Add_rewrite_rules{
var $query_vars;
var $rules;
function __construct($options){
$this->init($options);
}
function init($options){
foreach($options as $key => $value){
$this->$key = $value;
}
}
function rules_exist(){
global $wp_rewrite;
$has_rules = TRUE;
foreach($this->rules as $key => $value){
if(!in_array($value, $wp_rewrite->rules)){
$has_rules = FALSE;
}
}
return $has_rules;
}
//to be used add_action with the hook 'wp_head'
//flushing rewrite rules is labor intense so we better test to see if our rules exist first
//if the rules don't exist flush its like after a night of drinking
function flush_rules(){
global $wp_rewrite;
if(!$this->rules_exist()){
//echo "flushed"; // If want to see this in action uncomment this line and remove this text and you will see it flushed before your eyes
$wp_rewrite->flush_rules();
}
}
//filter function to be used with add_filter() with the hook "query_vars"
function add_query_vars($query_vars){
foreach($this->query_vars as $var){
$query_vars[] = $var;
}
return $query_vars;
}
//to be used with a the add_action() with the hook "generate_rewrite_rules"
function add_rewrite_rules(){
global $wp_rewrite;
$wp_rewrite->rules = $this->rules + $wp_rewrite->rules;
}
}
}
?>
Add the following function to the init of your plugin / functions file.
public function rewriteRules()
{
//Add the query variables to the list so wordpress doesn't discard them or worse use them to try and find by itself what page to serve.
$options = array(
'query_vars' => array('trainingid', 'vakname'),
'rules' =>
array( 'uncategorized/vak/([^/]+)/([^/]+)/?$' => 'index.php?p=1316&vakname=$matches[1]&level=$matches[2]'
)
);
//I use a autoloader but if you don't you have to include the class.
//include_once('path/to/AddRewriteRules.php');
$rewrite = new AddRewriteRules($options);
add_action('wp_head', array(&$rewrite, 'flush_rules'));
add_action('generate_rewrite_rules', array(&$rewrite, 'add_rewrite_rules'));
add_filter('query_vars', array(&$rewrite, 'add_query_vars'));
}

Removing Content with wp_delete_post in a Plugin with Custom Post Type

I set up a plugin that adds a custom post type and then brings in a bunch of dummy content with wp_insert_post on activation like so:
register_activation_hook( __FILE__, array( $this, 'activate' ) );
public function activate( $network_wide ) {
include 'dummycontent.php';
foreach ($add_posts_array as $post){
wp_insert_post( $post );
};
} // end activate
I would like to remove this content when the plugin is deactivated so I set up this function:
register_deactivation_hook( __FILE__, array( $this, 'deactivate' ) );
public function deactivate( $network_wide ) {
include 'dummycontent.php';
foreach($remove_posts_array as $array){
$page_name = $array["post_title"];
global $wpdb;
$page_name_id = $wpdb->get_results("SELECT ID FROM " . $wpdb->base_prefix . "posts WHERE post_title = '". $page_name ."'");
foreach($page_name_id as $page_name_id){
$page_name_id = $page_name_id->ID;
wp_delete_post( $page_name_id, true );
};
};
} // end deactivate
It works just fine. Except because the custom post type is created with the same plugin that these two functions are run through, the post type is removed before the posts themselves can be through wp_delete_post. When I test these functions out without the custom post type posts are added upon activation and removed upon deactivation. So I know the problem is with the post type. Does anyone know how to work around this?
Try something like this (YOUTPOSTTYPE is the name of your post type):
function deactivate () {
$args = array (
'post_type' => 'YOURPOSTTYPE',
'nopaging' => true
);
$query = new WP_Query ($args);
while ($query->have_posts ()) {
$query->the_post ();
$id = get_the_ID ();
wp_delete_post ($id, true);
}
wp_reset_postdata ();
}
It works in my plugin, it should works in your's. (This has been tested with WordPress 3.5.1).
wp_delete_post($ID, false) sends it to Trash. Only when you remove from Trash is a post really deleted. That's why it works with $force = true.
So it works as expected. First posts go to Trash, then they get actually deleted. Like Recycle Bin. Trace the post_status change to see when it hits the Trash if you want to do anything then. Otherwise wait for the delete.
Also delete content on uninstall and not on deactivate. Consider deactivating a plugin as pausing it and uninstalling it when you really want it gone.
Try this Function
function deactivate () {
$args = array(
'post_type' => 'POST_TYPE',
'posts_per_page' => - 1
);
if ( $posts = get_posts( $args ) ) {
foreach ( $posts as $post ) {
wp_delete_post( $post->ID, true );
}
}
}

How can I automatically assign categories for my custom posts in wordpress?

I want to do this so I can simply use the category as a link in my menu to see all posts of that category.
I have found this forum thread on this subject but I don't understand it.
It has the following solution:
function add_category_automatically($post_ID) {
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
$category = array (4);
wp_set_object_terms( $post_ID, $category, 'category');
}
}
add_action('publish_houses', 'add_category_automatically');
But I'm not sure what to put in the add_action function instead of publish_houses and what should go in $post_id. I had hope to assign it in my functions.php file where I create my custom post type.
Ok, I have changed my code to:
function add_category_automatically($post_ID) {
global $wpdb;
if(!wp_is_post_revision($post_ID) && get_post_type($post_ID) == "offered") {
$category = array (7);
wp_set_object_terms( $post_ID, $category, 'category');
}
}
add_action('publish_post', 'add_category_automatically');
Updated function:
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
$category = array (7);
wp_set_object_terms( $post_ID, $category, 'category');
}
}
add_action('publish_offered', 'add_category_automatically');
(Replaced my previous answer with a better one.)
If your custom post type is called offered you could just replace publish_houses with publish_offered and put the original publish_category_automatically function, and the add_action line, in your functions.php file.

Resources