views:

90

answers:

3

I need to display link after each comment, when you click that link, a new page displays that single coment on a new page.

Is that possible?

A: 

(New edited version after OP's comments)

There are many ways to do this. In theory this is the simplest, but maybe not 'most appropriate according to WordPress' way. Take this as a starting point. I haven't tested it, so you may encounter an error or two that should be solvable with some minor tweaks. Let me know if you get stumped and I'll do my best. So conceptually...

You should copy the page.php template file and rename it to 'comments_page.php' (or whatever you like). Open this file in your code editor and find where the following appears: (or create it if it does not exist)

/*Template Name: page*/

and change it to

/*Template Name: comments_page*/

Now open your WordPress admin area and create a new page. Call it whatever you want but don't add any content. In the right hand column, select the template that the page uses from the "Page Template" drop down menu. Select 'comments_page' (or whatever you listed as the template name). This tells WordPress to use your file to show this specific page instead of the default page template. Save the page and note the page_id that WordPress generates.

Now, find your theme's comments template, usually 'comments.php'. Find the function wp_list_comments();. We are going to add the name of a custom function that will control the display of your comments as an argument to this function. For an example, go to the twenty-ten theme's files, open comments.php and you'll see what that looks like:

wp_list_comments( array( 'callback' => 'twentyten_comment' ) );

Open the twenty-ten theme's functions.php and find

function twentyten_comment()

Copy that entire function and paste it into your theme's functions file. Change the name to' my_comment()', and add that to the wp_list_comments function call like this:

wp_list_comments( array('callback'=>'my_comment'));

In your newly-created 'my_comment()' function in your functions.php file, add a link where you want to the separate page of comments (comments_page.php) using get_page_link() and a query var named 'commentID' and the comments ID.

<a href = "<?php echo get_page_link($page_id).'/?commentID='.comment_ID();?>">View this comment</a>

Now to inappropriately add php logic to a template file. Once you understand how this works, you can create a function in your functions.php file and then call it in the theme file...

On comments_page.php ,use $_GET['commentID'] to retrieve the comment's id value from the url, and pass it to get_comment($commentID) to retrieve the single comment and display it on a single page.

if(isset($_GET['commentID'])){$commentID = $_GET['commentID'];}
$comment = get_comment($commentID);

Now you have all the single comments information in the $comment variable as an object.

You can decide how to display the comment, but to start, I recommend copying the contents of your theme's comments template to keep things consistent. It will show exactly the same thing the post page shows, but it sounds like this page is intended more for the permalink to a single comment that you link to from somewhere else.

Hope this helps. Let me know if you run into a snag.

Note: this answer provides info given to me from Todd Perkins over at wordpress.stackexchange.com

kevtrout
Thank you very much! Will look in to this!
Mas Ugn
Thanks again, i managed to pass comment_ID and then show the comment content on a new page. Is it possible to make a "comment page" with comments own permalink so i can referer to it from another website?
Mas Ugn
Look into using get_comments(); here:http://codex.wordpress.org/Function_Reference/get_comments. Create a link in each post to your separate comments page that contains a query var for the post_ID. Use get_comments() on the comments page and pass it the post_ID and other available args listed on the link above to show all the comments for the given post.
kevtrout
So thankful for your help, first I don't quite understand this part "Create a link in each post to your separate comments page that contains a query var for the post_ID". Also curious about how I can get a permalink to just a single comment page (for example comment id 11), I wrote that in my other/duplicate question. Would you mind showing som example code?
Mas Ugn
would like to have http://mysite.com/comment44 or http://mysite.com/comment-permalink-here so i can refer to it from ex. facebook.
Mas Ugn
You say you managed to pass comment_ID and show comment content on a new page. What does the url to this page look like?
kevtrout
@Mas: I've revamped my original answer so it's way more specific. Let me know if it helps.
kevtrout
Hi, i tried this solution but when I click "View Comments" it calls this page:http://mydomain.com/1http://mydomain.com/?page_id=1/?commentID=and I get Page not Found. The "1" i guess is the comment id.What am i doing wrong?
Mas Ugn
@Mas Ugn: It looks like you are getting your root url plus the comment ID plus the page link from `get_page_link()`, and that `the_comment_ID` isn't outputting the ID correctly. Please post the code used to display the link, and the link as coded in your php file.
kevtrout
@kevtrout Thanks for your help, I posted my code below
Mas Ugn
+1  A: 

Hi @Mas Ugn:

I answered your exact question over on WordPress Answers (also a StackExchange site) just yesterday. You can find that answer here. It involved the following four steps:

  1. Setting up the URL Rewriting by adding a query_var, rewrite_tag and a permastruct,
  2. Being sure to flush the rewrite rules in a plugin's activation hook or manually,
  3. Adding a parse_query filter hook to set the query_vars's post to be the comment's post and to disable sticky posts for the query,
  4. Adding a template_include filter hook to filter the template file name to load a template specific template file for a single comment, and lastly
  5. To create the comment template file as /wp-content/themes/%your-theme%/comment.php.

Again, you can find the answer over here.

Hope this helps.

-Mike


UPDATE:

Below is the full content that I had also posted on WordPress Answers:


There are numerous different ways to accomplish this, some more polished than others and practically all of them with potential for conflict with other plugins, but ignoring all that here's one way that is pretty close to what you asked for. :)

This solution will support a URL format like the following where %comment_id% is the numeric ID of your comment from the wp_comments table:

http://example.com/comments/%comment_id%/

First you'll need to configure your URL rewriting using the following code. Hopefully it is reasonably self-explanitory but don't hesitate to ask:

$wp->add_query_var('comment_id');  // Add the "behind-the-scenes" query variable that WordPress will use
$wp_rewrite->add_rewrite_tag('%comment_id%', '([0-9]+)','comment_id=');  // Define a rewrite tag to match that assigns to the query var 
$wp_rewrite->add_permastruct('comment-page', 'comments/%comment_id%');   // Define a URL pattern to match the rewrite tag.

You'll also either need to call this code in a plugin activation hook to flush the rules, or if it's your site you can just save permalinks in the admin console's Settings > Permalinks settings area:

global $wp_rewrite;
$wp_rewrite->flush_rules(false);

Next add a parse_query filter hook. This will be called after WordPress has inspected the query. It tests to see if your added comment_id query_var set and if so it tests to see if you are on the desired URL. If yes then it loads the comment array using get_comment() in order to set the 'p' parameter (which should be set to a post ID) to the post that is related to the comment. That way when WordPress runs the query that it is going to run no matter what at least it loads something you'll need in your comment.php theme template file below and you won't have to ran another query later when you need it. This code also tells WordPress to ignore sticky posts using the oddly named caller_get_posts option:

add_filter( 'parse_query', 'my_parse_query' );
function my_parse_query( $query ) {
    global $wp;
    if (isset($query->query['comment_id']) && substr($wp->request,0,9)=='comments/') { 
        $comment = get_comment($query->query['comment_id']);
        $query->query_vars['p'] =  $comment->comment_post_ID; // Causes the comment's post to be loaded by the query.
        $query->query_vars['caller_get_posts'] = true;  // Keeps sticky posts from invading into the top of our query.
    }
}

Still next you'll need to hook the code in /wp-includes/template-loader.php using the template_include filter. This will be called after WordPress has both inspected the query and loaded the post for the comment. Here you'll first check again for comment_id in the query_var and also for the URL being the one you want. If so we replace the /index.php template page with /comment.php which is a theme template file you will need to create:

add_filter( 'template_include', 'my_template_include' );
function my_template_include( $template ) {
    global $wp,$wp_query;
    if (isset($wp_query->query['comment_id']) && substr($wp->request,0,9)=='comments/') {
        $template = str_replace('/index.php','/comment.php',$template);
    }
    return $template;
}

Lastly now you need to create your theme template file which I've chosen to call /comment.php. Since it's your theme you'll want to make it look like you want but here is an example to get you started:

<?php 
/*
 *  File: /wp-content/themes/my-theme/comment.php
 */ 
global $wp_query,$post;
$comment_id = $wp_query->query['comment_id'];
$comment = get_comment($comment_id);
$permalink = get_permalink($post->ID);
get_header();
?>
<div id="container">
    <div id="comment-<?php echo $comment_id; ?>" class="comment">
        <p>Comment by: <span class="comment-author">
            <a href="<?php echo $comment->comment_author_url; ?>"><?php echo $comment->comment_author; ?></a></span>
            on <span class="comment-date"><?php echo date("D M jS Y", strtotime($comment->comment_date)); ?></span>
          at <span class="comment-time"><?php echo date("h:ia", strtotime($comment->comment_date)); ?></span>
        </p>
        <p>About: <a href="<?php echo $permalink; ?>"><?php echo $post->post_title; ?></a></p>
        <blockquote><?php echo $comment->comment_content; ?></blockquote>
    </div>
</div>
<?php 
get_sidebar();
get_footer();

Any questions? Just ask.

Hope this helps.

P.S. All of the code I describing above can either go in your theme's functions.php file and/or in a plugin of your own. A caveat is for the URL rewrite flushing rules that should go in a plugin activation hook if you are going to include it instead us just flushing them manually in the permalinks section of the admin console. I didn't show how to register an activation hook do but if you want to learn more you can read about it here.

MikeSchinkel
@Mike: Since WordPress Answers is still in private beta, I suggest you copy your answer from there to this place. It can only improve your rep here...
Jan Fabry
Oh, thanks Mike! I think this is what i need. Do you have some example code on this? Would be helpful! Not sure I can follow all the steps i'm afraid...
Mas Ugn
@Mike and @Mas, I asked the linking question on WordPress Answers on behalf of this question. I had the outline in mind of how to accomplish this, but wasn't sure about how to write the actual link. Wasn't trying to scarf this question for my own or anything :) Thanks for your input. I edited my answer below. It shows a much simpler solution, but that doesn't mean it's the best one!
kevtrout
@Jan Fabry: Doh! I wasn't even thinking about that issue. Thanks for pointing it out.
MikeSchinkel
@kevtrout: Yep as I started there are many ways to tackle this problem. Mine answer was but one of those ways. I like it because it fits in nicely with the WordPress architecture using a "comment.php" template file and using WordPress' rewrite system. But again there are many ways to skin a cat (metaphorically speaking, only.)
MikeSchinkel
@mike: I haven't really dug into the rewrite system. I'll check it out.
kevtrout
@kevtrout: Honestly (IMO) the WordPress URL routing system is a nightmare. That's why I submitted this trac ticket and plan to eventually try to replace it (you have to read the entire ticket to really follow where I'm heading: http://core.trac.wordpress.org/ticket/12935)
MikeSchinkel
Thanks so much for the code! Awesome. @MikeSchinkel: I tried out your solution above with no success. Not sure why, did not get an error message. Is it correct that the first 3 code snippets are meant to be in functiions.php, and the next in template-loader.php? I have a solution (without the nice permalinks, just /comment?nr=34) Works, but would have been nicer with your example. Hm...
Mas Ugn
I understand the code in the last snippet, the template-page
Mas Ugn
Everything should go in `functions.php` with the stated caveats for 1.) the two lines starting with `global $wp_rewrite;` and 2.) the `comment.php` template, of course. *NEVER* modify `template-loader.php`; it is core code. If it doesn't work you haven't 1.) flushed your permalinks (by saving them in the admin), 2.) you are not using WordPress 3.0, or 3.) you are using a misbehaving plugin that is conflicting.
MikeSchinkel
Thanks. How do I flush my permalinks? Do you mean revert to default? Can I still use %postname% for my posts and pages?
Mas Ugn
@Mas Ugn: Yes you can still use %postname% for pages $wp_rewrite->flush_rules(false);` and you can put in your theme's `functions.php` but it will make your pages load slightly slower. If you simply save your permalinks in the admin that will flush them too.
MikeSchinkel
@Mas Ugn: In future if you post your WordPress-specific questions at http://wordpress.stackexchange.com/ you'll get answers quicker (and probably better ones too)...
MikeSchinkel
@MikeSchinkel First, thanks for your time on this topic! I managed to do what I wanted but in another way. The page template - no problems. The link with query string i simply used $my_id = $_GET["nr"]; Then I pulled comments with a standard php/mysql-connection. I got a permalink like this http://www.mydomain.com/comment?nr=32. Worked out fine. Actually i wanted a permalink such as http://mydomain.com/first-words-in-comment. But it worked out anyway. Thanks!
Mas Ugn
Really strange why you can't get it to work. Must be another plugin causing problem. BTW, I'm spending most of my time on http://wordpress.stackexchange.com/ so for WordPress questions be sure to ask over there.
MikeSchinkel
A: 

This is my functions.php

  <?php

if ( ! function_exists( 'twentyten_comment' ) ) :

function my_comment( $comment, $args, $depth ) {
    $GLOBALS['comment'] = $comment;
    switch ( $comment->comment_type ) :
        case '' :
    ?>
        <li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>">
            <div id="comment-<?php comment_ID(); ?>">
            <div class="comment-author vcard">
                <?php echo get_avatar( $comment, 40 ); ?>
                <?php printf( __( '%s <span class="says">says:</span>', 'twentyten' ), sprintf( '<cite class="fn">%s</cite>', get_comment_author_link() ) ); ?>
            </div><!-- .comment-author .vcard -->
            <?php if ( $comment->comment_approved == '0' ) : ?>
                <em><?php _e( 'Your comment is awaiting moderation.', 'twentyten' ); ?></em>
                <br />
            <?php endif; ?>

            <div class="comment-meta commentmetadata"><a href="<?php echo esc_url( get_comment_link( $comment->comment_ID ) ); ?>">
                <?php
                    /* translators: 1: date, 2: time */
                    printf( __( '%1$s at %2$s', 'twentyten' ), get_comment_date(),  get_comment_time() ); ?></a><?php edit_comment_link( __( '(Edit)', 'twentyten' ), ' ' );
                ?>
            </div><!-- .comment-meta .commentmetadata -->

            <div class="comment-body"><?php comment_text(); ?></div>

    <a href = "<?php echo get_page_link($page_id).'/?commentID='.comment_ID();?>">View this comment</a>


            <div class="reply">
                <?php comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
            </div><!-- .reply -->
        </div><!-- #comment-##  -->

        <?php
                break;
            case 'pingback'  :
            case 'trackback' :
        ?>
        <li class="post pingback">
            <p><?php _e( 'Pingback:', 'twentyten' ); ?> <?php comment_author_link(); ?><?php edit_comment_link( __('(Edit)', 'twentyten'), ' ' ); ?></p>
        <?php
                break;
        endswitch;
    }
    endif;

This is my comments_page.php

/*Template Name: comments_page*/
<? if(isset($_GET['commentID'])){$commentID = $_GET['commentID'];}
$comment = get_comment($commentID);
 ?>
<?php get_header(); ?>

    <div id="content">
    <?php if (have_posts()) : ?>

        <?php while (have_posts()) : the_post(); ?>

        <div class="post">
            <!--uncomment for header tags--  <h1><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h1>
            <small><b>Posted:</b> <?php the_time('F jS, Y') ?> | <b>Author:</b> <?php the_author_posts_link(); ?> | <b>Filed under:</b> <?php the_category(', ') ?> <?php the_tags(' | <b>Tags:</b> ', ', ', ''); ?> <?php if ( $user_ID ) : 
            ?> | <b>Modify:</b> <?php edit_post_link(); ?> <?php endif; ?>| <?php comments_popup_link('No Comments &#187;', '1 Comment &#187;', '% Comments &#187;'); ?></small>   -->
            <?php the_content('Read the rest of this entry &raquo;'); ?>
             <hr/>
        </div>

        <?php endwhile; ?>

        <div class="navigation">
            <div class="alignleft"><?php next_posts_link('&laquo; Older Entries') ?></div>
            <div class="alignright"><?php previous_posts_link('Newer Entries &raquo;') ?></div>
        </div>

    <?php else : ?>

        <h2 class="center">Not Found</h2>
        <p class="center">Sorry, but you are looking for something that isn't here.</p>

    <?php endif; ?>

    </div>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

This is my comments.php

    <?php // Do not delete these lines
        if (!empty($_SERVER['SCRIPT_FILENAME']) && 'comments.php' == basename($_SERVER['SCRIPT_FILENAME']))
            die ('Please do not load this page directly. Thanks!');

    if (!empty($post->post_password)) { // if there's a password
        if ($_COOKIE['wp-postpass_' . COOKIEHASH] != $post->post_password) {  // and it doesn't match the cookie
            ?>

            <p class="nocomments">This post is password protected. Enter the password to view comments.</p>

            <?php
            return;
        }
    }

    /* This variable is for alternating comment background */
    $oddcomment = 'class="alt" ';
?>

<!-- You can start editing here. -->
<div id="comments">

<?php if ($comments) : ?>

    <h3><?php comments_number('No Comments', 'One Comment', '% Comments' );?> on &#8220;<?php the_title(); ?>&#8221;</h3>

<?php wp_list_comments( array('callback'=>'my_comment')); ?>


 <?php else : // this is displayed if there are no comments so far ?>

    <?php if ('open' == $post->comment_status) : ?>
        <!-- If comments are open, but there are no comments. -->

     <?php else : // comments are closed ?>
        <!-- If comments are closed. -->
        <p class="nocomments">Comments are closed.</p>

    <?php endif; ?>
<?php endif; ?>


<?php if ('open' == $post->comment_status) : ?>

<hr/>

<h4 class="center">Leave a Reply</h4>

<?php if ( get_option('comment_registration') && !$user_ID ) : ?>
<p>You must be <a href="<?php echo get_option('siteurl'); ?>/wp-login.php?redirect_to=<?php echo urlencode(get_permalink()); ?>">logged in</a> to post a comment.</p>
<?php else : ?>

<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform">

<ul class="formlist">

<?php if ( $user_ID ) : ?>

<p>Logged in as <a href="<?php echo get_option('siteurl'); ?>/wp-admin/profile.php"><?php echo $user_identity; ?></a>. <a href="<?php echo get_option('siteurl'); ?>/wp-login.php?action=logout" title="Log out of this account">Log out &raquo;</a></p>


<?php else : ?>

<li><input type="text" name="author" id="author" value="Name <?php if ($req) echo "(required)"; ?>" size="22" tabindex="1" <?php if ($req) echo "aria-required='true'"; ?> onblur="if(this.value.length == 0) this.value='Name <?php if ($req) echo "(required)"; ?>';" onclick="if(this.value == 'Name <?php if ($req) echo "(required)"; ?>') this.value='';" /></li>

<li><input type="text" name="email" id="email" value="Mail (will not be published) <?php if ($req) echo "(required)"; ?>" size="22" tabindex="2" <?php if ($req) echo "aria-required='true'"; ?> onblur="if(this.value.length == 0) this.value='Mail (will not be published) <?php if ($req) echo "(required)"; ?>';" onclick="if(this.value == 'Mail (will not be published) <?php if ($req) echo "(required)"; ?>') this.value='';" /></li>

<li><input type="text" name="url" id="url" value="Website" size="22" tabindex="3" onblur="if(this.value.length == 0) this.value='Website';" onclick="if(this.value == 'Website') this.value='';" /></li>

<?php endif; ?>

<!--<p><small><strong>XHTML:</strong> You can use these tags: <code><?php echo allowed_tags(); ?></code></small></p>-->

<li><textarea name="comment" id="comment" cols="70%" rows="10" tabindex="4" value="Enter comment here."></textarea></li>

<li class="submitbutton"><input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" /></li>
<input type="hidden" name="comment_post_ID" value="<?php echo $id; ?>" />

<?php do_action('comment_form', $post->ID); ?>

</ul>

</form>

<?php endif; // If registration required and not logged in ?>

<?php endif; // if you delete this the sky will fall on your head ?>

</div>
Mas Ugn
@Mas: as far as I can tell, when you call `get_page_link($page_id)` in `function my_comment()`, you haven't defined `$page_id`. Replace this variable with the ID that wordpress gave to your comments page. Refer to my previous answer where I stated: "Save the page and note the page_id that WordPress generates. " When you create a new page, wordpress lists the permalink under the title input field, labeled: "permalink". It'll be a url with "?page_id=xxxx" at the end. That's the number you should pass to `get_page_link()`
kevtrout
kevtrout