WordPress Redirect Login/Logout - wordpress

I have a script that adds a login to the menu. But after logged in it does not redirect correctly. I want to redirect after the log in to the page before the login page.
function sv_get_logout_redirect_url() {
$badurls = array('submit-form', 'dashboard', 'profile', 'guidelines');
$current_url = get_permalink();
$isgood = true;
foreach ($badurls as $bad) {
$pos = strpos($current_url,$bad);
if (! $pos === false) {
$isgood = false;
break; // no need to check any more "bads"
}
}
if ($isgood) {
return wp_logout_url(get_permalink());
} else {
return wp_logout_url(home_url());
}
}
add_filter( 'wp_nav_menu_items', 'sv_add_usermenu', 10, 2 );
function sv_add_usermenu( $items, $args ) {
global $current_user;
if (is_user_logged_in() && $args->theme_location == 'primary-menu') {
// menu items for logged in user
$guidelines_url = site_url() . '/guidelines/';
$dashboard_url = site_url() . '/dashboard/' . $current_user->user_nicename;
$profile_url = site_url() . '/profile/' . $current_user->user_nicename;
// http://fortawesome.github.com/Font-Awesome/
// some fontawesome names icon-arrow-down, icon-chevron-down, icon-caret-down
$items .= "<li class='menu-item'><a href='#'>$current_user->display_name <span class='icon-caret-down'> </span> </a>";
//$items .= "<li class='menu-item'><a href='#'>$current_user->display_name</a>";
$items .= "<ul>";
$items .= "<li class='sub-menu'><a href='$guidelines_url'>Usage Guidelines</a></li>";
$items .= "<li class='sub-menu'><a href='$dashboard_url'>My Dashboard</a></li>";
$items .= "<li class='sub-menu'><a href='$profile_url'>My Profile</a></li>";
$items .= "<li class='sub-menu'><a href='" . sv_get_logout_redirect_url() . "'>Uitloggen</a></li>";
$items .= "</ul>";
$items .= "</li>";
} elseif (!is_user_logged_in() && $args->theme_location == 'primary-menu') {
//menu items for NOT logged in user
//$login_url = site_url('/a-page-name/'); // get login url and redirect to a specific page
//$login_url = wp_login_url( home_url() ); // get login url and redirect to home page
$login_url = wp_login_url( get_permalink() ); // get login url and redirect to current page
//the contents of <a href"" must be a url
$items .= "<li class='sub-menu'> <a href='$login_url' class='simplemodal-login'>Log In</a></li>";
}
return $items;
}
I hope someone can help me! Thanks.

So if I understand you correctly somebody might be on the homepage and then click "login" from the menu and the login page appears. if at some time the user decides to logout again he should be returned to the home page (because this was the page he was on before he went to the login page).
If this is the case you should look into $_SERVER and $_SESSION variables in PHP. To be a bit more precise take a look at the $_SEVER['HTTP_REFERER'] variable which holds the address of the page (if any) which referred the user agent to the current page.
The official documentation is located here: http://php.net/manual/en/reserved.variables.server.php
Because you need this url for a longer period of time you should to store it inside session that you can call upon when the user want's to logout.
There is small downside to this solution though, what happens if the administrator of your WordPress site changes the permalink of the page the user was one before he tried to login? Then the url you stored from $_SEVER['HTTP_REFERER'] is incorrect and will result in a 404 page. But the likelihood of this happening is very small so hopefully this solution helps you with your problem.

Related

User email address into menu link in WordPress

I'm trying to create a menu link within my WordPress site that pulls the logged in user's email address into the URL. For example, if the user is logged in as john#doe.com, I want their menu link to be https://example.com/?email=john#doe.com, whereas jane#smith.com would be https://example.com/?email=jane#smith.com.
Is something like this possible?
Here's how you can do this.
Find out the name of the menu you're trying to add into
Add this code snippet into your functions.php
Note: You'll need to update the third line "primary" value to the name of the menu you're adding into
<?php
add_filter( 'wp_nav_menu_items', 'your_custom_menu_item', 10, 2 );
function your_custom_menu_item ( $items, $args ) {
if ( $args->theme_location == 'primary') {
$link = "https://example.com/";
if ( is_user_logged_in() ) {
$user_id = get_current_user_id();
$user_info = get_userdata($user_id);
$link .= "?email=" . $user_info->user_email;
}
$items .= '<li>Custom Text</li>';
}
return $items;
}
?>

