• dont work pagination. error 404: <mysite>/<post-type>/page/2 (((

    code template page “archive-catering”:

    <?php locate_template( 'archive-catering.php', true ); ?>
    <!DOCTYPE html>
    <html>
    
    <head>
    <meta charset="utf-8">
    <title><?php echo get_post_meta($post->ID, 'title', true); ?></title>
    <link href="https://fonts.googleapis.com/css?family=Roboto+Slab|Roboto:400,400i,700&subset=cyrillic,cyrillic-ext" rel="stylesheet">
      <link rel="stylesheet" href="<?php echo get_site_url(); ?>/font-awesome-4.6.3/css/font-awesome.min.css">
      <link rel="stylesheet" href="<?php echo get_site_url(); ?>/catering.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
      <script src="<?php echo get_site_url(); ?>/script_cat.js"></script>
    
    </head>
    <body>
    
    <?php
    $status_load = array(null,0);
    //проверка Nonce
    if (isset( $_POST['photos_nonce'] ) && wp_verify_nonce( $_POST['photos_nonce'], 'photos' ) ){
    	$nonce_status = true;
    } else $nonce_status = false;
    //если пользователь НЕ залогинен
    if ( !is_user_logged_in() ) {	
    		//если есть пост-поля
    		if (isset($_POST['user_login']) && isset($_POST['user_email'])){			
    			$user_login = sanitize_text_field( $_POST['user_login'] );
    			$user_email = sanitize_email( $_POST['user_email'] );
    			//создаем пользователя	
    			$random_password = wp_generate_password( $length=12, $include_standard_special_chars=false );
    			$registration = wp_create_user( $user_login, $random_password, $user_email );
    						
    			if ( is_wp_error($registration) ) {
    				$status_load[0] .= 'Ошибка регистрации: ' . $registration->get_error_message() . '</br>';
    				} else {
    					$now_user_login = get_user_by('id', $registration)->get('user_login');
    					$status_load[0] .= 'Спасибо за регистрацию, ' . $now_user_login . '</br>';
    					//авторизация
    					$creds = array(
    					'user_login'    => $user_login,
    					'user_password' => $random_password,
    					'remember'      => true,
    					);
    					
    					$user = wp_signon( $creds, false );
    					
    					if ( is_wp_error($user) ){
    						$status_load[0] .= 'Ошибка входа: ' . $user->get_error_message() . '</br>';
    						} else {
    							//устанавливаем текущего пользователя
    							wp_set_current_user($user->get('id'));
    							$now_user_login = $user->get('user_login');
    							$status_load[0] .= 'Вы вошли как: ' . $now_user_login . '</br>';
    						}					
    					}			
    			}
    		}
    
    //загрузка данных из формы
    
    if( isset( $_POST['register'] ) and is_user_logged_in()) {
    	
    	$mimes = array('image/gif', 'image/png', 'image/jpeg');	 
    		 // Проверим защиту nonce 
    		if ( $nonce_status ) {
    		if ( $_FILES ) { 
    				$files = $_FILES['photos'];
    				foreach ($files['name'] as $key => $value) { 			
    						if ($files['name'][$key] and in_array($files['type'][$key], $mimes)) {						
    							$file = array( 
    								'name' => sanitize_file_name($files['name'][$key]),
    								'type' => $files['type'][$key], 
    								'tmp_name' => $files['tmp_name'][$key], 
    								'error' => $files['error'][$key],
    								'size' => $files['size'][$key]
    							); 
    							$_FILES = array ('photos' => $file);
    							foreach ($_FILES as $file => $array) {				
    								$attach_ids[] = kv_handle_attachment($file,$post_id,$attach_id_array);						
    							}					
    						} 
    				}
    				$status_load[0] .= "Загружено изображений: " . count($attach_ids) .".</br>";
    				if (count($attach_ids) != 0) $status_load[1] = 1; else $status_load[0] .= "Заполните все поля, помеченные звездочками * .</br>";
    	}
    
    	} else {
    		$status_load[0] .= 'Проверка не пройдена. Невозможно загрузить файл.</br><a href="" class="btn green clearfix">Обновите страницу</a></br>';
    	}
    	
    	//создание поста если картинки загружены
    if 	(isset($status_load) and $status_load[1] == 1) {
    		// Создаем массив данных новой записи
    		
    		$post_data = array(
    		  'post_content' => wp_kses($_POST['content'], 'post' ),
    		  'post_title' => strip_tags($_POST['organisation']),
    		  'post_type'  => 'catering',
    		  'tax_input' => array(
    			'catering_category' => strip_tags($_POST['category'])
    			),
    		  'meta_input' => array(
    			'val' => strip_tags($_POST['val']),
    			'check' => strip_tags($_POST['check']),
    			'alco' => strip_tags($_POST['alco']),
    			'show' => strip_tags($_POST['show']),
    			'tel' => strip_tags($_POST['tel']),
    			'vklink' => esc_url($_POST['vklink'], 'post' ),
    			'adress' => wp_kses($_POST['adress'], 'default' )			
    			)
    		);
    		
    		$post_id = wp_insert_post( $post_data );
    		if ($post_id != 0) $status_load[0] .= 'Вы создали запись с названием '.strip_tags($_POST['organisation']).'</br>';
    
    		//прикрепляем загруженные картинки к созданному посту
    		
    		foreach ($attach_ids as $attach_id) {
    			$update_post = array (
    			'ID' => $attach_id,
    			'post_parent' => $post_id
    			);
    			wp_update_post( $update_post );
    		}
    		
    		//если есть право публиковать - минимально у Автора
    		if (current_user_can('publish_posts')){
    			wp_publish_post( $post_id );
    		}
    	} 	
    }
    
    function kv_handle_attachment($file_handler,$post_id,$attach_id_array,$set_thu=false) {
    		// check to make sure its a successful upload
    		if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
    
    		require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    		require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    		require_once(ABSPATH . "wp-admin" . '/includes/media.php');
    
    		
    		$attach_id = media_handle_upload( $file_handler, $post_id );
    
    		if ( is_wp_error( $attach_id ) ) {
    			$error_string = $attach_id->get_error_message();
    			$status_load .= "Ошибка: " . $error_string;
    		} else {
    			@unlink( $file_array['tmp_name'] );	
    			return $attach_id;
    		}
    		
    	}
    
    ?>
    
    <?php		
    
    //вывод заведений
    //обертка
    
    function tpl_Blog(){
    	echo '<article class="select clearfix color2" id="articles">
        <div class="row opbg clearfix">
          <hr>
          <h1 class="art">Новогодние предложения<br><span>выбирайте!</span></h1>
          <hr>';
    	tpl_Form();
    	tpl_Rows();
    	tpl_Pagination();
    	echo '</div>
        <div class="bgbottom">
          <img class="" src="'.get_site_url().'/img/bgbottom.png" width="100%" alt="">
        </div>
    	</article>';
    }
    //форма
    function tpl_Form(){
    	if ($_POST['f']['alco']=='on') $checked[0] = 'checked';
    	if ($_POST['f']['show']=='on') $checked[1] = 'checked';
    	if (isset($_POST['f']['val'])) $fval[0] = 'value="'.strip_tags($_POST['f']['val']).'"';
    	if (isset($_POST['f']['from'])) $fval[1] = 'value="'.strip_tags($_POST['f']['from']).'"';
    	if (isset($_POST['f']['to'])) $fval[2] = 'value="'.strip_tags($_POST['f']['to']).'"';
    	echo '<form action="'. get_permalink() .'#articles" class="clearfix" method="post" >
            <div class="width1-2 padding">
              <div class="width1-2 paddingright">
                <h4>количество гостей</h4>
                <input type="number" class="width1" placeholder="количество человек" name="f[val]" '.$fval[0].'>
              </div>
              <div class="width1-2">
                <h4>средний чек</h4>
                <input type="number" class="in1-2" placeholder="от" name="f[from]" '.$fval[1].'>
                <input type="number" class="in1-2 marleft" placeholder="до" name="f[to]" '.$fval[2].'>
              </div>
              <div class="width1-2">
                <h4><input type="checkbox" style="" name="f[alco]" id="falco" '.$checked[0].'>
                <label for="falco">свой алкоголь</label></h4>
              </div>
              <div class="width1-2">
                <h4><input type="checkbox" name="f[show]" id="fshow" '.$checked[1].'>
                <label for="fshow">шоу-программа</label></h4>
              </div>
            </div>
            <div class="width1-2 vcenter center">
    			<input type="submit" class="btn green center" value="обновить" name="filter">
            </div>
          </form>';
    }
    //чанк ряда
    function tpl_Rows(){
    	global $postslist;
    	global $post;	
    	
    	if ($_POST['f'] != ''){
    		$meta_query = array('relation' => 'AND');
    		$i = 0;
    		foreach($_POST['f'] as $key => $post_f){
    			//очистим от тэгов
    			strip_tags($post_f);
    			if ($post_f != ''){
    				
    				if ($key == 'from'||$key == 'to'||$key == 'val') {
    					switch ($key) {
    						case 'from':
    							$meta_query[$i]['key'] = 'check';
    							$meta_query[$i]['compare'] = '>=';
    							$meta_query[$i]['type'] = 'NUMERIC';
    							break;	
    						case 'to':
    							$meta_query[$i]['key'] = 'check';
    							$meta_query[$i]['compare'] = '<=';
    							$meta_query[$i]['type'] = 'NUMERIC';
    							break;
    						case 'val':
    							$meta_query[$i]['key'] = 'val';
    							$meta_query[$i]['compare'] = '>=';
    							$meta_query[$i]['type'] = 'NUMERIC';
    							break;
    						}
    				} else {
    					$meta_query[$i]['key'] = $key;
    					
    				}				
    				$meta_query[$i]['value'] = $post_f;
    				$i++;
    			}			
    		}
    	}
    	
    	$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    	$postslist = new WP_Query(
    	array(
    	'posts_per_page' => 4,
    	'order'=> 'ASC',
    	'orderby' => 'title',
    	'post_type' => 'catering',
    	'meta_query' => $meta_query,
    	'paged' => $paged,
    	'page' => $paged
    	)
    	);
    	$row_count = 2;
    	if ( $postslist->have_posts() ) :
    	while ( $postslist->have_posts() ){
    	$postslist->the_post();
    	if ($row_count == 2) echo '<div class="tabs clearfix">';
    	
    	tpl_Post();
    	
    	
    	
    	$row_count--;
    	if ($row_count == 0) {
    		echo '</div>';
    		$row_count = 2;
    	}
    	}
    	else :
    			echo '<p>no found</p>';
    
    	endif;
    	if ($row_count != 2) echo '</div>';
    	
    }
    
    //чанк
    
    function tpl_Post(){	
    	global $postslist;
    	global $post;
    	echo '<div class="width1-2 tab padding">';
    	$media = array_shift(get_attached_media('image'));
    	echo '<img src="'. wp_get_attachment_image_url($media->ID, 'catering_thumb') .'" alt="">';
        echo '<a href="/catering-post/?post='.$post->ID.'" data-toggle="postmodal">';
    	the_title('<h2>', '</h2>');
    	echo '</a>';	
    	echo '<div class="color3 stars">';
    	$meta = get_post_meta( get_the_ID() );
    	$stars = $meta['rating'][0];
    	for ($i=0; $i<5; $i++){		
    		if ($stars != 0) {
    			echo '<i class="fa fa-star"></i>';
    			$stars--;
    		} else echo '<i class="fa fa-star-o"></i>';		
    	}
        echo '</div>
              <ul class="center clearfix">';	
    	if( $meta['check'][0] != '' ){
    		echo '<li><i class="fa fa-money"></i>
                <h3>Чек<br>'.$meta['check'][0].' руб.</h3>
                </li>';
    		} 
    	if ( $meta['val'][0] != '' ) {
    		echo '<li><i class="fa fa-users"></i>
                  <h3>вместимость<br>'.$meta['val'][0].'  чел.</h3>
                </li>';
    		} 
    	if ( isset($meta['alco']) and $meta['alco'][0]=='on' ) {
    		echo '<li><i class="fa fa-glass"></i>
                  <h3>свой<br>алкоголь</h3>
                </li>';
    		} 
    	if ( isset($meta['show']) and $meta['show'][0]=='on' ) {
    		echo '<li><i class="fa fa-microphone"></i>
                  <h3>шоу<br>программа</h3>
                </li>';
    		}
        echo '</ul>';
        the_excerpt();
        echo '</div>';
    }
    ?>
    <!--пагинация-->
    <?php
    function tpl_Pagination(){
    	global $postslist;
    	global $post;
    	global $paged;
    	// пагинация для произвольного запроса
    	$big = 999999999; // уникальное число
    	$links = paginate_links( array(
    		'base'    => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
    		'format'  => '?paged=%#%',
    		'current' => $paged,
    		'total'   => ($postslist->max_num_pages) ? $postslist->max_num_pages : 1,
    		'prev_text' => '<<',
    		'next_text' => '>>',
    	) );
    	
    	add_filter('navigation_markup_template', 'my_navigation_template', 10, 2 );
    	function my_navigation_template( $template, $class ){
    		/*
    		Вид базового шаблона:
    		<nav class="navigation %1$s" role="navigation">
    			<h2 class="screen-reader-text">%2$s</h2>
    			<div class="nav-links">%3$s</div>
    		</nav>
    		*/
    
    		return '
    		<div class="pagination %1$s" role="navigation">%3$s</div>
    		';
    	}
    	if ( $links ) {
    		echo _navigation_markup( $links, 'center', 'Моя крутая навигация' );
    		
    	}
    	
    	wp_reset_postdata();
    }
    ?>
    <!--хэдер-->
    <header class="clearfix color1">
        <div class="row clearfix">
          <hr>
          <h1 class="art">Где отметить новый год <br><span>в Перми</span></h1>
          <hr>
          <div class="width1-2 center">
            <p>
              Вы давно ищете, где отметить новый год с компанией, или где отметить новогодний корпоратив с коллегами?
            </p>
            <a href="#articles" class="btn green">Выбрать место</a>
          </div>
          <div class="width1-2 center clearfix">
            <p>
              Вы представитель ресторана, банкетного зала, задаетесь вопросом где искать клиентов и как себя рекламировать?
            </p>
            <a href="#register" class="btn blue">Зарегистрироваться</a>
          </div>
        </div>
      </header>
    
    <!--выводим блог-->
    <?php tpl_Blog();?>
    <!--ФОРМЫ-->
    
    <?php 
    $currentuser = wp_get_current_user();
    if ($currentuser->ID != 0){
    	$headers['subhead'] = 'Привет, ';
    	if (!empty($currentuser->user_firstname)) $headers['subhead'] .= $currentuser->user_firstname; else $headers['subhead'] .= $currentuser->user_login;
    	$headers['head'] = 'НОВОЕ МЕСТО:';
    } else $headers['head'] = 'Регистрация'; $headers['subhead'] = 'ДОБАВИТЬ ОРГАНИЗАЦИЮ';
    ?>
    <div class="register clearfix" id="register">
        <div class="row opbg1 clearfix">
          <hr>
          <h1 class="art color2"><?php echo $headers['subhead'] ?><br><span><?php echo $headers['head'] ?></span></h1>
          <hr>
          <form class="clearfix" method="post" action="#" enctype="multipart/form-data">
            <div class="clearfix">
              <div class="width1-2 padding clearfix">
    		  <!--поля регистрации-->
    			<?php 
    			//поля регистрации
    			if ( !is_user_logged_in() ) {
                echo '<h4>логин*</h4>
                <input type="text" class="width1" name="user_login" pattern="[A-Za-z0-9]{3,30}" title="Не менее 3 букв или цифр, латиница" required>
                <h4>Ваш E-mail*</h4>
                <input type="email" class="width1" name="user_email" required>';
    			}
    			//кнопка выхода
    			if ( is_user_logged_in() ) {
    				echo '<a href="'.get_site_url().'/catering-lk" title="Личный кабинет"><h4>Личный кабинет</h4></a>';
    				echo '<a href="'.wp_logout_url( $_SERVER['REQUEST_URI'] ).'" title="Выход"><h4>Выход</h4></a>
    				<h4>Вы можете быстро добавить новое заведение:</h4>';
    						}
    			?>
                <h4>КАТЕГОРИЯ зАВЕДЕНИЯ</h4>			
    			<select name="category" class="width1">
    			<!--список тем -->
    			<?php $terms = get_terms(array('taxonomy' => 'catering_category','hide_empty' => false));
    			 $count = count($terms);
    			 if($count > 0){
    				 foreach ($terms as $term) {
    				   echo '<option value="'.$term->term_id.'">'.$term->name.'</option>';
    				 }
    			 }
    			 ?>
    			</select>		
                <h4>название*</h4>
                <input type="text" class="width1" name="organisation" required>
                <h4>адрес*</h4>
                <input type="text" class="width1" name="adress" required>
    			<h4>телефон*</h4>
                <input type="tel" class="width1" name="tel" required>
              </div>
              <div class="width1-2 padding clearfix">
    			<h4>Страница Вконтакте</h4>
                <input type="url" class="width1" name="vklink" placeholder="https://адрес сайта">
                <h4>вместимость*</h4>
                <input type="number" class="width1" name="val" required>
                <h4>средний чек*</h4>
                <input type="number" class="width1" name="check" placeholder="указывайте в рублях" required>
                <h4>подробное описание</h4>
                <textarea class="width1" rows="<?php if ( is_user_logged_in() ) echo '7'; else echo '10'; ?>" name="content">
                </textarea>
              </div>
            </div>
            <div class="padding clearfix">
              <h4>добавить изображения</h4>
              <div class="clearfix">
                <div class="file-upload">
                  <label>
                    <input type="file" name="photos[]" id="file1" onchange="renderImage(this.files[0], this.id);" required>
                    <span>
    				<p>главное изоражение*</p>
                    </span>
    				
                  </label>
                  <div class="preview" id="preview_file1">
                    <!--image will be inserted here-->
                  </div>
                </div>
                <div class="file-upload">
                  <label>
                    <input type="file" name="photos[]" id="file2" onchange="renderImage(this.files[0], this.id);">
                    <span>
                    <i class="fa fa-plus"></i>
                    </span>
                  </label>
                  <div class="preview" id="preview_file2">
                    <!--image will be inserted here-->
                  </div>
                </div>
                <div class="file-upload">
                  <label>
                    <input type="file" name="photos[]" id="file3" onchange="renderImage(this.files[0], this.id);">
                    <span>
                    <i class="fa fa-plus"></i>
                    </span>
                  </label>
                  <div class="preview" id="preview_file3">
                    <!--image will be inserted here-->
                  </div>
                </div>
                <div class="file-upload">
                  <label>
                    <input type="file" name="photos[]" id="file4" onchange="renderImage(this.files[0], this.id);">
                    <span>
                    <i class="fa fa-plus"></i>
                    </span>
                  </label>
                  <div class="preview" id="preview_file4">
                    <!--image will be inserted here-->
                  </div>
                </div>
              </div>
            </div>
            <div class="padding clearfix">
              <div class="width1-2">
                <h4 class="inline"><input type="checkbox" style="" name="alco" id="alco">
                <label for="alco">свой алкоголь</label></h4>
                <h4 class="inline"><input type="checkbox" name="show" id="show">
                 <label for="show">шоу-программа</label></h4>
    			 <p>*обязательно заполнить</p>
              </div>
              <div class="width1-2 center">
    			<?php wp_nonce_field( 'photos', 'photos_nonce' ); ?>
                <input type="submit" class="btn blue" value="зарегистрировать" name="register">
              </div>
            </div>
    		
          </form>
    	  <?php if ( !is_user_logged_in() ) echo '<div class="center width1">
            <h4>если вы зарегистрированы</h4>
    	  <a href="#login" class="btn green" data-toggle="modal">Войти</a>
    	  </div>';?>
        </div>
      </div>
     
     <!--Моальное окно-->
     
     <?php
     
     if ($status_load[0] != '') {
    	 //вывод результата загрузки
    	echo '<div class="modal modalopen clearfix" id="alert" >
      <div class="modaback closer"></div>
       <div class="content clearfix">
         <span class="close closer"><i class="fa fa-close"></i></span>
          <h4>СПАСИБО!</h4>
         <hr class="color4">
          <p>'.$status_load[0].'</p>
       </div>    
      </div>'; 
     }
     
    echo '<div class="modal modalhide clearfix" id="login" >
      <div class="modaback closer"></div>
       <div class="content clearfix">
         <span class="close closer"><i class="fa fa-close"></i></span>
          <h4>ВХОД</h4>
         <hr class="color4">';
    wp_login_form(array('form_id' => 'catering_login'));
    echo '</div>
      </div>';
     ?>
     
     <div class="modal modalhide clearfix postmodal">
          <div class="modaback closer"></div>
          <div class="row postview clearfix" id="postinner">
             <span class="close closer"><i class="fa fa-close"></i></span>
              <div class="">
                  <h1 class="art" id="post-organisation"></h1>
                  <h2 class="center" id="post-catering"></h2>
                  <ul class="center" id="post-options"><li><i></i></li></ul>
              <p class="padding clearfix" id="post-content"></p>          
              </div>
              <div class="padding clearfix center">
                  <div class="width1-3 center">
              <i class="fa fa-mobile bgcolor1 center"></i>
              <h2 id="post-tel"></h2>
              </div>
              <div class="width1-3 center" id="post-vklink"></div>
              <div class="width1-3 center clearfix">
                   <i class="fa fa-map-marker bgcolor3 center"></i>
                  <h2 id="post-adress"></h2>
              </div>
              </div>
              <div class="padding clearfix center" id="post-images"></div>
          </div>      
      </div>
     
    </body>
    
    </html>

    code on theme function file:

    add_action( 'init', 'true_register_post_type_init' ); // Использовать функцию только внутри хука init
     
    function true_register_post_type_init() {
    	$labels = array(
    		'name' => 'Заведения',
    		'singular_name' => 'Заведение', // админ панель Добавить->Функцию
    		'add_new' => 'Добавить заведение',
    		'add_new_item' => 'Добавить новую заведение', // заголовок тега <title>
    		'edit_item' => 'Редактировать заведение',
    		'new_item' => 'Новая заведение',
    		'all_items' => 'Все заведения',
    		'view_item' => 'Просмотр заведения на сайте',
    		'search_items' => 'Искать заведения',
    		'not_found' =>  'Заведений не найдено.',
    		'not_found_in_trash' => 'В корзине нет заведений.',
    		'menu_name' => 'ЗАВЕДЕНИЯ' // ссылка в меню в админке
    	);
    	$args = array(
    		'labels' => $labels,
    		'public' => true,
    		'show_ui' => true, // показывать интерфейс в админке
    		'has_archive' => true,
    		'hierarchical' => true,
    		'rewrite' => array(
    			'slug' => 'catering',
    			'with_front' => false,
    			'pages'=> true
    			),
    		'menu_icon' => 'dashicons-location-alt', // иконка в меню
    		'menu_position' => 5, // порядок в меню
    		'supports' => array( 'title', 'editor', 'comments', 'author', 'thumbnail', 'custom-fields'),
    		'delete_with_user' => true, //удалять посты при удалении пользователя
    	);
    	register_post_type('catering', $args);
    }

    Please help!!!)

Viewing 1 replies (of 1 total)
  • Ben Hutchings

    (@benmeredevelopmentcouk)

    Hi, I just faced something very similar, and it turned out I needed to manually add a Rewrite to handle the paging. For example:

    function rewrite_cpt_paging() {
        add_rewrite_rule('^catering/page/([0-9]+)/?$', 'index.php?pagename=catering&paged=$matches[1]', 'top');
    }
    add_action('init', 'rewrite_cpt_paging');

    If you need to add paging to several rewritten CPTs at once, you could use something like this:

    function rewrite_cpt_paging() {
    add_rewrite_rule(‘^(catering|other-cpt1|other-cpt2)/page/([0-9]+)/?$’, ‘index.php?pagename=$matches[1]&paged=$matches[2]’, ‘top’);
    }
    add_action(‘init’, ‘rewrite_cpt_paging’);

    Maybe… give it a try!

Viewing 1 replies (of 1 total)
  • The topic ‘register_post_type rewrite pages pagination’ is closed to new replies.