Wordpress, redirect a user directly to a custom post edit screen after login - redirect

currently I got this:
function redirect_companies()
{
if ( current_user_can( 'ca_company' ) )
{
$screen = get_current_screen();
if ( $screen->post_type != 'unternehmen' && $screen->id != 'profile' )
{
global $current_user;
$current_users_posts = get_posts(
array(
'post_type' => 'unternehmen',
'author' => $current_user->ID
)
);
if ( count( $current_users_posts ) > 1 )
{
$redirect = admin_url( 'edit.php?post_type=unternehmen' );
}
else
{
$redirect = get_edit_post_link( $current_users_posts[0]->ID );
}
wp_redirect( $redirect, 301 );
}
}
}
add_action('current_screen', 'redirect_companies');
What it should do: A user with role 'ca_company' logs into wordpress backend and instantly gets redirected to either the overview screen of the custom post type posts of "unternehmen" or, if only one post by this user exists, to the edit screen of that one post.
Also, it should perform this redirect routine, if the user is trying to access any page that is not from post type "unternehmen" and is not the user-profile-edit screen.
I successfully tested this when I already was logged in as auch user and then trying to access for example the dashboard. This works.
But if I completely log out of WP and then log in again, wordpress is performing this:
http://i.stack.imgur.com/M60aJ.png
... and then my browser is telling me, that there is a redirecting error. Infinite redirecting loop. But why? Why does it even go into that "if" where I check for post type "unternehmen". Because if I log in, I am first getting to dashboard...
Hope someone can help :)

Use this action 'add_action('wp_login', 'do_anything');'. And in callback function you can give link to wp_redirect('link') where you want to redirect your screen.

Related

wp_redirect() function caused endless loading/spinner on WooCommerce Checkout

I added wp_redirect() function for logged-in user. Because I want to show them a special page when they logged in.
/*
* Logged-in user redirection for special page.
*/
function login_redirection(){
if ( is_user_logged_in() && is_page(65309)) {
wp_redirect('welcome-page/');
exit;
}
}
add_action('wp', 'login_redirection');
/**
* when users logged-out, redirect them to login page
*/
add_action(
'wp_logout',
create_function(
'',
'wp_redirect(home_url("/login-page"));exit();'
)
);
But this code caused endless loading/spinner on the WooCommerce Checkout page.
How can I solve this issue?
I need help with this.
Sometimes the solution is in front of your eyes
add_action(
'wp_login',
create_function(
'',
'wp_redirect(home_url("/welcome-page"));exit();'
)
);

Yii2 Redirect to previous page after update

