1

The original goal is this:
all users can add and remove images from the page on front end, but, they can only see their own images.

When in the admin part of the website, administrators should see all images, from every user. (only administrators have access to the admin part of the website).

So far, I have the following code:

add_action( 'pre_get_posts','users_own_attachments' );
function users_own_attachments( $wp_query_obj ) {
    global $current_user, $pagenow;
    $is_attachment_request = ($wp_query_obj->get('post_type')=='attachment');   
    if( !$is_attachment_request )
        return; 
    if( !is_a( $current_user, 'WP_User') )
        return; 
    if( !in_array( $pagenow, array( 'upload.php', 'admin-ajax.php' ) ) )
        return;
    if(basename(get_page_template()) === 'upload.php')
        return;
    if ( ! is_admin() && $query->is_main_query() ) 
        return;
    $wp_query_obj->set('author', $current_user->ID );   
    return;
}

However, $pagenow always returns admin-ajax.php, no matter on what page it's beeing called, and basename(get_page_template()) always returns only home URL. $wp_query_obj doesn't have any usefull information in it.

How can I check if the user is on upload.php, or on another page on the site?

Thanks.

2
  • Are your users definitely on a page called upload.php? Or is that in reference to a WordPress core file? If your user is on the front end, the page they will be making the request from is unlikely to be the aforementioned unless you have created an upload.php file yourself that is requested directly. Can you elaborate...
    – Adam
    Commented Dec 26, 2019 at 12:04
  • No, users are not on that page. Users can upload images on their profile page, eg: mysite.com/author/admin. They can open media selector I've enabled using javascript. On this page, everyone should see only their own images. But, if an administrator goes to the upload.php page, they should see all images from all users.
    – Bojan
    Commented Dec 26, 2019 at 13:38

1 Answer 1

1

I was searching the internet, and I found out about this

strtolower( wp_get_referer() );

So I was able to place simple if statement and test what page called the admin-ajax.

if (strpos($referrer, 'upload.php') === false) { ... }

2
  • 1
    That's a client-supplied header though, and can be faked by the client, if you're using it for anything security related.
    – Rup
    Commented Dec 28, 2019 at 18:58
  • Thanks for the heads up
    – Bojan
    Commented Jan 1, 2020 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.