WordPress как на ладони

Скрыть от лишних глаз Unattached — Опять ненужные дыры

Гружу на сайт картинки, которые потом вызываю в различных страницах архивов и категорий (картинки не вставлены в посты и старницы) - более картинки нигде не используются и имеют статус Unattached.

на сайте есть файл image.php - он отвечает за вывод изображений, дак вот через него любой пользователь (какой угодно статус - особенно конкурент) может одним разом посмотреть все непрекрепленные\Unattached файлы.

Бывает что на сайт гружу тестовые картинки, бывает лежат загатовки или старые архивные файлы - мне так удобно - так вот гугл и яндекс их на общее обозрение выставляет А ЭТО ПЛОХО

РЕШЕНИЕ (знаний мало, юзаю плагин)

поставил плагин с редиректом Redirect Unattached Images
все хорошо, кроме того что теперь я как ХОЗЯИН не могу смотреть эти станицы, вот я его подкавырнул и код сразу вставил в functions.php

ВОПРОС: правильно ли я решил задачу и может быть есть что-то по лучьше

/**
 * Plugin Name:  Redirect Unattached Images
 * Plugin URI:   http://robneu.com/redirect-unattached-images/
 * Description:  Redirect attachment pages for all unattached images to the current site's home page.
 * Version:      0.1.1
 * Author:       WP Site Care
 * Author URI:   http://www.wpsitecare.com
 * License:      GPL-2.0+
 * License URI:  http://www.gnu.org/licenses/gpl-2.0.html
 *
 * Git URI:           https://github.com/wpsitecare/redirect-unattached-images
 * GitHub Plugin URI: https://github.com/wpsitecare/redirect-unattached-images
 * GitHub Branch:     master
 *
 * @package  RedirectUnattachedImages
 * @category Core
 * @author   Robert Neu
 * @version  0.1.0
 */

// Exit if accessed directly
defined( 'ABSPATH' ) || exit;

add_action( 'template_redirect', 'sitecare_redirect_unattached_images' );
/**
 * Redirects the attachment page for any image which has not been attached to a
 * post, page, or custom post type to the current site's home URL.
 *
 * @since  0.1.0
 * @uses   is_attachment()
 * @uses   get_queried_object()
 * @return void
 */

function sitecare_redirect_unattached_images() {

	$login=0; // добавил я 
	if ( is_user_logged_in() ) { // добавил я 
		$login = 1 ; // добавил я 
	} // добавил я 

	if ( ! is_attachment() || $login == 1) { // добавил я условие или 
		return;
	}
	$parent = get_queried_object()->post_parent;
	if ( ! empty( $parent ) ) {
		return;
	}
	if (  $login == 0 ) { // добавил я 

	wp_safe_redirect(

		esc_url_raw( apply_filters( 'sitecare_redirect_unattached_images', get_home_url() ) ),
		301
	);
	exit;

	}
}
Заметки к вопросу:
campusboy 6.7 лет назад

Покажите код своего image.php

kolshix 6.7 лет назад

свою не покажу - так как под сайт заточена и многое править не хочу, - вот оригинал, пробовал на разных темах, идея автора срабатывает

Кстати пробовал менять тему на twentyfifteen - там тоже невложенные файлы палятся

<?php get_header(); ?>
<div id="page">
	<?php if (of_get_option('promax_latest' ) =='1' ) {load_template(get_template_directory() . '/includes/ltposts.php'); } ?>
	<div id="page-inner" class="clearfix">
		<div id="content"><?php promax_breadcrumbs(); ?>
<?php if(have_posts()) : ?>
<?php while(have_posts())  : the_post(); ?>

<h1><?php the_title(); ?></h1>
<div class="entry" class="clearfix"><?php if (of_get_option('promax_ad2') <> "" ) { echo stripslashes(of_get_option('promax_ad2')); } ?>
<div class="entry-meta">
								<?php
								$metadata = wp_get_attachment_metadata();
								printf( __( '<span class="meta-prep meta-prep-entry-date">Published </span> <span class="entry-date"><time class="entry-date" datetime="%1$s">%2$s</time></span> at <a href="%3$s" title="Link to full-size image">%4$s × %5$s</a> in <a href="%6$s" title="Return to %7$s" rel="gallery">%8$s</a>.', 'promax' ),
									esc_attr( get_the_date( 'c' ) ),
									esc_html( get_the_date() ),
									esc_url( wp_get_attachment_url() ),
									$metadata['width'],
									$metadata['height'],
									esc_url( get_permalink( $post->post_parent ) ),
									esc_attr( strip_tags( get_the_title( $post->post_parent ) ) ),
									get_the_title( $post->post_parent )
								);
							?>
								<?php edit_post_link( __( 'Edit', 'promax' ), '<span class="edit-link">', '</span>' ); ?>
								</div><!-- .entry-meta -->
							<div class="entry-content">

						<div class="entry-attachment">
							<div class="attachment">
<?php
/**
 * Grab the IDs of all the image attachments in a gallery so we can get the URL of the next adjacent image in a gallery,
 * or the first image (if we're looking at the last image in a gallery), or, in a gallery of one, just the link to that image file
 */
