Forum

Thread tagged as: Question, Addons, Blog

Random Blog Post w/ comments section

Hi,

I am wanting to make a page that pulls in one random blog post out of all my blog posts.

I have been looking at the perch_blog_custom() documentation over at

https://docs.grabaperch.com/addons/blog/page-functions/custom/

but i cant seem to get a random blog post to show up.

I would also like the comments that are on that blog post to show with the new comment form.

ltjfan site

ltjfan site 0 points

  • 5 years ago
Rachel Andrew

Rachel Andrew 394 points
Perch Support

What have you tried that isn't working?

Please post your code and Diagnostics Report with any request - it helps us to help you!

H Rachel,

The code i have so far is

                <?php
                    perch_blog_custom(array(
                        'count' => '1',
                        'template' => 'post.html',  
                        'sort-order' => 'RAND'                    
                    ));
                ?>
                <?php perch_blog_post_comments(perch_get('s')); ?>

                <?php perch_blog_post_comment_form(perch_get('s')); ?>   

The code is showing up the first post only, rather than showing a random article.

As for the comments and comments form, i literally have now idea how to get that to work. it isnt showing anything up.

my Diagnostics report is as follows

Perch: 2.8.26
Production mode: Production (100)
Installed apps: content (2.8.26), assets (2.8.26), categories (2.8.26), perch_blog (5.0), perch_forms (1.8.3)
DB driver: PDO
DB tables: perch2_blog_authors (1), perch2_blog_comments (1), perch2_blog_index (47), perch2_blog_posts (2), perch2_blog_posts_to_tags (0), perch2_blog_sections (1), perch2_blog_tags (0), perch2_blogs (1), perch2_categories (0), perch2_category_counts (0), perch2_category_sets (1), perch2_content_index (93), perch2_content_items (40), perch2_content_regions (6), perch2_forms (2), perch2_forms_responses (4), perch2_navigation (0), perch2_navigation_pages (0), perch2_page_templates (1), perch2_pages (6), perch2_resource_log (7), perch2_resource_tags (0), perch2_resources (5), perch2_resources_to_tags (0), perch2_settings (23), perch2_user_passwords (0), perch2_user_privileges (37), perch2_user_role_privileges (16), perch2_user_roles (2), perch2_users (1)
Users: 1
App runtimes:
<?php
    $apps_list = array(
        'content', 
        'categories',
        'perch_blog',
        'perch_forms',
    );