How to add active class for current item and ancestor in new WooCommerce Product Categories List Block widget?

I am using a Product Categories List Block to list all product categories in sidebar in shop and category pages (like filters). I am listing categories in my site by using a wordpress Widget. Categories are shown but there is no active class for current category or ancestor category. How to make it that if user is on current category, the li item will get current-cat class and ancestor current-ancestor class?
HTML STRUCTURE OF WIDGET
I needed to solve this myself, so here is my current solution.
Since there is currently no filter available for the default WooCommerce blocks, I solved it using PHP's DOMDocument parser while rendering the block.
You can add a filter to render_block to catch the html for the specific block, in this case the block name is woocommerce/product-categories. By adding checks for non-admin & non-json requests we make sure the changes only happen on the front-end output.
If you add the code below to your theme's functions.php, a class current-category-item is added to the list item that matches the current url.
function custom_render_block_wc_product_categories(string $block_content, array $block): string
{
if(
$block['blockName'] !== 'woocommerce/product-categories'
|| is_admin()
|| wp_is_json_request()
) {
return $block_content;
}
$html = '';
global $wp;
$current_slug = trim($wp->request,'/');
$dom = new DOMDocument();
$dom->loadHTML($block_content);
$elements = $dom->getElementsByTagName('a');
if( $elements['length'] ){
foreach ($elements as $node){
$href = parse_url($node->getAttribute('href'));
$path = trim($href['path'], '/');
if( $path === $current_slug ){
$class = $node->parentNode->getAttribute('class');
$class .= ' current-category-item';
$node->parentNode->setAttribute('class', $class);
break;
}
}
}
$html .= "<div class='block-outer-wrapper'>";
$html .= "<header><h4>" . __('Categories','woocommerce') . "</h4></header>";
$html .= $dom->saveHTML();
$html .= "</div>";
return $html;
}
add_filter('render_block', 'custom_render_block_wc_product_categories', 10, 2);
I also added a header to the block, but these lines are optional as long as you return $dom->saveHTML() after your changes.

The Devel module query log doesn't appear in a custom theme

The Devel module query log appears correctly (at the bottom of the page) when I use one of the default themes, but not when I switch to my custom theme. The query log seems to appear within the inner pages in the custom theme, though not the front page or administrator pages (if those are set to use the custom theme).
I have been through page.tpl.php and html.tpl.php and I can't see any missing variables.
How does the query log get printed on the page?
STEP 1:
Check in your template.php you can find the next hooks. If it doesnt exists, create it.
function YOURTHEME_preprocess_node(&$variables) {
$variables['messages'] = theme('status_messages');
}
function YOUTRHEME_status_messages($variables) {
$m = drupal_get_messages();
foreach ($m as $type => $messages) {
if (count($messages) > 0) {
$output .= "<div class=\"messages\">";
$output .= " <ul>";
foreach ($messages as $key => $message) {
if (count($messages) > 0) {
$output .= '<li class="message '.$type.'"><span class="text">'. $message . "</span></li>";
}
}
$output .= " </ul>";
$output .= "</div>";
}
}
return $output;
}
STEP 2
In your template check if var $message is printed. If it doesnt exists, create it.
print $message;

Unable to login from another wordpress site

My A site passes POST data to site B thus must log in the user into site B.
I prefer not to verify password in site B, so I'm using below:
$user = $_POST;
$a = get_user_by('login', $user['data']['user_login']);
do_action('wp_login', $a->data->user_login, $a);
wp_set_current_user( $a->data->ID );
wp_set_auth_cookie( $a->data->ID );
I can get current logged in user like this: wp_get_current_user();.
also when I check is_user_logged_in(), it says true as well.
But when I redirect to site B, the user is not logged in.
One more is that,
when i echo site_url() it says site B url which is correct. BUt when I use wp_safe_redirect or wp_redirect() it goes to site A.
so I use a hack like this:
$string = '<script type="text/javascript">';
$string .= 'window.location = "' . site_url() . '"';
$string .= '</script>';
echo $string;
exit;
What am I doing wrongly here?