$attachments = array_values( get_children( array( 'post_parent' => $post->post_parent, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' ) ) );
foreach ( $attachments as $k => $attachment ) :
	if ( $attachment->ID == $post->ID )
		break;
endforeach;

$k++;
// If there is more than 1 attachment in a gallery
if ( count( $attachments ) > 1 ) :
	if ( isset( $attachments[ $k ] ) ) :
		// get the URL of the next image attachment
		$next_attachment_url = get_attachment_link( $attachments[ $k ]->ID );
	else :
		// or get the URL of the first image attachment
		$next_attachment_url = get_attachment_link( $attachments[ 0 ]->ID );
	endif;
else :
	// or, if there's only 1 image, get the URL of the image
	$next_attachment_url = wp_get_attachment_url();
endif;
?>
								<a href="<?php echo esc_url( $next_attachment_url ); ?>" title="<?php the_title_attribute(); ?>" rel="attachment"><?php
								$attachment_size = apply_filters( 'promax_attachment_size', array( 960, 960 ) );
								echo wp_get_attachment_image( $post->ID, $attachment_size );
								?></a>

								<?php if ( ! empty( $post->post_excerpt ) ) : ?>
								<div class="entry-caption">
									<?php the_excerpt(); ?>
								</div>
								<?php endif; ?>
							</div><!-- .attachment -->

						</div><!-- .entry-attachment -->

						<div class="entry-description">
							<?php the_content(); ?>
							<?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'promax' ), 'after' => '</div>' ) ); ?>
						</div><!-- .entry-description -->

					</div><!-- .entry-content -->
							</div> <!-- end div .entry -->
<span class="postmeta_box">
		<ul class="auth"> <?php promax_post_meta_data(); ?>, in <?php the_category(', '); ?>
</ul>
<ul class="tags">         
<?php if("the_tags") the_tags('Tags: ', ', ', ' - '); ?><?php edit_post_link('Edit', ' | ', ''); ?>
	</ul>

</span>       

<div class="gap"></div><?php if (of_get_option('promax_author' ) =='1' ) {load_template(get_template_directory() . '/includes/author.php'); } ?>

<?php if ( of_get_option('promax_links' ) =='on') { ?>
		<div id="single-nav" class="clearfix">
			<div id="single-nav-left"><?php previous_image_link('thumbnail'); ?></div>
		<div id="single-nav-right"><?php next_image_link('thumbnail'); ?></div>
		</div>        <?php } ?>
		<!-- END single-nav -->

			<div class="comments">    <?php comments_template(); ?> </div> <!-- end div .comments -->   
			<?php endwhile; ?>
			<?php else : ?>
				<div class="post">
					<h3><?php _e('404 Error: Not Found', 'promax' ); ?></h3>
				</div>
			<?php endif; ?>
		</div> <!-- end div #content -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
0
kolshix
6.7 лет назад 779
  • 0
    Kama9620

    Я бы рекомендовал возвращать 404 страницу, вместо редиректа. Для этого юзай хук pre_handle_404. Под твой случай код будет такой:

    // Ставим 404 статус
    add_action( 'pre_handle_404', 'set_404_for_unattached_images' );
    function set_404_for_unattached_images( $false ) {
    	// вложение и юзер не админ
    	if ( is_attachment() && ! current_user_can('manage_options') ) {
    		// 404 если unattach
    		if( empty(get_queried_object()->post_parent)  ){
    			global $wp_query;
    			$wp_query->set_404();
    			status_header( 404 );
    			nocache_headers();
    
    			return true; // для обрыва хука 
    		}
    	}
    
    	return $false;
    }
    kolshix 6.7 лет назад

    не помогает, вставил в файл функций , в итоге - через ссылку ?attachment_id=3118 - продолжает пользователь(любой) получать доступ

    а предыдущий плагин работал

    kolshix 6.7 лет назад

    сделал так

    // Exit if accessed directly
    defined( 'ABSPATH' ) || exit;
    
    add_action( 'template_redirect', 'sitecare_redirect_unattached_images' );
    /**
     * Redirects the attachment page for any image which has not been attached to a
     * post, page, or custom post type to the current site's home URL.
     *
     * @since  0.1.0
     * @uses   is_attachment()
     * @uses   get_queried_object()
     * @return void
     */
    
    function sitecare_redirect_unattached_images() {
    
    	$login=0;
    	if ( is_user_logged_in() ) {
    		$login = 1 ;
    	}
    
    	if ( ! is_attachment() ||  $login == 1) {
    		return;
    	}
    	$parent = get_queried_object()->post_parent;
    	if ( ! empty( $parent ) ) {
    		return;
    	}
    	if (  $login == 0 ) {       
    			global $wp_query;
    			$wp_query->set_404();
    			status_header( 404 );
    			nocache_headers();
    
    			return true; // для обрыва хука 
    
    		exit;
    
    	}
    }
    
    Комментировать
На вопросы могут отвечать только зарегистрированные пользователи. Вход . Регистрация