Scheduled tasks for perch_blog: delete_spam_comments (1440 mins)
Editor plug-ins: markitup
H1: 850291ec3d2c3f2cab9b0220c68a3892
L1: e5f3e2bccf5ff8033972b9aa389cb43d
F1: 2edba60ed1f613d6dd804feb202456a2
headerColour: #ffffff
content_singlePageEdit: 1
helpURL:
siteURL: /beardfacts/
hideBranding: 1
content_collapseList: 1
lang: en-gb
update_2.8.26: done
latest_version: 2.8.15
on_sale_version: 2.8.26
perch_blog_update: 5.0.1
perch_blog_post_url: post.php?s={postSlug}
headerScheme: light
dashboard: 1
perch_blog_slug_format: %Y-%m-%d-{postTitle}
perch_blog_akismet_key:
perch_blog_max_spam_days: 0
hide_pwd_reset: 0
content_hideNonEditableRegions: 0
content_frontend_edit: 0
perch_blog_comment_notify: 0
logoPath: /perch/resources/beardfactslogo.svg
perch_blog_site_name: Beard Facts : Facts about beards
PERCH_DEVELOPMENT: 10
PERCH_STAGING: 50
PERCH_PRODUCTION: 100
PERCH_DB_USERNAME: ltjfansi_beardfa
PERCH_DB_SERVER: localhost
PERCH_DB_DATABASE: ltjfansi_beardFacts
PERCH_DB_PREFIX: perch2_
PERCH_TZ: UTC
PERCH_EMAIL_FROM: jordan@beardfacts.co.uk
PERCH_EMAIL_FROM_NAME: Jordan Sayner
PERCH_LOGINPATH: /perch
PERCH_PATH: /home3/ltjfansi/public_html/beardfacts/perch
PERCH_CORE: /home3/ltjfansi/public_html/beardfacts/perch/core
PERCH_RESFILEPATH: /home3/ltjfansi/public_html/beardfacts/perch/resources
PERCH_RESPATH: /perch/resources
PERCH_HTML5: 1
PERCH_RUNWAY:
PERCH_ERROR_MODE: DIE
PERCH_DATE_LONG: %d %B %Y
PERCH_DATE_SHORT: %d %b %Y
PERCH_TIME_SHORT: %H:%M
PERCH_TIME_LONG: %H:%M:%S
PERCH_RUNWAY_ROUTED:
PERCH_STRONG_PASSWORDS:
PERCH_DEBUG:
PERCH_PREVIEW_ARG: preview
PERCH_TEMPLATE_PATH: /home3/ltjfansi/public_html/beardfacts/perch/templates
PERCH_DEFAULT_DOC: index.php
PERCH_DEFAULT_EXT: .php
PERCH_PRODUCTION_MODE: 100
PERCH_RWD:
PERCH_HTML_ENTITIES:
PERCH_SSL:
PERCH_STRIPSLASHES:
PERCH_PROGRESSIVE_FLUSH: 1
PERCH_PARANOID:
PERCH_FORCE_SECURE_COOKIES:
PERCH_PASSWORD_MIN_LENGTH: 6
PERCH_MAX_FAILED_LOGINS: 10
PERCH_AUTH_LOCKOUT_DURATION: 1 HOUR
PERCH_VERIFY_UPLOADS:
PERCH_AUTH_PLUGIN:
PERCH_DB_CHARSET: utf8
PERCH_DB_PORT:
PERCH_DB_SOCKET:
PERCH_SESSION_TIMEOUT_MINS: 20
HOSTING SETTINGS

PHP: 5.5.30
Zend: 2.5.0
OS: Linux
SAPI: cgi-fcgi
Safe mode: not detected
MySQL client: 5.5.42-37.1
MySQL server: 5.5.42-37.1
Free disk space: 63.91 GB
Extensions: Core, date, ereg, libxml, openssl, pcre, sqlite3, zlib, bcmath, bz2, calendar, ctype, curl, dom, hash, fileinfo, filter, ftp, gd, gettext, gmp, SPL, iconv, session, intl, json, mbstring, mcrypt, mssql, mysql, mysqli, odbc, standard, PDO, pdo_mysql, pdo_sqlite, Phar, posix, pspell, Reflection, imap, SimpleXML, soap, sockets, exif, tidy, tokenizer, wddx, xml, xmlreader, xmlrpc, xmlwriter, xsl, zip, cgi-fcgi, mhash
GD: Yes
ImageMagick: No
PHP max upload size: 2M
PHP max form post size: 8M
PHP memory limit: 128M
Total max uploadable file size: 2M
Resource folder writeable: Yes
Session timeout: 24 minutes
Native JSON: Yes
Filter functions: Yes
Transliteration functions: Yes
DOCUMENT_ROOT: /home3/ltjfansi/public_html/beardfacts
GATEWAY_INTERFACE: CGI/1.1
HTTP_ACCEPT: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
HTTP_ACCEPT_ENCODING: gzip, deflate, sdch
HTTP_ACCEPT_LANGUAGE: en-US,en;q=0.8,ms;q=0.6
HTTP_CONNECTION: close
HTTP_COOKIE: _ga=GA1.3.1092428743.1456527034; cmsa=1; PHPSESSID=b50acd98d4756dd79e82d0612fb3a726
HTTP_HOST: www.beardfacts.co.uk
HTTP_REFERER: https://www.beardfacts.co.uk/perch/core/settings/diagnostics/
HTTP_UPGRADE_INSECURE_REQUESTS: 1
HTTP_USER_AGENT: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36
HTTP_X_HTTP_PROTO: HTTP/1.1
HTTP_X_LOG_7526: 80.192.214.35
HTTP_X_REAL_IP: 80.192.214.35
PATH: /bin:/usr/bin
PHPRC: /home3/ltjfansi
QUERY_STRING: extended
REDIRECT_STATUS: 200
REMOTE_ADDR: 80.192.214.35
REMOTE_PORT: 42428
REQUEST_METHOD: GET
REQUEST_URI: /perch/core/settings/diagnostics/?extended
SCRIPT_FILENAME: /home3/ltjfansi/public_html/beardfacts/perch/core/settings/diagnostics/index.php
SCRIPT_NAME: /perch/core/settings/diagnostics/index.php
SERVER_ADDR: 192.254.232.193
SERVER_ADMIN: webmaster@beardfacts.psykestudios.co.uk
SERVER_NAME: www.beardfacts.co.uk
SERVER_PORT: 80
SERVER_PROTOCOL: HTTP/1.1
SERVER_SIGNATURE: <address>Apache Server at www.beardfacts.co.uk Port 80</address>
SERVER_SOFTWARE: Apache
UNIQUE_ID: VtQhpsY5960AAGVjE1UAAACu
PHP_SELF: /perch/core/settings/diagnostics/index.php
REQUEST_TIME_FLOAT: 1456742822.9056
REQUEST_TIME: 1456742822
argc: 1
Drew McLellan