How to show recent post in the main domain from subdomain blog

need to show the recent post from my subdomain to my main domain frontend. I am using below code, but its picking only main domain recent post. any help to fetch subdomain recent post ?
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
</ul>
EDIT 2:
So it turns out, that you are not running both sites from the same WordPress installation(otherwise referred to as a WordPress Network). Here is what I can suggest that you use in this case.
Put this code in the main site's functions.php:
/**
* this function retrieves the requested part of the main site
* ok, well basically can be from any site, depending on the $url param, as long as it has the proper function that will display the requested content
* #param $url - the url of the site
* #param $key - part of the name of the function that will display the content
* #param $add_qs - any additional query string that will be appended, use "&params=param1,param2,param3" to pass "param1", "param2" and "param3"
* to the loading function
*/
function get_main_site_part($url, $key, $add_qs = '') {
// cache the result, so we don't make a request with each page load
$cache = ABSPATH . 'wp-content/uploads/main_site_' . $key . '.txt';
$cache_lifetime = 300;
// just to make sure - try to remove the trailing slash in the $url
$url = untrailingslashit($url);
$uri = $url . '/?including_template_part=1&load_part=' . $key . $add_qs;
# reload the cache on every 5 minutes
if (!file_exists($cache) || time() - filemtime($cache) > $cache_lifetime) {
$main_site_html = wp_remote_get($uri);
if (is_a($main_site_html, 'WP_Error')) {
//print_r($main_site_html);
//exit('error! ');
return;
}
$fp = fopen($cache, 'w');
fwrite($fp, $main_site_html);
fclose($fp);
} else {
$main_site_html = file_get_contents($cache);
}
return $main_site_html;
}
Now put this function in your sub-domain's functions.php:
/* HTML LOADING HOOK - For loading content from one site to another - best application in multisite */
function print_requested_template_part() {
// Respond only to requests from the same address...
if ( $_SERVER['REMOTE_ADDR'] == $_SERVER['SERVER_ADDR'] && $_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['including_template_part']) && isset($_GET['load_part']) && $_GET['load_part'] != '' ) {
$part = $_GET['load_part'];
$func = 'render_' . str_replace('-', '_', $part); // if you have declared a function called "render_footer_include", then "?load_part=footer_include"
if ( function_exists($func) ) {
// Allow for passing parameters to the function
if ( isset($_GET['params']) ) {
$params = $_GET['params'];
$params = ( strpos($params, ',') !== false )? explode(',', $params) : array($params);
call_user_func_array($func, $params);
} else {
call_user_func($func);
}
}
exit; // if we don't exit here, a whole page will be printed => bad! it's better to have empty footer than a footer with the whole main site...
}
}
add_action('init', 'print_requested_template_part', 1);
function render_my_recent_posts( $numberposts = 5 ) { ?>
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ) {
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
</ul><?php
}
Then in your main site call this function, where you want your recent posts to appear:
echo get_main_site_part( 'http://questions.admissiontimes.com/', 'my_recent_posts', '&params=5' )
EDIT 1:
Using the sample code that you have in your question, combined with my solution from below, here is what the final code will look like:
<?php
switch_to_blog( 2 ); // Switch to the blog that you want to pull posts from. You can see the ID when you edit a site through the Network Admin - the URL will look something like "http://example.com/wp-admin/network/site-info.php?id=2" - you need the value of "id", in this case "2" ?>
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ) {
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
</ul>
<?php restore_current_blog(); // Restore the current blog ?>
Now, you just put that code wherever you had your original code and everything should be working properly.
You need to switch to the blog in question, using the switch_to_blog($blog_id) function, where $blog_id is the ID of the blog(sub-site) in question.
Then do your normal get_posts/or equivalent/ function and display/store the posts in the way you want.
Once you're done with that, just call restore_current_blog() and that's it.

Resources