Показать сообщения, соответствующие пользователю, который вошел в систему (Wordpress-PHP)
для моего веб-проекта в Wordpress мне нужно включить страницу, где пользователи могут просматривать контент, который они создали в интернете (загруженные видео, комментарии, события и т. д.), Но с той особенностью, что на этой странице будет отображаться только информация, которую они создали, а не Информация других пользователей. То есть мне нужно написать код, чтобы отображалась только информация, сгенерированная пользователем, которая зарегистрирована. Я сделал много попыток, но я знаю, что я не могу заключить, правильно, последнюю часть кода (или лучше есть какая-то ошибка, тоже, в остальных), где вы должны включить строку, которая позволит вам показать результат того, что бросает код:
¿Правильно ли это делать с Эхо, return? и даже если это с тем или иным, как должна выглядеть эта строка кода? Я сделал много попыток ,но безуспешно (см. код вниз).
¿Я должен использовать команду function и add_filter код?
Если бы вы могли взглянуть на фрагмент кода, показанный ниже. К вашему сведению, результат, который этот код бросает мне на страницу Array.
я указываю вам некоторые ссылки, где я консультировался об этом тема:
Https://codex.wordpress.org/Class_Reference/WP_Query#Code_Documentation https://codex.wordpress.org/Function_Reference/get_posts https://wordpress.stackexchange.com/questions/69614/logged-in-user-id-as-post-id https://stackoverflow.com/questions/34685396/get-post-id-of-current-logged-in-user-and-add-a-link-to-the-menu
Код:
<?php // Accedemos a la variable global
global $current_user;
// Obtenemos la informacion del usuario conectado y asignamos los valores a
las variables globales
// Mas info sobre 'get_currentuserinfo()':
// http://codex.wordpress.org/Function_Reference/get_currentuserinfo
get_currentuserinfo();
// Guardamos el nombre del usuario en una variable
$usuario = esc_attr($current_user->user_login);
$args = array(
'author' => $current_user->ID,
'orderby' => 'post_date',
'order' => 'ASC',
'posts_per_page' => -1 // no limit
);
$current_user_posts = get_posts( $args );
echo $args;
?>
Спасибо!!
1 answers
Вы создаете страницу с slug "List" в бэкэнде, а затем в папке theme файл с именем page-listado.php
(заголовок может отличаться ,содержимое страницы мы показываем в конце списков)
<?php get_header(); // header del wordpress ?>
<?php if (get_the_content()) : ?>
<h1><?php the_title(); // título de la página ?></h1>
<?php
global $current_user;
if($current_user->ID != 0) : ?>
<?php
// parametros de query
$the_args = array(
'author' => $current_user->ID,
'post_status' => 'publish',
'orderby' => 'post_date',
'order' => 'DESC',
'posts_per_page' => 15, //-1,
'offset' => 0,
);
// tipo POSTS
$the_args['post_type']='post';
$the_query = new WP_Query($the_args);
?>
<?php if ($the_query-> have_posts ()) :?>
<h2>posts</h2>
<ul>
<?php while ($the_query-> have_posts ()) : $the_query-> the_post(); ?>
<li><?php the_date();?> - <a
href="<?php the_permalink(); ?>"><?php the_title()?></a></li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php
// tipo PAGES
$the_args['post_type']='page';
$the_query = new WP_Query($the_args);
?>
<?php if ($the_query-> have_posts ()) :?>
<h2>pages</h2>
<ul>
<?php while ($the_query-> have_posts ()) : $the_query-> the_post(); ?>
<li><?php the_date();?> - <a
href="<?php the_permalink(); ?>"><?php the_title()?></a></li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php
// tipo ATTACHMENTS
$the_args['post_type']='attachment';
$the_args['post_status']='inherit';
$the_query = new WP_Query($the_args);
?>
<?php if ($the_query-> have_posts ()) :?>
<h2>attachments</h2>
<ul>
<?php while ($the_query-> have_posts ()) : $the_query-> the_post(); ?>
<li><?php the_date();?> - <a
href="<?php the_permalink(); ?>"><?php the_title()?></a></li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); // reseteamos el query?>
<?php
// los comments (el display author va variando según las preferencias del usuario)
$args = array(
'user_id' => $current_user->ID,
);
$comments = get_comments($args);
?>
<?php if (!empty($comments)) :?>
<h2>comments</h2>
<ul>
<?php foreach($comments as $comment) : ?>
<li><?php echo($comment->comment_author .
' - ' . $comment->comment_content); ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<?php endif; ?>
<div class="wp-content"><?php the_content(); // el contenido de la página ?></div>
<?php endif; ?>
<?php get_footer(); // footer del wordpress ?>
Четыре queries один из сообщений, один из страниц, один из attachments, и, наконец, один из комментариев. в первых трех изменяется post_type
, а в случае вложений post_status
, Последний мы делаем с get_comments().