• Всем привет
    Написал вот такой скрипт, он получает GET параметри и создает новий пост с изображением.
    Но возникла проблема и уже как 4 часа сижу над ее решением.
    Етот скрипт вместо одного поста создает дна. Не пойму почему так получаета. Посмотрите пожалуйста на код, и если можете подскажите что я сделал не так?

Просмотр 4 ответов — с 1 по 4 (всего 4)
  • Автор tilseier

    (@tilseier)

    
    if(isset($_GET)):
    $token = isset($_GET['token']) ? $_GET['token'] : '';
    $set_img = isset($_GET['url']) ? $_GET['url'] : '';
    $referer_site = isset($_GET['referer']) ? $_GET['referer'] : '';
    $parse_url_site = parse_url($referer_site);
    $set_img_basename = basename($set_img);
    $set_img_domain = $parse_url_site['scheme'].'://'.$parse_url_site['host'];
    $title_site = isset($_GET['title']) ? $_GET['title'] : '';
    $alt_img = isset($_GET['alt']) ? $_GET['alt'] : '';
    
    	if($token == 'aklkflKHKJAHFKJASHjhdajshkfjasfkJHASFLqlwkfk213r23dh23rhr2j3rhkjhwe23jrh2'):
    	// Register Post Data
    	$post_img = array();
    	$post_img['post_status']   = 'publish';
    	$post_img['post_type']     = 'post'; // can be a CPT too
    	$post_img['post_title']    = $title_site;
    	$post_img['post_content']  = '';
    	$post_img['post_author']   = get_current_user_id();//1;
    
    	// Create Post
    	$post_id = wp_insert_post( $post_img );
    
    	//Add or Update meta data
    	if ( !update_post_meta( $post_id, '_Photo Source', $set_img ) ) add_post_meta( $post_id, '_Photo Source', $set_img, true );
    	if ( !update_post_meta( $post_id, '_Photo Source Domain', $set_img_domain ) ) add_post_meta( $post_id, '_Photo Source Domain', $set_img_domain, true );
    
    	// add_post_meta( $post_id, '_Photo Source', $set_img, true);
    	// add_post_meta( $post_id, '_Photo Source Domain', $set_img_domain, true);
    
    	// Add Featured Image to Post
    	$image_url        = $set_img; // Define the image URL here
    	$image_name       = $set_img_basename;
    	$upload_dir       = wp_upload_dir(); // Set upload folder
    	$image_data       = file_get_contents($image_url); // Get image data
    	$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name
    	$filename         = basename( $unique_file_name ); // Create image file name
    
    	// Check folder permission and define file location
    	if( wp_mkdir_p( $upload_dir['path'] ) ) {
    	    $file = $upload_dir['path'] . '/' . $filename;
    	} else {
    	    $file = $upload_dir['basedir'] . '/' . $filename;
    	}
    
    	// Create the image  file on the server
    	file_put_contents( $file, $image_data );
    
    	// Check image file type
    	$wp_filetype = wp_check_filetype( $filename, null );
    
    	// Set attachment data
    	$attachment = array(
    	    'post_mime_type' => $wp_filetype['type'],
    	    'post_title'     => sanitize_file_name( $filename ),
    	    'post_content'   => '',
    	    'post_status'    => 'inherit'
    	);
    
    	// Create the attachment
    	$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
    
    	// Include image.php
    	require_once(ABSPATH . 'wp-admin/includes/image.php');
    
    	// Define attachment metadata
    	$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
    
    	// Assign metadata to attachment
    	wp_update_attachment_metadata( $attach_id, $attach_data );
    
    	// And finally assign featured image to post
    	if(set_post_thumbnail( $post_id, $attach_id )){
    		echo '<h1 class="text-center">Post was successfully added!</h1>';
    	}else{
    		echo '<h1 class="text-center">Wrong!</h1>';
    	}
    
    	endif;
    
    endif;
    
    • Ответ изменён 8 лет назад пользователем Sergey Biryukov.
    Модератор Sergey Biryukov

    (@sergeybiryukov)

    Live and Learn

    Етот скрипт вместо одного поста создает дна.

    В какой момент он вызывается? Если просто при загрузке страницы, попробуйте привязать его к какому-нибудь действию — например, init.

    Автор tilseier

    (@tilseier)

    Странно он почемуто не срабатывает, в чем может быть причина?

    
    function set_img_post() {
    
    if(isset($_GET)):
    $token = isset($_GET['token']) ? $_GET['token'] : '';
    $set_img = isset($_GET['url']) ? $_GET['url'] : '';
    $referer_site = isset($_GET['referer']) ? $_GET['referer'] : '';
    $parse_url_site = parse_url($referer_site);
    $set_img_basename = basename($set_img);
    $set_img_domain = $parse_url_site['scheme'].'://'.$parse_url_site['host'];
    $title_site = isset($_GET['title']) ? $_GET['title'] : '';
    $alt_img = isset($_GET['alt']) ? $_GET['alt'] : '';
    
    	if($token == 'QzEK5PJ3/RRO4cuaQQiKKNg5au6SESUSkQOK5w9HKFgH6GxVu1NNilA5TYqoMBbz6sKdZP6eQ4GeLyZ1Ht5S/VrHIISvHXKFPxXNZZmRp1M='):
    	// Register Post Data
    	$post_img = array();
    	$post_img['post_status']   = 'publish';
    	$post_img['post_type']     = 'post'; // can be a CPT too
    	$post_img['post_title']    = $title_site;
    	$post_img['post_content']  = '';
    	$post_img['post_author']   = get_current_user_id();//1;
    
    	// Create Post
    	$post_id = wp_insert_post( $post_img );
    
    	//Add or Update meta data
    	if ( !update_post_meta( $post_id, '_Photo Source', $set_img ) ) add_post_meta( $post_id, '_Photo Source', $set_img, true );
    	if ( !update_post_meta( $post_id, '_Photo Source Domain', $set_img_domain ) ) add_post_meta( $post_id, '_Photo Source Domain', $set_img_domain, true );
    
    	// add_post_meta( $post_id, '_Photo Source', $set_img, true);
    	// add_post_meta( $post_id, '_Photo Source Domain', $set_img_domain, true);
    
    	// Add Featured Image to Post
    	$image_url        = $set_img; // Define the image URL here
    	$image_name       = $set_img_basename;
    	$upload_dir       = wp_upload_dir(); // Set upload folder
    	$image_data       = file_get_contents($image_url); // Get image data
    	$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name
    	$filename         = basename( $unique_file_name ); // Create image file name
    
    	// Check folder permission and define file location
    	if( wp_mkdir_p( $upload_dir['path'] ) ) {
    	    $file = $upload_dir['path'] . '/' . $filename;
    	} else {
    	    $file = $upload_dir['basedir'] . '/' . $filename;
    	}
    
    	// Create the image  file on the server
    	file_put_contents( $file, $image_data );
    
    	// Check image file type
    	$wp_filetype = wp_check_filetype( $filename, null );
    
    	// Set attachment data
    	$attachment = array(
    	    'post_mime_type' => $wp_filetype['type'],
    	    'post_title'     => sanitize_file_name( $filename ),
    	    'post_content'   => '',
    	    'post_status'    => 'inherit'
    	);
    
    	// Create the attachment
    	$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
    
    	// Include image.php
    	require_once(ABSPATH . 'wp-admin/includes/image.php');
    
    	// Define attachment metadata
    	$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
    
    	// Assign metadata to attachment
    	wp_update_attachment_metadata( $attach_id, $attach_data );
    
    	// And finally assign featured image to post
    	if(set_post_thumbnail( $post_id, $attach_id )){
    		echo '<h1 class="text-center">Post was successfully added!</h1>';
    	}else{
    		echo '<h1 class="text-center">Wrong!</h1>';
    	}
    
    	endif;
    
    endif;
    
    }
    
    add_action( 'init', 'set_img_post' );
    
    // add_action( 'wp_loaded','set_img_post' );
    
    Автор tilseier

    (@tilseier)

    Весь код. вместо одного поста создает два. А с использовалием add_action не срабатывает. В чем может быть причина?

    
    <?php
    
    /*
    
    Template Name: _add_img
    
    */
    
    define("DONOTCACHEPAGE", true);
    
    if (isset($_GET['action']) && $_GET['action'] == 'logout') {
    
    	if (wp_verify_nonce($_GET['nonce'], 'logout')) {
    
    		wp_logout();
    
    		wp_safe_redirect(home_url('/login/?action=loggedout'));
    
    		exit();
    
    	}
    
    }
    
    if (of_get_option('captcha_public') != '' && of_get_option('captcha_private') != '')
    
    	require_once(get_template_directory() . '/recaptchalib.php');
    
    get_header();
    
    if (!is_user_logged_in()): 
    // { wp_redirect(home_url()); exit; }
    
    ?>
    
    <div class="container">
    
    	<div class="row">
    
    		<div class="col-sm-2"></div>
    
    		<div class="col-sm-8 usercp-wrapper hide">		
    
    			<?php if (isset($_GET['action']) && $_GET['action'] == 'loggedout' && !$_GET['login']) { ?>
    
    				<div class="error-msg-incorrect"><div class="alert alert-success"><strong><?php _e('Logged Out Successfully', 'pinc'); ?></strong></div></div>
    
    			<?php } ?>
    
    			
    
    			<?php 
    
    			if (function_exists('wsl_activate')) {
    
    				do_action('wordpress_social_login');
    
    			}
    
    			?>
    
    			<?php if (isset($_GET['pw']) && $_GET['pw'] == 'reset') {   ?>
    
    				<div class="error-msg-incorrect"><div class="alert alert-success"><strong><?php _e('Your password has been reset.', 'pinc'); ?></strong></div></div>
    
    			<?php } else if (isset($_GET['registration']) && $_GET['registration'] == 'disabled') {   ?>
    
    				<div class="error-msg-incorrect"><div class="alert alert-warning"><strong><?php _e('User registration is currently closed.', 'pinc'); ?></strong></div></div>
    
    			<?php } else if (isset($_GET['registration']) && $_GET['registration'] == 'done' ) {   ?>
    
    				<div class="error-msg-incorrect"><div class="alert alert-success"><strong><?php _e('To activate account, please check your email for verification link.', 'pinc'); ?></strong></div></div>
    
    			<?php } else if (isset($_GET['email']) && $_GET['email'] == 'unverified' ) {   ?>
    
    				<div class="error-msg-incorrect"><div class="alert alert-warning"><strong><?php _e('Account not activated yet. Please check your email for verification link.', 'pinc'); ?></strong></div></div>
    
    			<?php } else if (isset($_GET['email']) && $_GET['email'] == 'verify') {
    
    				$user = get_user_by('login', $_GET['login']);
    
    				$key = get_user_meta($user->ID, '_Verify Email', true);
    
    				if ($key == $_GET['key']) {
    
    					delete_user_meta($user->ID, '_Verify Email', $key);
    
    				?>
    
    				<div class="error-msg-incorrect"><div class="alert alert-success"><strong><?php _e('Verification success. You may login now.', 'pinc'); ?></strong></div></div>
    
    				<?php } else { ?>
    
    				<div class="error-msg-incorrect"><div class="alert alert-warning"><strong><?php _e('Invalid verification key', 'pinc'); ?></strong></div></div>
    
    			<?php }
    
    			} else if (isset($_GET['login']) && $_GET['login'] == 'failed') { ?>
    
    				<div class="error-msg-incorrect"><div class="alert alert-warning"><strong><?php _e('Incorrect Username', 'pinc'); ?>/<?php _e('Password', 'pinc'); if (of_get_option('captcha_public') != '' && of_get_option('captcha_private') != '') { echo '/'; _e('Captcha', 'pinc'); } ?></strong></div></div>
    
    			<?php } ?>
    
    			<div class="error-msg-blank"></div>
    
    			
    
    			<h1<?php if (function_exists('wsl_activate')) echo ' style="border: none"'; ?>><?php _e('Login', 'pinc') ?></h1>
    
    			<?php if (!function_exists('wsl_activate')) echo '<br />'; ?>
    
    			
    
    			<form name="loginform" id="loginform" action="<?php echo site_url('wp-login.php', 'login_post'); ?>" method="post">
    
    				<div class="form-group">
    
    					<label class="form-label" for="log"><?php _e('Username or Email', 'pinc'); ?></label>
    
    					<input class="form-control" type="text" name="log" id="log" value="" tabindex="10" />
    
    				</div>
    
    				<div class="form-group">
    
    					<label class="form-label" for="pwd"><?php _e('Password', 'pinc'); ?> (<a href="<?php echo home_url('/login-lpw/'); ?>"><?php _e('Forgot?', 'pinc'); ?></a>)</label>
    
    					<input class="form-control" type="password" name="pwd" id="pwd" value="" tabindex="20" />
    
    				</div>
    
    				
    
    				<?php
    
    				if (of_get_option('captcha_public') != '' && of_get_option('captcha_private') != '') {
    
    					$publickey = of_get_option('captcha_public');
    
    				?>
    
    					<script src="https://www.google.com/recaptcha/api.js" async defer></script>
    
    					<div class="g-recaptcha" data-sitekey="<?php echo $publickey; ?>"></div>
    
    				<?php }	?>
    
    				
    
    				<br />
    
    				
    
    				<input type="hidden" name="rememberme" id="rememberme" value="forever" />
    
    				<input type="hidden" name="redirect_to" id="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" />
    				<?php //if ($_GET['redirect_to']) { echo esc_attr($_GET['redirect_to']); } else { echo esc_attr(home_url('/')); } ?>
    
    				<input type="hidden" name="nonce" id="nonce" value="<?php echo wp_create_nonce('login'); ?>" />
    
    				<input type="hidden" name="formname" id="formname" value="pinc_loginform" />
    
    				<input type="submit" class="btn btn-success btn-block btn-pinc-custom" name="wp-submit" id="wp-submit" value="<?php _e('Login', 'pinc'); ?>" tabindex="30" />
    
    				<br />
    
    				<p class="text-center">
    
    				<a class="btn btn-grey" href="<?php echo home_url('/signup/'); ?>"><?php _e('Don\'t have an account? Sign Up Now', 'pinc'); ?></a>
    
    				</p>
    
    			</form>
    
    		</div>
    
    		<div class="col-sm-2 hiddex-xs"></div>
    
    	</div>
    
    </div>
    
    <script>
    
    jQuery(document).ready(function($) {
    
    	$('.usercp-wrapper').show();
    
    	$('#log').focus();
    
    });
    
    </script>
    
    <?php else: ?>
    
    <?php 
    
    // function set_img_post() {
    
    if(isset($_GET)):
    $token = isset($_GET['token']) ? $_GET['token'] : '';
    $set_img = isset($_GET['url']) ? $_GET['url'] : '';
    $referer_site = isset($_GET['referer']) ? $_GET['referer'] : '';
    $parse_url_site = parse_url($referer_site);
    $set_img_basename = basename($set_img);
    $set_img_domain = $parse_url_site['scheme'].'://'.$parse_url_site['host'];
    $title_site = isset($_GET['title']) ? $_GET['title'] : '';
    $alt_img = isset($_GET['alt']) ? $_GET['alt'] : '';
    
    	if($token == 'QzEK5PJ3/RRO4cuaQQiKKNg5au6SESUSkQOK5w9HKFgH6GxVu1NNilA5TYqoMBbz6sKdZP6eQ4GeLyZ1Ht5S/VrHIISvHXKFPxXNZZmRp1M='):
    	// Register Post Data
    	$post_img = array();
    	$post_img['post_status']   = 'publish';
    	$post_img['post_type']     = 'post'; // can be a CPT too
    	$post_img['post_title']    = $title_site;
    	$post_img['post_content']  = '';
    	$post_img['post_author']   = get_current_user_id();//1;
    
    	// Create Post
    	$post_id = wp_insert_post( $post_img );
    
    	//Add or Update meta data
    	if ( !update_post_meta( $post_id, '_Photo Source', $set_img ) ) add_post_meta( $post_id, '_Photo Source', $set_img, true );
    	if ( !update_post_meta( $post_id, '_Photo Source Domain', $set_img_domain ) ) add_post_meta( $post_id, '_Photo Source Domain', $set_img_domain, true );
    
    	// add_post_meta( $post_id, '_Photo Source', $set_img, true);
    	// add_post_meta( $post_id, '_Photo Source Domain', $set_img_domain, true);
    
    	// Add Featured Image to Post
    	$image_url        = $set_img; // Define the image URL here
    	$image_name       = $set_img_basename;
    	$upload_dir       = wp_upload_dir(); // Set upload folder
    	$image_data       = file_get_contents($image_url); // Get image data
    	$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name
    	$filename         = basename( $unique_file_name ); // Create image file name
    
    	// Check folder permission and define file location
    	if( wp_mkdir_p( $upload_dir['path'] ) ) {
    	    $file = $upload_dir['path'] . '/' . $filename;
    	} else {
    	    $file = $upload_dir['basedir'] . '/' . $filename;
    	}
    
    	// Create the image  file on the server
    	file_put_contents( $file, $image_data );
    
    	// Check image file type
    	$wp_filetype = wp_check_filetype( $filename, null );
    
    	// Set attachment data
    	$attachment = array(
    	    'post_mime_type' => $wp_filetype['type'],
    	    'post_title'     => sanitize_file_name( $filename ),
    	    'post_content'   => '',
    	    'post_status'    => 'inherit'
    	);
    
    	// Create the attachment
    	$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
    
    	// Include image.php
    	require_once(ABSPATH . 'wp-admin/includes/image.php');
    
    	// Define attachment metadata
    	$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
    
    	// Assign metadata to attachment
    	wp_update_attachment_metadata( $attach_id, $attach_data );
    
    	// And finally assign featured image to post
    	if(set_post_thumbnail( $post_id, $attach_id )){
    		echo '<h1 class="text-center">Post was successfully added!</h1>';
    	}else{
    		echo '<h1 class="text-center">Wrong!</h1>';
    	}
    
    	endif;
    
    endif;
    
    // }
    
    // add_action( 'init', 'set_img_post' );
    
    // add_action( 'wp_loaded','set_img_post' );
    
    ?>
    
    <script>
    var tm=4000;
    window.setTimeout("window.close()",tm);
    </script>
    
    <?php endif; ?>
    
    <?php get_footer(); ?>
    
Просмотр 4 ответов — с 1 по 4 (всего 4)
  • Тема «Почему так происходит и…» закрыта для новых ответов.