Drew McLellan 2638 points
Perch Support

When you're using perch_get('s') do you mean to use the slug of the retrieved post?

Drew McLellan said:

When you're using perch_get('s') do you mean to use the slug of the retrieved post?

Im not really sure, thats the code in the example blog post to get comments. i suppose for that to work i need to be pulling in a slug which i current am not doing.

Sorry, Im new to Perch, 2nd site I've built using it (first with a blog) and Im more of a front end dev than a back end dev.

Drew McLellan

Drew McLellan 2638 points
Perch Support

<?php

$posts = perch_blog_custom(array(
    'count' => '1',
    'template' => 'post.html',  
    'sort-order' => 'RAND',
    'skip-template'=> true,
    'return-html' => true,             
));

echo $posts[0]['html'];
$slug = $post[0]['postSlug'];

perch_blog_post_comments($slug);

perch_blog_post_comment_form($slug); 
?>  

Hi, Thanks for that

But that didn't work, and now its not even showing up a blog post at all.

                <?php
                    perch_blog_custom(array(
                        'count' => '1',
                        'template' => 'post.html',  
                        'sort-order' => 'RAND'                    
                    ));
                ?>

The above code shows one item. but it doesn't show a random item. Do i meed to pull in all my blogposts into an array and pick one at random. something a bit like this (this code doesn't actually work :-(. )

                    $facts = perch_blog_post(perch_get('postSlug'), array(
                        'skip-template'=>true,
                    ));
                    if (count($facts)) {
                        $fact_slugs = array();
                        foreach($facts as $fact) {
                            $fact_slugs[] = $fact['postSlug'];
                        }
                    }
                    echo $fact_slugs[array_rand($fact_slugs)];

then where the echo is i render out the blog post Im after

                    $data = perch_blog_custom(array(
                        'filter'=>'postSlug',
                        'match'=>'eq',
                        'value'=>$fact_slugs,
                        'skip-template'=>true, 
                    ));

                    $data = $data[0]; 
Rachel Andrew

Rachel Andrew 394 points
Perch Support

What is output if you turn on debug?

Hi Rachel,

My debug output is

