How to override some function in wordpress - php

I have my wordpress setup on IIS and it is rewritten. Because of that I found some probably bug in wordpress in wp_includes/canonical.php file.
I think that when I update my wordpress that all my changes will disapear. I can't wait for wordpress fix this (I don't even know if it is bug or how to report one) because that "bug" causes my homepage to go in redirect loop.
I made some change in redirect_canonical function in that file specificly this change:
function redirect_canonical( $requested_url = null, $do_redirect = true ) {
///some other code
if ( ! $requested_url && isset( $_SERVER['HTTP_HOST'] ) ) {
// build the URL in the address bar
$requested_url = is_ssl() ? 'https://' : 'http://';
//$requested_url=$_SERVER['HTTP_HOST'] //I deleted this because my URL is rewritten
$asParts = parse_url( $sURL ); // PHP function
$requested_url .= $asParts['host'] ;
$requested_url .= $_SERVER['REQUEST_URI'];
How to make this change resistant to wordpress updates?

WordPress have the hooks concept to change the core functions and process. All hooks are defined via apply_filters and do_action. The hooks are different in filter apply_filters and action - do_action.
You should read about: https://codex.wordpress.org/Plugin_API/Hooks
You should never change the core, because maintenance, function and more. In your example function redirect_canonical have also hooks, like redirect_canonical (Doku) (in source). However it give much more and it is in depends on your goal, requirements.
As small example to change the return value of the function via the filter hook see the code example below.
add_filter( 'redirect_canonical', function ( $redirect_url, $requested_url ) {
// I don't know what is the var $sURL in your code.
$requested_url = parse_url( $sURL );
// Leave here the logic to change the result for $redirect_url.
return $redirect_url;
}, 10, 2 );

Related

How does one determine which page is currently being edited using WordPress inbuilt functionality?

I have written a module into my WordPress theme, its overly complicated and irrelevant.
I need to include a block of code and want a reliable way to determine if the user is currently editing specific pages.
Essentially, I want the equivalent of the front-end check:
if (is_front_page()) {
But, for when on the editor pages.
It is required to be able to target pages that are not given special names like front-page / shop-page too. So I may need to target by post ID.
What is the cleanest way to perform this check?
I have tried the function above, along with:
$screen = get_current_screen();
However, this forces a critical error:
Fatal error: Uncaught Error: Call to undefined function get_current_screen() in ... points to line.
A couple other methods have also been attempted, I just note a few. I thought I would be able to get one to work but none seem to do the trick. Please can someone point me in the right direction?
EDIT
Adding example snippet
// This creates the fatal error.
// $screen = get_current_screen();
// var_dump($screen);
// This is for the front-end
// if (is_front_page()) {
// global $pagenow;
// var_dump($pagenow);
// if ($pagenow == 'post.php') {
// This returns string(8) "post.php" which is not descript enough.
// This is front-end
// global $post;
// $post_id = $post->ID;
// Post ID 3887 is Home
if ($post_id == '3887') {
echo 'hello!';
require_once('inc/overlays/page-template/fc-front-page.php');
} else {
echo 'Well that did not work!';
}
The reason I am doing this is irrelevant, I simply want to include a file in a different folder, the file called will be different depending on which page is currently being edited!
get_current_screen() is only valid on admin pages.
The WP_Screen object is set after the admin_init action hook via the current_screen action hook. You can refer to the Plugin API/Action Reference and the Actions Run During a Typical Request for the firing hook sequence.
To make sure the WP_Screen object is firing, you can use the following function. It will output the screen object as a html commentary on admin pages that support it.
add_action( 'current_screen', 'print_r_get_current_screen' );
if ( ! function_exists( 'print_r_get_current_screen' ) ) {
function print_r_get_current_screen() {
echo PHP_EOL . '<!--' . PHP_EOL;
print_r( get_current_screen() );
echo PHP_EOL . '-->' . PHP_EOL;
};
};
But I don't think using the current screen will help you in achieving what you're trying to do.
You can use get_option( 'page_on_front' ); to get the id of the front page.
add_action( 'init', 'print_r_get_option_page_on_front' );
if ( ! function_exists( 'print_r_get_option_page_on_front' ) ) {
function print_r_get_option_page_on_front() {
echo PHP_EOL . '<!--' . PHP_EOL;
print_r( get_option( 'page_on_front' ) ); //... 0 if undefined, page ID if defined
echo PHP_EOL . '-->' . PHP_EOL;
};
};
For woocommerce I'm pretty sure you can use woocommerce_get_page_id( 'shop' ).

Implementing simple dynamic routes in Wordpress

Suppose I have a clean wordpress install, with a basic custom theme.
In that theme, I have a custom page template which is just an iframe, which is pointed at a webapp on a different domain.
So suppose my wordpress install can be reached at http://example.com, and my page with the iframe template is located at http://example.com/members/.
I now want to add dynamic routes, so that all requests to http://example.com/members/login, or http://example.com/members/event/1 (for example) all go to http://example.com/members/ but pass the second part of the route ('/login', or '/event/1') to the iframe inside.
What would be the best way to accomplish this, without having to hack into Wordpress' internals?
I found this plugin: https://wordpress.org/plugins/wp-on-routes/ but much to my dismay I discovered that when I tried using it it completely overwrites Wordpress' built in routing, which meant I would have to manually re-add each and every URL (as I understand it, I'm not that accomplished in PHP), which is a no go as my client still needs to be able to post without manually editing php files.
Thank you for reading.
You can add routing using the add_rewrite_rule hook like so:
function custom_rewrite_rule() {
add_rewrite_rule('members/([^/]+)/([^/]+)/?$',
'index.php?memberspage=$matches[1]&event_id=$matches[2]',
'top');
}
add_action('init', 'custom_rewrite_rule', 10, 0);
You may need to create several depending on the URLs you rewriting. You can then use the URL parameters in your template to load the appropriate page in your iframe.
I managed to find a solution for my problem, thanks to Fencer04's suggestion. I found this page: https://developer.wordpress.org/reference/functions/add_rewrite_rule/ where I found an example that was close enough to my problem to work.
So in functions.php:
function custom_rewrite_rule(){
$page_id = 318; // replace this ID with the page with the iFrame template
$page_data = get_post($page_id);
if(!is_object($page_data)){
return; // all other pages don't have to support custom deeplinks
}
// catches deeplinks 1 level deep, i.e.: /members/profile
add_rewrite_rule(
$page_data->post_name . '/([^/]+)/?$',
'index.php?pagename=' . $page_data->post_name . '&memberspage=$matches[1]',
'top'
);
// catches deeplinks 2 levels deep, i.e.: /members/profile/edit
add_rewrite_rule(
$page_data->post_name . '/([^/]+)/([^/]+)/?$',
'index.php?pagename=' . $page_data->post_name . '&memberspage=$matches[1]&members_param=$matches[2]',
'top'
);
// catches 3 levels deep, i.e. /members/profile/edit/confirm
add_rewrite_rule(
$page_data->post_name . '/([^/]+)/([^/]+)/([^/]+)/?$',
'index.php?pagename=' . $page_data->post_name . '&memberspage=$matches[1]&members_param=$matches[2]&members_param2=$matches[3]',
'top'
);
}
add_action('init', custom_rewrite_rule);
Next I added filters for the new query_vars:
add_filter('query_vars', function($vars) {
$vars[] = "memberspage";
$vars[] = "members_param";
$vars[] = "members_param2";
return $vars;
});
And then in my template-iframe.php, I can access these parameters like so:
<?php
// get query strings
global $wp_query;
$page = $wp_query->query_vars['memberspage'];
$params = $wp_query->query_vars['members_param'];
$params2 = $wp_query->query_vars['members_param2'];
$membersBaseURL = 'http://members.domain.com/';
$iframeURL = $membersBaseURL;
if(isset($page)){
$iframeURL = $iframeURL . $page . '/';
}
if(isset($params)){
$iframeURL = $iframeURL . $params . '/';
}
if(isset($params2)){
$iframeURL = $iframeURL . $params2 . '/';
}
?>
<iframe id="iframeLeden" src="<?php echo($iframeURL) ?>" frameborder="0"></iframe>
So now if I go to http://www.domain.com/members/login, it'll show me the correct static WP page, with inside an iframe that shows the page http://members.domain.com/login/ .

Open Graph Meta Tag Overwritting Yoast, WordPress

I'm trying to change the og:url content on specific posts but I am unsure how to implement my changes from the functions.php file.
I have tried doing this using the content I have found on the internet but believe it has been updated since then.
I have updated the class-opengraph.php file in the the wordress-seo plugin folder which works, please find my edits below:
public function url() {
$url = apply_filters('wpseo_opengraph_url',
WPSEO_Frontend::get_instance()->canonical(false));
if (is_string($url) && $url !== '' ) {
if (is_page(32721)) {
$this->og_tag('og:url', esc_url('testing'));
} else {
$this->og_tag( 'og:url', esc_url( $url ) );
}
return true;
}
return false;
}
It's not good to modify the plugin files directly because when you update the plugin, you will lose all your changes to those files.
There are two solutions that I have found to do such thing.
You get the instance of the class WPSEO_Frontend, then update it's options for the og:url.
e.g.
$object = WPSEO_Frontend::get_instance();
$object->options['og_url'] = esc_url( $url );
This can be added before the wp_head()
You can use add_filter to hook a function to the filter action. We use the filter action below.
Filter: 'wpseo_opengraph_url' - Allow changing the OpenGraph URL
e.g.
function update_og_url($url) {
return "http://www.yoursampleurl.com";
}
add_filter('wpseo_opengraph_url', 'update_og_url', 10, 1);
Source: Wordpress SEO API

Where to declare the wp_rewrite codes? wp_rewrite issues

I have a question regarding wp_rewrite, It doesn't display correctly,
I need to make this url
eduedu/wp-content/plugins/workwork/admin/templates/tcpdf/samp/flash.php
to
eduedu/generator
It works when using .htaccess, the problem is, that It doesnt work when place inside the plugin folder, the htaccess must be place in the root folder of wordpress. So I thought of using wp_rewrite.
Here is my code, I added this on the page when in it will redirect to
eduedu/wp-content/plugins/workwork/admin/templates/tcpdf/samp/flash.php
I'm not sure if its correct, any idea?
add_action('generate_rewrite_rules', 'cs_rewrite_rules');
add_filter('init', 'eduFlush');
function cs_rewrite_rules() {
global $wp_rewrite;
$new_non_wp_rules = array(
'^generator/?$' => 'eduedu/wp-content/plugins/workwork/admin/templates/tcpdf/samp/flash.php',
);
$wp_rewrite->non_wp_rules += $new_non_wp_rules;
}
function eduFlush(){
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
Maybe something along these lines would help:
function site_router() {
global $url_array;
$url_array = explode("/",$_SERVER['REQUEST_URI']);
$route = $url_array[1];
$template_dir = 'wp-content/plugins/workwork/admin/templates/tcpdf';
switch($route) {
case 'generator':
load_template($template_dir.'/samp/flash.php');
die();
break;
}
}
add_action( 'send_headers', 'site_router');
It gets the current URL array (domain.com/url_array[1]), then it gets where you want to get the file from.
The switch gets the url, so domain.com/generator, and then loads in the template from the file you call.
You may need to change the url_array[1] to [2] if wordpress is in a sub-folder (domain.com/wp_root)

How to combine / integrate CodeIgniter and Wordpress blogs functionality?

My website having feature requirement of blogging. I have to make blog which would look same like my website appearance.
How to combine CodeIgniter and Wordpress blogging(only) functionality such that it should look like within same website?
I have seen this question: Wordpress template with codeigniter. But didn't got much clue.
Seems like a bit of overkill.
Why not use a Restful service like json_api to retrieve your posts, then copy over the css file(parts)?
You do this you will need to create 2 files and modify 2 existing functions. One function is in CodeIgniter and the other is in Wordpress.
Here are the steps.
1.) Open your configs/hooks.php file and create a pre_controller hook as follows:
$hook['pre_controller'] = array(
'class' => '',
'function' => 'wp_init',
'filename' => 'wordpress_helper.php',
'filepath' => 'helpers'
);
2.) Create a new file in your helpers directory called 'wordpress_helper.php', and add the following code to it:
/**
*
*/
function wp_init(){
$CI =& get_instance();
$do_blog = TRUE; // this can be a function call to determine whether to load CI or WP
/* here we check whether to do the blog and also we make sure this is a
front-end index call so it does not interfere with other CI modules.
*/
if($do_blog
&& ($CI->router->class == "index" && $CI->router->method == "index")
)
{
// these Wordpress variables need to be globalized because this is a function here eh!
global $post, $q_config, $wp;
global $wp_rewrite, $wp_query, $wp_the_query;
global $allowedentitynames;
global $qs_openssl_functions_used; // this one is needed for qtranslate
// this can be used to help run CI code within Wordpress.
define("CIWORDPRESSED", TRUE);
require_once './wp-load.php';
define('WP_USE_THEMES', true);
// Loads the WordPress Environment and Template
require('./wp-blog-header.php');
// were done. No need to load any more CI stuff.
die();
}
}
3.) Open wp-includes/link-template.php and made the following edit:
if ( ! function_exists('site_url'))
{
function site_url( $path = '', $scheme = null ) {
return get_site_url( null, $path, $scheme );
}
}
4.) Copy url_helper.php from the CodeIgniter helper folder to your APPPATH helper folder
and make the following edit:
if ( ! function_exists('site_url'))
{
function site_url($uri = '', $scheme = null)
{
// if we are in wordpress mode, do the wordpress thingy
if(defined('CIWORDPRESSED') && CIWORDPRESSED){
return get_site_url( null, $path, $scheme );
}else{
$CI =& get_instance();
return $CI->config->site_url($uri);
}
}
}
The steps above will allow you to dynamically load either your CI app or your WP site based on some simple filtering. It also gives you access to all CI functionality within WP of that is something you can use.

Categories