I have a application where after update user should be redirected to previous page from pagination.
let's say there is a gridview and user is at page 3. Then he update some record at that page. There should be a redirect to index page 3. What if, while user is updating record, before save, he opens another controller/action in new tab. Then ReturnUrl is now that new action and after save the record he is updating, he is redirected to that new url.
I've tried to set in every action "index" Url::remember(); and then in action "update" - return $this->goBack().
Also return $this->redirect(Yii::$app->request->referrer);, but it stays at same page.
There is a way to store every index URL in session, but in large project that means many sessions.
You could provide the returnUrl to the link, say:
Url::to(['update','id'=>$model->url,'returnUrl'=> Yii::$app->request->url]);
Then in your controller, use $this->request->queryParams['returnUrl'] to redirect to the previousUrl.
To take it one step further, to always provide the returnUrl, you could extend the Url Helper class:
namespace app\helpers;
use yii\helpers;
class Url extends yii\helpers\Url
public function toRouteAndReturn($route, array $params = [], $scheme = false) {
$params['returnUrl'] = Yii::$app->request->url;
return parent::toRoute($route,$params,$scheme);
}
You could provide in your main config:
'on afterAction' => function($event) {
if(!Yii::$app->getResponse()->isSent && !empty(Yii::$app->getRequest()->queryParams['returnUrl']) {
Yii::$app->getResponse()->redirect(Yii::$app->getRequest()->queryParams['returnUrl']);
}
}
Then you could use app\helpers\Url::toRouteAndReturn() instead of yii\helpers\Url::toRoute() to have it return to the previous url.
You can try below Solution.
First in your index page, get current page url and encode it.
$current_url=base64_encode(\Yii::$app->request->getUrl());
Append this url with your update link as below.
'urlCreator' => function ($action, $model, $key, $index) use ($current_url) {
if ($action === 'update') {
$url = Yii::$app->request->baseUrl . '/controllerName/update?id=' . $model->id.'&prev='.$current_url;
return $url;
}
// ......
}
In Controller, in Update method decode url as below and use for redirection.
public function actionUpdate($id)
{
$model = $this->findModel($id);
$prev=base64_decode($_REQUEST['prev']);
// ......
return $this->redirect($prev); // you will redirect from where update method is called
// ......
}
Isn't it quite easy to pass page param into your update url (<model/update>) like <model>/update?id=<id>&page=<page>?
in your index.php view, edit your ActionColumn as follow:
[
'class' => 'yii\grid\ActionColumn',
'urlCreator' => function ($action, $model, $key, $index) {
return \yii\helpers\Url::to([$action, 'id' => $model->id, 'page' => Yii::$app->request->getQueryParam('page', null)]);
},
],
As you can see, I'm getting page param from request url and pass it to models' action buttons
And when you click to update model, the page that we entered from is stored/placed in url.
Controller:
public function actionUpdate($id, $page = null)
{
$model = $this->findModel($id);
...
if($model->save()) {
return $this->redirect(['index', 'page' => $page]);
}
...
}
Finally, after we successfully update the model, the action redirects us to previous index page.

Facebook Real Time Subscriptions Throws Exception Even when challenge is answered

I'm trying to subscribe from my app to Real Time Subscription of Facebook using v2.4 Graph API (after creating a callback function in fbcallback.php) using the code below from my index.php page (the appid and IP address obviously fake in this post):
try {
$response=$fb->sendRequest('POST','/1111/subscriptions',
array(
'object' => 'user',
'callback_url' => 'http://111.111.111.111/fbcallback.php',
'fields' => 'first_name',
'verify_token' => 'thisisaverifystringtestuser',
)
);
$graphNode = $response->getGraphNode();
}catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "exception:" . $e->getMessage(); }
While i'm sure from callback log that Facebook reaches my callback function and i use in it the code below:
<?php
define('VERIFY_TOKEN', 'thisisaverifystringtestuser');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' &&
$_GET['hub_verify_token'] == VERIFY_TOKEN) {
echo $_GET['hub_challenge'];
}
?>
i get the Message from my index page code looking like this:
exception:(#2201) response does not match challenge, expected value = '866531638', received='866531638'
Anyone encountered it?
P.S I created a test user from the app dashboard roles and configured him to subscribe to app on creation and also got (but not used) an access token for this user from dashboard also.....since i can't denote a specific user during the subscription proccess from my php code i expect (or wish) this user to be subscribed by my php code...am i wrong?
Looks like your script outputs more than just the hub_challenge value.
When I copy&paste the error message from your posting, and insert it in NotePad++, I get that part shown as
received='?866531638'
^
– so there seems to be some invisible/not display-able character before the actual value.
Make sure your script is saved as UTF-8 without BOM, and that it does not make any other output besides the hub_challenge value either. (That could include stuff outside of <?php … ?> tags as well.)

Force user to allow facebook permissions using Graph API

I developed Facebook application and I have some problems on "Allow access step",In initial stage user must authorize app and permissions.Currently if users skip extended permissions also landing to application home page , But I need to force user to accept all permissions, I got success when using FQL method , Now its not working , I cant find out the solution. Here is my code
$TotalPermissions = UserAndFriendsPermissions();
return true;
$tp = substr_replace($TotalPermissions ,"",-1);
$this->loadClassFile("Facebook", MAIN_PLUGIN_PATH."Common/facebook/facebook.php");
$facebook = new Facebook(array('appId' => $FBConnect["fb_app_id"],'secret' => $FBConnect["fb_secret_key"],));
$params = array('method' => 'fql.query','query' => "SELECT ".$tp." FROM permissions WHERE uid=me()");
$result = $facebook->api($params);
$totalp = count(explode(",",$tp));
$ap=0;
foreach ($result[0] as $key => $val)
{
if($val==1)
{
$ap++;
}
}
if($ap==$totalp)
{
return true;
}
else
{
?>
<?php
Redirect("https://apps.facebook.com/APP_NAMESPACE");
}
You cannot force users to accept all your extended permissions. What you can do is to check for permissions given and handle those cases accordingly i.e. redirecting users who have not given permission to a landing page which explains why you need those permissions.

Need help with routing in Mojolicious

I have the "Pages" controller with the "show" method and "Auths" controller with the "check" method which returns 1 if user is authenticated.
I have "default" page ("/profile").
I need to redirect to / if the user is authenticated and redirect all pages to / with the authorization form if the user is not authenticated. My code does not want to work properly (auth based on the FastNotes example application): (
auths#create_form - html-template with the authorization form.
$r->route('/') ->to('auths#create_form') ->name('auths_create_form');
$r->route('/login') ->to('auths#create') ->name('auths_create');
$r->route('/logout') ->to('auths#delete') ->name('auths_delete');
$r->route('/signup') ->via('get') ->to('users#create_form') ->name('users_create_form');
$r->route('/signup') ->via('post') ->to('users#create') ->name('users_create');
#$r->route('/profile') ->via('get') ->to('pages#show', id => 'profile') ->name('pages_profile');
my $rn = $r->bridge('/')->to('auths#check');
$rn->route ->to('pages#show', id => 'profile') ->name('pages_profile');
$rn->route('/core/:controller/:action/:id')
->to(controller => 'pages',
action => 'show',
id => 'profile')
->name('pages_profile');
# Route to the default page controller
$r->route('/(*id)')->to('pages#show')->name('pages_show');
It seems you want / to render either a login form OR a profile page. The code above will always show / as login because it hits that route condition first and will never care if you're authenticated or not.
Try a switch in your initial route for / (your default route after the bridge is unnecessary).
my $r = $self->routes;
$r->get('/' => sub {
my $self = shift;
# Check whatever you set during authentication
my $template = $self->session('user') ? '/profile' : '/login';
$self->render( template => $template );
});
A couple of notes on your example:
Its much easier to help debug issues if you use Mojolicious::Lite for examples.
Try using under instead of bridge.
Try using $r->get(..) instead of $r->route(..)->via(..)
Hope this helps.