Debug Message
[1] SELECT * FROM perch2_pages WHERE pagePath='/random.php' LIMIT 1
Using template: /templates/pages/attributes/default.html
Using sub-template: /templates/pages/attributes/seo.html
Using sub-template: /templates/pages/attributes/facebook.html
Using sub-template: /templates/pages/attributes/twitter.html
[5] SELECT * FROM perch2_pages WHERE pageNew=0 AND pageHidden=0 AND pageDepth >=0 AND pageDepth<=1 ORDER BY pageTreePosition ASC
[1] SELECT pageTreePosition FROM perch2_pages WHERE pagePath='/random.php' LIMIT 1
[1] SELECT pageID FROM perch2_pages WHERE pageTreePosition IN ('000-003', '000') ORDER BY pageTreePosition DESC
[5] Using template: /templates/navigation/item.html
[1] SELECT SQL_CALC_FOUND_ROWS DISTINCT tbl.* FROM ( SELECT idx.itemID, main.*, idx2.indexValue as sortval FROM perch2_blog_index idx JOIN perch2_blog_posts main ON idx.itemID=main.postID AND idx.itemKey='postID' JOIN perch2_blog_index idx2 ON idx.itemID=idx2.itemID AND idx.itemKey='postID' AND idx2.indexKey='_id' WHERE 1=1 AND idx.itemID=idx2.itemID AND idx.itemKey=idx2.itemKey GROUP BY idx.itemID, idx2.indexValue ) as tbl WHERE (postStatus='Published' AND postDateTime<='2016-03-01 11:14:00' ) GROUP BY itemID, sortval ORDER BY sortval ASC LIMIT 0, 1
[1] SELECT FOUND_ROWS() AS `count`
[23] SELECT DISTINCT settingID, settingValue FROM perch2_settings WHERE userID=0
[1] Using template: /addons/apps/perch_blog/templates/blog/post.html
[1] SELECT * FROM perch2_blog_authors ORDER BY authorFamilyName, authorGivenName ASC
[1] SELECT * FROM perch2_blog_sections ORDER BY sectionTitle ASC
[1] SELECT * FROM perch2_blogs ORDER BY blogTitle ASC
[1] SELECT * FROM perch2_blog_posts WHERE postStatus='Published' AND postDateTime<='2016-03-01 11:14:00' AND postSlug=''
[nil] SELECT * FROM perch2_blog_comments WHERE 1=1 AND postID=0 AND commentStatus='LIVE' ORDER BY commentDateTime ASC
[] Using template: /addons/apps/perch_blog/templates/blog/comment.html
[0] Using template: /addons/apps/perch_blog/templates/blog/comment_form.html
Array
(
    [type] => 8
    [message] => Undefined variable: post
    [file] => /home3/ltjfansi/public_html/beardfacts/random.php
    [line] => 110
)

using the code

                $posts = perch_blog_custom(array(
                    'count' => '1',
                    'template' => 'post.html',  
                    'sort-order' => 'RAND',
                    'skip-template'=> true,
                    'return-html' => true,             
                ));

                echo $posts[0]['html'];
                $slug = $post[0]['postSlug'];

                perch_blog_post_comments($slug);

                perch_blog_post_comment_form($slug); 
Drew McLellan

Drew McLellan 2638 points
Perch Support

There was a typo:

$slug = $posts[0]['postSlug'];

Doh, how did I miss that.

Now I am just struggling to get the article to be random rather than the first blog post i posted.

Hi Jordan,

I think even for random you need to sort by something. So pick any id from your template and use that. E.g.:

<?php
                    perch_blog_custom(array(
                        'count' => '1',
                        'template' => 'post.html',
                        'sort'=>'title',  
                        'sort-order' => 'RAND'                    
                    ));
?>

Hope this helps

Cheers for all the help guys, but now there seems to be a different problem.

The comments are showing fine, but now im getting an new error when trying to load the actual post.

the code im using is

                <?php

                    $posts = perch_blog_custom(array(
                        'count' => '1',
                        'template' => 'post.html',
                        'sort' => 'postTitle',    
                        'sort-order' => 'RAND',
                        'skip-template'=> true,
                        'return-html' => true,             
                    ));

                    echo $posts[0]['html'];

                    $slug = $posts[0]['postSlug'];

                    perch_blog_post_comments($slug);

                    perch_blog_post_comment_form($slug); 

                ?> 

my debug is

