WordPress.org

Ready to get started?Download WordPress

Forums

How to use the_post action hook (2 posts)

  1. Bagira
    Member
    Posted 4 years ago #

    Hi! I use filter the_posts, that create posts list from my specific table:

    function add_special_posts($posts) {
       global $wpdb;    	    
    
       if (is_category('11')) {
    
          $my_table_name = $wpdb->prefix . "posts";
          $sql_select = "SELECT * FROM " . $my_table_name;
          $result = $wpdb->get_results($sql_select, ARRAY_A);
    
          $posts = array();    
    
          foreach ($result as $mytable_value) {
    
             $post  = new stdClass();   
    
             $post->ID = $mytable_value['id'];
             $post->post_author = '1';
             $post->post_date = date('Y-m-d H:m:s');
             $post->post_type = 'post';
             $post->post_title = $mytable_value['portfolio_name'];
             $post->post_content = $mytable_value['full_description'];
             $post->post_status = 'open';
    	 $post->comment_status = 'open';
    	 $post->ping_status = 'open';
    
             $posts[] = $post;
          }
       }
       return $posts;
    
      }

    It works fine: i get posts list from my specific table in category with id=11. Now I want to view a single post page with data from my_table_name. I suspect that I use the_post action hook or may be loop_start action hook.
    When I use something like as:

    function view_single_special_post($post) {
       global $wpdb; 
    
       if (is_single() && in_category('11',$post->ID)) {  
    
          $portfolio_table_name = $wpdb->prefix . "portfolio";
          $sql_select = "SELECT * FROM " . $portfolio_table_name;
          $result = $wpdb->get_results($sql_select, ARRAY_A);
    
          foreach ($result as $mytable_value) {
    
              $post->ID = $mytable_value['id'];
              $post->post_author = '1';
              $post->post_date = date('Y-m-d H:m:s');
              $post->post_type = 'post';
              $post->post_title = $mytable_value['portfolio_name'];
              $post->post_content = $mytable_value['full_description'];
              $post->post_status = 'open';
              $post->comment_status = 'open';
              $post->ping_status = 'open';
          }
       }
       return $post;
    }
    
    add_action('the_post', 'view_single_special_post');

    It doesn't work for category wiht id=11, which has data from my specific table $my_table_name, but works for other categories. I write it at the plugin file.

    Help me please and sorry for my English.

  2. Francis Crossen
    Member
    Posted 4 years ago #

    the_post action hook will pass an array of $posts to your function, not a single post.

    You need to return array( '0' => $your_post )

Topic Closed

This topic has been closed to new replies.

About this Topic