Tag Archives: Wordpress custom code

Displaying related posts in WordPress

Displaying related posts on a website can indeed be beneficial for engaging readers, increasing their time on the site, and providing SEO benefits through internal linking. Here are some approaches you can consider for displaying related posts:

  • Content-based Recommendations: Use algorithms that analyze the content of the current post and suggest related posts based on similarities in topics, keywords, or tags. This can be done by examining the metadata of each post and comparing it to other posts in the database.
  • Category or Tag Matching: Assign categories or tags to your posts and display related posts that share similar categories or tags. This approach is useful when you have a well-structured taxonomy or tagging system in place.
  • User Behavior Analysis: Track user behavior on your website, such as their browsing history, clicked links, or search queries. Based on this data, recommend related posts that are popular among users who have shown similar interests or reading patterns.
  • Popular or Trending Posts: Display a list of popular or trending posts based on factors like views, comments, or social media shares. This approach can be effective in showcasing content that is currently popular among your audience.
  • Manual Selection: Curate related posts manually by linking them directly within the content or by creating a designated section for recommended posts. This approach allows for more control over the selection process but may require additional effort.
  • Hybrid Approaches: Combine multiple methods mentioned above to generate related post recommendations. For example, you can prioritize content-based recommendations but also include popular posts or manually curated selections.
  • Visual Presentation: Consider the visual presentation of related posts. You can display them as thumbnails, excerpts, or titles with featured images to make them visually appealing and enticing for readers to click.

Additionally, it’s important to consider the placement of related posts. Some common locations include underneath the main content, in a sidebar, or at the end of the post. A/B testing can help determine the most effective placement for maximizing engagement.

Remember to regularly update your related post recommendations as new content is published, and periodically evaluate the performance of your chosen method(s) to ensure they are achieving the desired results.

To work with, you will need some sample content. So, let’s create a few posts and assign them on a few categories.

Implementation Steps:

  1. In step one you have to retrieve the terms assigned to current post for which you will retrieve posts from blog. For, this we can use this snippet.
    
        // get related posts
        $term_list = wp_get_post_terms(get_the_ID(), 'my_taxonomy', array("fields" => "ids"));
    

    In this, we used a predefined function of wordpress “wp_get_post_terms()” for details of this function please refer to codex link.

  2. After retrieving terms assigned to current post you have to retrieve the related posts using “WP_Query”. Code will be look a like as follows:
    
    
         $args = array(
            'post_type' => 'my_post_type',
            'post__not_in' => array(get_the_ID()),
            'orderby' => 'rand',
            'tax_query' => array(
                'relation' => 'AND',
                array(
                    'taxonomy' => 'articles_cat',
                    'field' => 'term_id',
                    'terms' => $term_list,
                    'operator' => 'IN',
                ),
            ),
        );
    
        $wp_query = new WP_Query($args);
    

    After, this we will get list of posts in (Object Array), which should be used with while loop for displaying content retrieved in list.

  3. This is the last step in showing related posts. The result you get in step, put it in while loop to show final results.
    
    
        while ($query->have_posts()) : $query->the_post();
                /* Here add your html as per your design */
                echo $post->ID;
                echo $post->post_title;
                echo $post->post_content;
                echo '< img width="298" height="198" src ="'.wp_get_attachment_url(get_post_thumbnail_id($post->ID)).'" u="image">';
                echo get_permalink();
        endwhile;
        wp_reset_query();
    
    

  4. Finally, after combining all the steps you will get the following code.
    
    
        // get related posts
        $term_list = wp_get_post_terms(get_the_ID(), 'my_taxonomy', array("fields" => "ids"));
        $args = array(
            'post_type' => 'my_post_type',
            'post__not_in' => array(get_the_ID()),
            'orderby' => 'rand',
            'tax_query' => array(
                'relation' => 'AND',
                array(
                    'taxonomy' => 'articles_cat',
                    'field' => 'term_id',
                    'terms' => $term_list,
                    'operator' => 'IN',
                ),
            ),
        );
    
        $query = new WP_Query($args);
        
        while ($query->have_posts()) : $query->the_post();
            echo $post->ID;
            echo $post->post_title;
            echo $post->post_content;
            echo '< img width="298" height="198" src ="'.wp_get_attachment_url(get_post_thumbnail_id($post->ID)).'" u="image">';
            echo get_permalink();
        endwhile;
        wp_reset_query();
    
    

Send Mail from an AMP page

In one of my projects I embedded Google’s new open-source initiative, AMP(Accelerated Mobil Pages). It was a WordPress website. I was all done with most of the part of website, however there was still a module which needs research i.e. implementing contact form into website.

While, we implementing any form in a website, we need to add validations as well as the data-handler scripts. So, I had two problems to resolve on:
1. I cannot use Javascript or jQuery for the validation. Although, I had HTML validation methods, but these are not enough. So, I needed some way to validate the form as good as we do with Javascript.
2. I had to send mail after the submission of form and redirect user to thank you page.

Thanks, to the AMP community on git-hub from where I get to know the various attributes we can use with `amp-form`. Basically, AMP provides many of event-handlers by using which you can implement the validations and in forms. You, can various event handlers on this git-hub library.

You can check amp-form attributes and there usage here.

You can send mail from your AMP page. Here is an example:

HTML of AMP form

<!doctype html>
<html amp lang="en">
  <head>
    <meta charset="utf-8">
    <script async src="https://cdn.ampproject.org/v0.js"></script>
    <title>Hello, AMPs</title>
    <link rel="canonical" href="http://example.ampproject.org/article-metadata.html" />
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
    <script type="application/ld+json">
      {
        "@context": "http://schema.org",
        "@type": "NewsArticle",
        "headline": "Open-source framework for publishing content",
        "datePublished": "2015-10-07T12:02:41Z",
        "image": [
          "logo.jpg"
        ]
      }
    </script>
    <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
    <script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>
  </head>
  <body>
    <h1>Hello World!</h1>
      <form target="_top" action-xhr="https://test.php" method="post" name="test">
        <input type="text" name="name" value="ABRA KA DABRA!">
        <input type="submit"/>
    </form>
  </body>
</html>

PHP Code for Handling form request:

<?php
if(!empty($_POST))
{
    $name = $_POST['name'];

    /*/ this is the email we get from visitors*/
    $domain_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
    $redirect_url = 'https://example.com/thank-you';

    /*//-->MUST BE 'https://';*/
    header("Content-type: application/json");
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Allow-Origin: *.ampproject.org");
    header("AMP-Access-Control-Allow-Source-Origin: ".$domain_url);


    /*/ For Sending Error Use this code /*/
    if(!mail("[email protected]" , "Test submission" , "email: $name <br/> name: $name" , "From: $name\n ")){
        header("HTTP/1.0 412 Precondition Failed", true, 412);

        echo json_encode(array('errmsg'=>'There is some error while sending email!'));
        die();
    }
    else
    {
        /*/--Assuming all validations are good here--*/
        if( empty($redirect_url))
        {
            header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");
        }
        else
        {
            header("AMP-Redirect-To: ".$redirect_url);
            header("Access-Control-Expose-Headers: AMP-Redirect-To, AMP-Access-Control-Allow-Source-Origin");        }
            echo json_encode(array('successmsg'=>$_POST['name'].'My success message. [It will be displayed shortly(!) if with redirect]'));
        die();
    }
}?>