Debug Message
[1] SELECT * FROM perch2_pages WHERE pagePath='/random.php' LIMIT 1
Using template: /templates/pages/attributes/default.html
Using sub-template: /templates/pages/attributes/seo.html
Using sub-template: /templates/pages/attributes/facebook.html
Using sub-template: /templates/pages/attributes/twitter.html
[5] SELECT * FROM perch2_pages WHERE pageNew=0 AND pageHidden=0 AND pageDepth >=0 AND pageDepth<=1 ORDER BY pageTreePosition ASC
[1] SELECT pageTreePosition FROM perch2_pages WHERE pagePath='/random.php' LIMIT 1
[1] SELECT pageID FROM perch2_pages WHERE pageTreePosition IN ('000-003', '000') ORDER BY pageTreePosition DESC
[5] Using template: /templates/navigation/item.html
[1] SELECT SQL_CALC_FOUND_ROWS DISTINCT tbl.* FROM ( SELECT idx.itemID, main.*, idx2.indexValue as sortval FROM perch2_blog_index idx JOIN perch2_blog_posts main ON idx.itemID=main.postID AND idx.itemKey='postID' JOIN perch2_blog_index idx2 ON idx.itemID=idx2.itemID AND idx.itemKey='postID' AND idx2.indexKey='postTitle' WHERE 1=1 AND idx.itemID=idx2.itemID AND idx.itemKey=idx2.itemKey GROUP BY idx.itemID, idx2.indexValue ) as tbl WHERE (postStatus='Published' AND postDateTime<='2016-03-01 21:35:00' ) GROUP BY itemID, sortval ORDER BY RAND()LIMIT 0, 1
[1] SELECT FOUND_ROWS() AS `count`
[23] SELECT DISTINCT settingID, settingValue FROM perch2_settings WHERE userID=0
[1] Using template: /addons/apps/perch_blog/templates/blog/post.html
[1] SELECT * FROM perch2_blog_authors ORDER BY authorFamilyName, authorGivenName ASC
[1] SELECT * FROM perch2_blog_sections ORDER BY sectionTitle ASC
[1] SELECT * FROM perch2_blogs ORDER BY blogTitle ASC
[1] SELECT * FROM perch2_blog_posts WHERE postStatus='Published' AND postDateTime<='2016-03-01 21:35:00' AND postSlug='beardfact-1'
[2] SELECT * FROM perch2_blog_comments WHERE 1=1 AND postID=1 AND commentStatus='LIVE' ORDER BY commentDateTime ASC
[2] Using template: /addons/apps/perch_blog/templates/blog/comment.html
[1] SELECT * FROM perch2_blog_posts WHERE postID=1 AND postStatus='Published' AND postDateTime<='2016-03-01 21:35:00'
Using template: /addons/apps/perch_blog/templates/blog/comment_form.html
Array
(
    [type] => 8
    [message] => Undefined index: html
    [file] => /home3/ltjfansi/public_html/beardfacts/random.php
    [line] => 96
)

line 96 is

                    echo $posts[0]['html'];

Sorry to both everyone, it is very much appreciated.

Drew McLellan

Drew McLellan 2638 points
Perch Support

What does this give you?

print_r($posts);

it now shows the post and comments section perfectly (random article each page view aswell)

but i'm getting this array wrapped around it

Array ( [0] => Array ( [excerpt] =>
BeardFact #1
[image] => /perch/resources/quote-1.jpg [categories] => [postCommentCount] => 2 [itemID] => 1 [postID] => 1 [blogID] => 1 [postTitle] => BeardFact #1 [postSlug] => beardfact-1 [postDateTime] => 2016-02-27 01:27:50 [postDescRaw] => BeardFact #1 [postDescHTML] =>
BeardFact #1
[postDynamicFields] => {"excerpt":{"_flang":"markdown","raw":"BeardFact #1","processed":"
BeardFact #1<\/p>"},"image":{"assetID":"1","title":"Quote 1","_default":"\/perch\/resources\/quote-1.jpg","bucket":"default","path":"quote-1.jpg","size":37010,"w":700,"h":280,"mime":"image\/jpeg","sizes":{"thumb":{"w":"150","h":"60","target_w":150,"target_h":150,"density":2,"path":"quote-1-thumb@2x.jpg","size":8529,"mime":"","assetID":"2"},"w50h50c1":{"w":"50","h":"50","target_w":"50","target_h":"50","crop":"true","density":"1","path":"quote-1-w50h50.jpg","size":1770,"mime":"","assetID":"5"}}},"categories":null,"postCommentCount":"0"} [postTags] => [postStatus] => Published [authorID] => 0 [sectionID] => 1 [postImportID] => [postLegacyURL] => [postAllowComments] => 1 [postTemplate] => post.html [postMetaTemplate] => post_meta.html [sortval] => BeardFact #1 [paging] => 1 [total] => 7 [number_of_pages] => 7 [total_pages] => 7 [per_page] => 1 [current_page] => 1 [lower_bound] => 1 [upper_bound] => 1 [prev_url] => [next_url] => /random.php?page=2 [prev_page_number] => [next_page_number] => 2 [not_last_page] => 1 [perch_excerpt] =>
BeardFact #1
[perch_image] => /perch/resources/quote-1.jpg [perch_categories] => [perch_postCommentCount] => 0 [postURL] => post.php?s=beardfact-1 ) [html] =>

blog post here

)

there are no errors in my debug report

Debug Message
[1] SELECT * FROM perch2_pages WHERE pagePath='/random.php' LIMIT 1
Using template: /templates/pages/attributes/default.html
Using sub-template: /templates/pages/attributes/seo.html
Using sub-template: /templates/pages/attributes/facebook.html
Using sub-template: /templates/pages/attributes/twitter.html
[5] SELECT * FROM perch2_pages WHERE pageNew=0 AND pageHidden=0 AND pageDepth >=0 AND pageDepth<=1 ORDER BY pageTreePosition ASC
[1] SELECT pageTreePosition FROM perch2_pages WHERE pagePath='/random.php' LIMIT 1
[1] SELECT pageID FROM perch2_pages WHERE pageTreePosition IN ('000-003', '000') ORDER BY pageTreePosition DESC
[5] Using template: /templates/navigation/item.html
[1] SELECT SQL_CALC_FOUND_ROWS DISTINCT tbl.* FROM ( SELECT idx.itemID, main.*, idx2.indexValue as sortval FROM perch2_blog_index idx JOIN perch2_blog_posts main ON idx.itemID=main.postID AND idx.itemKey='postID' JOIN perch2_blog_index idx2 ON idx.itemID=idx2.itemID AND idx.itemKey='postID' AND idx2.indexKey='postTitle' WHERE 1=1 AND idx.itemID=idx2.itemID AND idx.itemKey=idx2.itemKey GROUP BY idx.itemID, idx2.indexValue ) as tbl WHERE (postStatus='Published' AND postDateTime<='2016-03-01 22:25:00' ) GROUP BY itemID, sortval ORDER BY RAND()LIMIT 0, 1
[1] SELECT FOUND_ROWS() AS `count`
[23] SELECT DISTINCT settingID, settingValue FROM perch2_settings WHERE userID=0
[1] Using template: /addons/apps/perch_blog/templates/blog/post.html
[1] SELECT * FROM perch2_blog_authors ORDER BY authorFamilyName, authorGivenName ASC
[1] SELECT * FROM perch2_blog_sections ORDER BY sectionTitle ASC
[1] SELECT * FROM perch2_blogs ORDER BY blogTitle ASC
[1] SELECT * FROM perch2_blog_posts WHERE postStatus='Published' AND postDateTime<='2016-03-01 22:25:00' AND postSlug='beardfact-2'
[2] SELECT * FROM perch2_blog_comments WHERE 1=1 AND postID=2 AND commentStatus='LIVE' ORDER BY commentDateTime ASC
[2] Using template: /addons/apps/perch_blog/templates/blog/comment.html
[1] SELECT * FROM perch2_blog_posts WHERE postID=2 AND postStatus='Published' AND postDateTime<='2016-03-01 22:25:00'
Using template: /addons/apps/perch_blog/templates/blog/comment_form.html
Drew McLellan

Drew McLellan 2638 points
Perch Support

Oh, my mistake. Should be this:

echo $posts['html'];

You are all legends, thank you so much. Works perfect.

now which post do i mark as the solution, haha.