PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label posts. Show all posts
Showing posts with label posts. Show all posts

Saturday, July 9, 2022

[FIXED] How to sort a 'query_posts' function by custom field, while limiting posts by another custom field

 July 09, 2022     loops, php, posts, wordpress     No comments   

Issue

I'm querying a series of posts in WP with the following function:

<?php 
$thirtydays = date('Y/m/d', strtotime('+30 days'));
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts( array( 
    'post_type' => array('post', 'real-estate'), 
    'meta_key' => 'Time          Available', 
    'meta_compare' => '<=', 
    'meta_value' => $thirtydays, 
    'paged' => $paged )); 
?>

This part is working fine. It's basically pulling all my Real Estate posts, but only returning results that have a 'Time Available' of 30 days or less.

I need this to also order the posts in ascending order from low to high using the data from another custom field, 'Price.'

Whenever I add the standard 'orderby' => 'meta_value', 'meta_key' => 'Price' it no longer shows results within 30 days.

Is there any way I can combine these two? And is it possible to add a button which re-runs the query and sorts by Price, Bedrooms, etc? Or is this too specific for WP?


Solution

I believe this will provide you want you need. It's a class called PostsOrderedByMetaQuery that extends WP_Query and accepts new arguments 'orderby_meta_key' and 'orderby_order':

class PostsOrderedByMetaQuery extends WP_Query {
  var $posts_ordered_by_meta = true;
  var $orderby_order = 'ASC';
  var $orderby_meta_key;
  function __construct($args=array()) {
    add_filter('posts_join',array(&$this,'posts_join'),10,2);
    add_filter('posts_orderby',array(&$this,'posts_orderby'),10,2);
    $this->posts_ordered_by_meta = true;
    $this->orderby_meta_key = $args['orderby_meta_key'];
    unset($args['orderby_meta_key']);
    if (!empty($args['orderby_order'])) {
      $this->orderby_order = $args['orderby_order'];
      unset($args['orderby_order']);
    }
    parent::query($args);
  }
  function posts_join($join,$query) {
    if (isset($query->posts_ordered_by_meta)) {
      global $wpdb;
      $join .=<<<SQL
INNER JOIN {$wpdb->postmeta} postmeta_price ON postmeta_price.post_id={$wpdb->posts}.ID
       AND postmeta_price.meta_key='{$this->orderby_meta_key}'
SQL;
    }
    return $join;
  }
  function posts_orderby($orderby,$query) {
    if (isset($query->posts_ordered_by_meta)) {
      global $wpdb;
      $orderby = "postmeta_price.meta_value {$this->orderby_order}";
    }
    return $orderby;
  }
}

You would call it like this:

$thirtydays = date('Y/m/d', strtotime('+30 days'));
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$query = new PostsOrderedByMetaQuery(array(
  'post_type' => array('post', 'real-estate'),
  'meta_key' => 'Time Available',
  'meta_compare' => '<=',
  'meta_value' => $thirtydays,
  'paged' => $paged,
  'orderby_meta_key' => 'Price',
  'orderby_order'    => 'DESC',
));
foreach($query->posts as $post) {
  echo " {$post->post_title}\n";
}

You can copy the PostsOrderedByMetaQuery class to your theme's functions.php file, or you can use it within a .php file of a plugin you may be writing.

If you want to test it quickly I've posted a self-contained version of the code to Gist which you can download and copy to your web server's root as test.php, modify for your use case, and then request from your browser using a URL like http://example.com/test.php.

Hope this helps.

-Mike

P.S. This answer is very similar to an answer I just gave over at WordPress Answers, which is the sister site of StackOverflow where lots of WordPress enthusiasts like me answer questions daily. You might want to see that answer too because it has a tad more explanation and because you might want to see WordPress Answers. Hope you'll consider posting your WordPress questions over there too in the future?



Answered By - MikeSchinkel
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do you display the contents of a database over many pages

 July 09, 2022     posts, ruby-on-rails     No comments   

Issue

I'm making a rails app that handles many, many posts. What i want to do it display the posts over x number of pages with 5 posts per page. I've looked around a lot and have not been able to find a solution. I'm new to ruby on rails and don't yet know enough to be able to separate the posts by page.


Solution

There are two gems that could help you: will_paginate or kaminari.



Answered By - plang
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to find one categories all posts' all category? And again specific category form those categories.?

 July 09, 2022     categories, php, posts, wordpress     No comments   

Issue

I have one category named City and Second category Named Decease Inside City different cities will be there and inside Decease different decease will be there.

I will have posts having one city and more than one decease.

So what I want is when I click on One City I want to show all the decease belonging to this category.

So In detail with one city suppose 4 posts are there and all posts belongs to some decease So I need to find that how many posts are there having one category as this city. And then I need to find All the categories of all these posts and from that I need to find which categories parent category name is Decease. And then I need to show those categories.

How I should code this in wordpress in a nice manner? If some one has already spend some time on doing like this code then Kindly guide what will be good way to do this.


Solution

$deseace_cat_id = getCareTypeCategoryId(); 
    $careType=array();
    if(have_posts())
    {
        $cats = array();
        $cat_ids=array();                           

         while (have_posts()) : the_post();
            $post_categories = wp_get_post_categories( $post->ID );
            foreach($post_categories as $c){                
                $cat = get_category( $c );
                if(!in_array($c, $cat_ids) && $cat->category_parent==$deseace_cat_id)
                {
                    $cat_ids[]=$c;          
                    $cats[] = array( 'name' => $cat->name, 'slug' => $cat->slug );                          
                }               
            }                                                           
            echo "<br>";
         endwhile;
         for($i=0;$i<count($cats);$i++)
         {
            ?>
            <a class="careTypeUrl" href="#" careSlug='<?php echo $cats[$i]['slug'];?>'><?php echo $cats[$i]['name'];?></a><br>
            <?php   
         }       
    }


Answered By - Dena
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why does page navigation not work here?

 July 09, 2022     categories, navigation, posts, wordpress     No comments   

Issue

    <?php
/**
* Template Name: Blog page
* Description: The blog page
*/
get_header(); ?>


<?php
$args = array( 'numberposts' => 3 );
$lastposts = get_posts( $args );
foreach($lastposts as $post) : setup_postdata($post); ?>
<div class="postblog">
    <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>

    <span class="postdetails">
    <?php the_time ('j F, Y'); ?>&nbsp;&nbsp;&nbsp;<span class="bullet">&bull;</span>&nbsp;&nbsp;&nbsp;Posted in:&nbsp;<?php the_category(', '); ?>
    </span>

    <?php the_content(); ?>

    <div class="fb">
    <?php if(function_exists("wpfblike")) echo wpfblike(); ?>
    </div>

    </div>

<?php endforeach; ?>


</div>
<?php get_footer(); ?>

Whenever I try to use WP_Paginate or Pagenavi with this, it refuses to show up, no matter what I try to use I cannot get page navigation. I have 5 posts and only three are showing (as per the code above) so how do I get to the other two?


Solution

Have you tried using next_posts_links and previous_posts_links?

<?php
$page = (get_query_var('paged')) ? get_query_var('paged') : 1; 
query_posts("showposts=3&paged=$page");
?>
<?php while (have_posts()) : the_post(); ?>
// display your post
<?php endwhile; ?>
// display navigation
<div class="navigation">
<div class="alignleft"><?php next_posts_link('&larr; Older Entries') ?></div>
<div class="alignright"><?php previous_posts_link('Newer Entries &rarr;') ?></div>
</div>


Answered By - Cyclonecode
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What other alternatives are there to Wordpress query_posts()?

 July 09, 2022     posts, wordpress     No comments   

Issue

The Wordpress codex says that:

query_posts() is only one way amongst many to query the database and generate a list of posts. Before deciding to use query_posts(), be sure to understand the drawbacks.

but it does not list what those alternatives to query_posts() are. Should I be using something else?


Solution

Take a look at this page. It lists a few alternatives to query_posts. WP_Query() may be what you're looking for.



Answered By - rocky
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to display blog posts with featured images on magento homepage?

 July 09, 2022     magento, posts, wordpress     No comments   

Issue

I have integrate the fishbig in my magento site.(fishbig used for integrate wordpress with magento). now the posts are displayed fine.

now i need to get postname, postdate, post featured image and post link for displaying in the home page as slide. how can i get that?


Solution

When we integrate fishbig with magento we can have one folder "wordpress" in the template folder.(path:- app\design\frontend\base\default\template).

in that we can create our custom folder like "home". in that we need to create one .phtml file called "slider.phtml".

the followings code returns the post name, post featured image etc...

<?php $posts = $this->getPosts() 

if (count($posts) > 0): ?>



<?php 
      foreach($posts as $post): ?>
      <?php 

     $image_url = $post->getFeaturedImage()->getFullSizeImage(); // Featured image
          $post_link = $post->getPermalink(); // Post link
          $post_date = $post->getPostDate(); // Post date
          $post_day = date('l', strtotime($post_date)); // Day of Post
          $post_title = $post->getPostTitle(); // Post Title

<?php endforeach; ?> 

<?php endif; ?>

Then call this template in home page slide section like,

<div class="home_banner">
  <?php
$magento_block = Mage::getSingleton('core/layout');
$blog = $magento_block->createBlock('wordpress/sidebar_widget_posts')->setTemplate('wordpress/home/homeslide.phtml');
$blog->setPostCount(6);
echo $blog->toHtml();
?> 
</div>


Answered By - Ravichandran Jothi
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I limit this to exclude duplicates? I'm seeing my message twice because I'm friends with more than one person

 July 09, 2022     mysql, php, posts     No comments   

Issue

Question: Can someone help me fix the following piece of code to meet the following info:

When using this query, it sees that my username is in the database multiple times on diff columns, and so it is duplicating my posts when finding them in the query. I WANT it to show posts at diff timestamps by the same person, but not display from the same person if timestamp is the same.

Might be a better way to code the query, if so, I wouldn't mind seeing those options. Would doing a UNION query be the best way to do this?

$query = "SELECT p.* ".
"FROM posts p ".
"INNER JOIN friendships f ON p.username = f.user2 OR p.username = f.user1 ".
"WHERE f.user1 = '$sessionusername' OR f.user2 = '$sessionusername' ORDER BY id DESC"; 

SOLUTION:

I am answering my own question here, just to give someone a workable solution from what I did to fix the issue. I tried grouping by ID and then turning around and ordering by ID; however, it threw an error -- so instead I am ordering by timestamp, and grouping by ID. Below is my code. Worked for me -- and hopefully this ends up helping someone else!

$query = "SELECT p.*, MAX(timestamp) AS latest ".
"FROM posts p ".
"INNER JOIN friendships f ON p.username = f.user2 OR p.username = f.user1 ".
"WHERE f.user1 = '$sessionusername' OR f.user2 = '$sessionusername' GROUP BY id ORDER BY  latest DESC";   

Solution

Use GROUP BY to tell mysql what entity/fields you want to be unique:

SELECT p.*
FROM posts p
INNER JOIN friendships f ON (p.username = f.user2 OR p.username = f.user1)
WHERE f.user1 = '$sessionusername' OR f.user2 = '$sessionusername' 
GROUP BY posts.id
ORDER BY id DESC


Answered By - Puggan Se
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, July 8, 2022

[FIXED] How to get pagination working with “Pending” Posts

 July 08, 2022     archive, categories, pagination, posts, wordpress     No comments   

Issue

I'm working on a site that allows users to browse through pending posts/content on the front-end.

However, I can't seem to get pagination working with those posts. I've got a custom query that brings up the first page of pending posts on a category page, archive, etc.

But the Page 2, 3, etc. doesn't work.

Any thoughts?

Thanks!

Here's the example code I'm working with:

$args = array(
    'cat'      => $cat_ID,
    'paged' => get_query_var('paged'),
    'showposts' => 50,
    'posts_per_page' => 50,
    'post_status' => 'pending',

);

query_posts($args);

if( have_posts() ) : while (have_posts()) : the_post();

//Post code inserted here

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

Solution

WordPress pagination will 404 if there are not enough results in the main query to run to that page.

I'm sure there is a better way, but the only way I can think of round it is to use your custom loop in an archive/search page that has more posts than you have drafts.

For example, add your custom loop to the search.php template and reach it by passing a search query that will generate lots of results (e.g. 'a'). Using search.php will include pages, posts and custom post types in the results so will yield more results.

Use paginate_links for the pagination, which will continue to pass the queryvar on each page and after that you should be good.

On a slightly separate note, I would suggest using WP_Query instead of query_posts. See here for why.



Answered By - Mark
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get pagination working with “Pending” Posts

 July 08, 2022     archive, categories, pagination, posts, wordpress     No comments   

Issue

I'm working on a site that allows users to browse through pending posts/content on the front-end.

However, I can't seem to get pagination working with those posts. I've got a custom query that brings up the first page of pending posts on a category page, archive, etc.

But the Page 2, 3, etc. doesn't work.

Any thoughts?

Thanks!

Here's the example code I'm working with:

$args = array(
    'cat'      => $cat_ID,
    'paged' => get_query_var('paged'),
    'showposts' => 50,
    'posts_per_page' => 50,
    'post_status' => 'pending',

);

query_posts($args);

if( have_posts() ) : while (have_posts()) : the_post();

//Post code inserted here

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

Solution

WordPress pagination will 404 if there are not enough results in the main query to run to that page.

I'm sure there is a better way, but the only way I can think of round it is to use your custom loop in an archive/search page that has more posts than you have drafts.

For example, add your custom loop to the search.php template and reach it by passing a search query that will generate lots of results (e.g. 'a'). Using search.php will include pages, posts and custom post types in the results so will yield more results.

Use paginate_links for the pagination, which will continue to pass the queryvar on each page and after that you should be good.

On a slightly separate note, I would suggest using WP_Query instead of query_posts. See here for why.



Answered By - Mark
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get the number of posts that located in 2 specific categories at the same time in WordPress

 July 08, 2022     categories, count, posts, wordpress     No comments   

Issue

I have tried to use this code:

$terms = get_terms('translates_category', 'include=220,238');

But it returns an array with two separate objects:

Array
(
[0] => stdClass Object
    (
        [term_id] => 220
        [name] => Degrees of comparison
        [slug] => degrees-of-comparison
        [term_group] => 0
        [term_taxonomy_id] => 272
        [taxonomy] => translates_category
        [description] => 
        [parent] => 217
        [count] => 2
    )

[1] => stdClass Object
    (
        [term_id] => 238
        [name] => Lesson
        [slug] => lesson
        [term_group] => 0
        [term_taxonomy_id] => 290
        [taxonomy] => translates_category
        [description] => 
        [parent] => 0
        [count] => 1
    )
)

As I can assume, it's returns number of all posts (count) in those 2 categories separately. But I need the total number of only the posts that located in both categories at the same time.

There may be 100 posts in first category and 10 in second but only 1 of them may be associated with both of categories at a time. And I need to count such posts.

How can I do that?


Solution

This should solve your problem:

function my_post_count($tax, $cat1, $cat2) {
    $args = array(
        'tax_query' => array(
            'relation' => 'AND',
            array(
                'taxonomy' => $tax,
                'field' => 'term_taxonomy_id',
                'terms' => array( $cat1 ),
                'operator' => 'IN'
            ),
            array(
                'taxonomy' => $tax,
                'field' => 'term_taxonomy_id',
                'terms' => array( $cat2 ),
                'operator' => 'IN'
            ),
        )
    );
    $query = new WP_Query( $args );
    return $query->post_count;
}
echo my_post_count('translates_category', 220, 238);


Answered By - Octav
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get Page's Posts by Others

 July 08, 2022     facebook, facebook-graph-api, fan-page, posts     No comments   

Issue

I need to pull the 'Posts by Others' from my Facebook Page and display them on my site. Spent the afternoon fiddling around with the API and was able to see posts made by the page, but not others. Any ideas?


Solution

Steve, I just found another solution, you can use the Graph API using FQL.

Just make a call to the following:

https://graph.facebook.com/fql?q=SELECT post_id, created_time , app_data, type, actor_id, target_id, message FROM stream WHERE  source_id = YOUR_PAGE_ID AND actor_id != YOUR_PAGE_ID&access_token=YOUR_ACCESS_TOKEN

If you need more variables, you just need to put them after SELECT, and you can check them out here: https://developers.facebook.com/docs/reference/fql/stream

On iOS, you don't need to put the access token in the query. To check how to do it with the latest iOS SDK, see my answer here: https://stackoverflow.com/a/14357179/675486



Answered By - Natan R.
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I add categories-authors-members area for commenting on my website?

 July 08, 2022     css, html, php, posts     No comments   

Issue

I have designed my own template on dreamweaver using HTML and CSS. I don't know much about php which i assume its what i need. but i still want to know how to make something has similar idea like http://howtogeek.com I mean the posts and commenting and the author's thing.


Solution

Why not try something like http://disqus.com/

It requires no programming on your end at all and allows users to share there thoughts on your content.



Answered By - dcbarans
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to make a Wordpress post only visible for the author and through a direct link?

 July 08, 2022     author, posts, wordpress     No comments   

Issue

I want to make a Wordpress site where users can register them self. They only need the ability to update there profile and write a post. This post should be only visible to the author or through a direct link.

Does anybody know how I can make the post of the author invisible on the website but when the author logs in the post is visible and when someone uses the direct link to the post it's also visible. Is there some kind of plugin what can do this or some kind of code which I can edit so this will work.

Also there are multiple authors with each there own posts.

Thank you


Solution

  1. Go to your posts

  2. Open the desired one.

  3. Set post visibility to Private

Also you can vizit this page: http://wordpress.org/support/topic/let-author-only-see-their-posts



Answered By - 5wpthemes
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] When a Post comment is made, no more can be created, only shown

 July 08, 2022     comments, posts, ruby, ruby-on-rails, ruby-on-rails-3.2     No comments   

Issue

I am trying to get a post and comment system working, for this however i want only one comment to be made per post. Only as i am trying to create a system as where content will be displayed followed by a comment 7 times in one post... Example...

program model 1 body content 1

Commentmodel1

program model 1 body content 2

Commentmodel2

program model 1 body content 3

Commentmodel3

.etc.etc.

For Me this is the simplest way of being able todo this by creating 7 different comment models, i know there is probably an easier way but as im new this seems the simplest. However i am struggling getting the one comment model to only allow just one comment to be made.

In this application coach is the user.

Here are the files involved, For the Models, program is the basic Post model, and comments is comments.

programs/Show.html.erb

<p id="notice"><%= notice %></p>

<p>
  <b>Title:</b><br />
  <%= @program.title %>
</p>

<p>
  <b>Body:</b><br />
  <%= @program.cweekcomments %>
</p>


<%= link_to 'Edit', edit_program_path(@program) %> |
<%= link_to 'Back', programs_path %>

<br /><br /><br />
<i>Comments</i>
<% @program.comments.each do |comment| %> 
  <p>
    <b>Comment:</b>

    <% if comment %>
        <%= comment.body %>
        <br />
        <%= link_to 'Edit', edit_program_comment_path(@program, comment) %> | <%= link_to 'Destroy', [@program, comment] , method: :delete, data: { confirm: 'Are you sure?' } %>
    <% else %>
        <%= form_for([@program, @program.comments.build]) do |f| %>
        <div class="field">
        <%= f.label :body %><br />
        <%= f.text_area :body %>
        </div>
        <div class="actions">
        <%= f.submit %>
        </div>
        <% end %>
    <% end %>
    </p>  
<% end %>

Programs_controller.rb

class ProgramsController < ApplicationController

  before_filter :authenticate_coach!, :except => [:show]


  # GET /programs
  # GET /programs.json

  def index
    @programs = Program.find_all_by_coach_id(current_coach[:id])

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @programs }
    end
  end

  # GET /programs/1
  # GET /programs/1.json
  def show
    @program = Program.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @program }
    end
  end

  # GET /programs/new
  # GET /programs/new.json
  def new
    @program = Program.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @program }
    end
  end

  # GET /programs/1/edit
  def edit
    @program = Program.find(params[:id])
  end

  # POST /programs
  # POST /programs.json
  def create
    @program = Program.new(params[:program])


    respond_to do |format|
      if @program.save
        format.html { redirect_to @program, notice: 'Program was successfully created.' }
        format.json { render json: @program, status: :created, location: @program }
      else
        format.html { render action: "new" }
        format.json { render json: @program.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /programs/1
  # PUT /programs/1.json
  def update
    @program = Program.find(params[:id])

    respond_to do |format|
      if @program.update_attributes(params[:program])
        format.html { redirect_to @program, notice: 'Program was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @program.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /programs/1
  # DELETE /programs/1.json
  def destroy
    @program = Program.find(params[:id])
    @program.destroy

    respond_to do |format|
      format.html { redirect_to programs_url }
      format.json { head :no_content }
    end
  end
end

Comments_controller.rb

class CommentsController < ApplicationController

  def new
    @comment = @program.comments.build
  end 

  def create
    @program = Program.find(params[:program_id])
    @comment = @program.comments.create(params[:comment])
    redirect_to program_path(@program)
  end

  def destroy
    @program = Program.find(params[:program_id])
    @comment = @program.comments.find(params[:id])
    @comment.destroy
    redirect_to program_path(@program)
  end

  def edit
    @program = Program.find(params[:program_id])
    @comment = @program.comments.find(params[:id])
  end

   def update
    @program = Program.find(params[:program_id])
    @comment = @program.comments.find(params[:id])

    respond_to do |format|
      #if @program.comments.update_attributes(params[:comment])
      if @comment.update_attributes(params[:comment])
        format.html { redirect_to program_path(@program), notice: 'Comment was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
      end
    end

end

In advance, thanks for your help, much appreciated!


Solution

Change your program comment relation to has_one.(has_one :comment in your program.rb)

def create
   @program = Program.find(params[:program_id])
   if @program.comment
     flash[:error] = "Cannot comment more than once"
   else
     @comment = @program.comments.create(params[:comment])
     flash[:notice] = "Comment created"
   end
   redirect_to program_path(@program)
end


Answered By - usha
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] When a Post comment is made, no more can be created, only shown

 July 08, 2022     comments, posts, ruby, ruby-on-rails, ruby-on-rails-3.2     No comments   

Issue

I am trying to get a post and comment system working, for this however i want only one comment to be made per post. Only as i am trying to create a system as where content will be displayed followed by a comment 7 times in one post... Example...

program model 1 body content 1

Commentmodel1

program model 1 body content 2

Commentmodel2

program model 1 body content 3

Commentmodel3

.etc.etc.

For Me this is the simplest way of being able todo this by creating 7 different comment models, i know there is probably an easier way but as im new this seems the simplest. However i am struggling getting the one comment model to only allow just one comment to be made.

In this application coach is the user.

Here are the files involved, For the Models, program is the basic Post model, and comments is comments.

programs/Show.html.erb

<p id="notice"><%= notice %></p>

<p>
  <b>Title:</b><br />
  <%= @program.title %>
</p>

<p>
  <b>Body:</b><br />
  <%= @program.cweekcomments %>
</p>


<%= link_to 'Edit', edit_program_path(@program) %> |
<%= link_to 'Back', programs_path %>

<br /><br /><br />
<i>Comments</i>
<% @program.comments.each do |comment| %> 
  <p>
    <b>Comment:</b>

    <% if comment %>
        <%= comment.body %>
        <br />
        <%= link_to 'Edit', edit_program_comment_path(@program, comment) %> | <%= link_to 'Destroy', [@program, comment] , method: :delete, data: { confirm: 'Are you sure?' } %>
    <% else %>
        <%= form_for([@program, @program.comments.build]) do |f| %>
        <div class="field">
        <%= f.label :body %><br />
        <%= f.text_area :body %>
        </div>
        <div class="actions">
        <%= f.submit %>
        </div>
        <% end %>
    <% end %>
    </p>  
<% end %>

Programs_controller.rb

class ProgramsController < ApplicationController

  before_filter :authenticate_coach!, :except => [:show]


  # GET /programs
  # GET /programs.json

  def index
    @programs = Program.find_all_by_coach_id(current_coach[:id])

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @programs }
    end
  end

  # GET /programs/1
  # GET /programs/1.json
  def show
    @program = Program.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @program }
    end
  end

  # GET /programs/new
  # GET /programs/new.json
  def new
    @program = Program.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @program }
    end
  end

  # GET /programs/1/edit
  def edit
    @program = Program.find(params[:id])
  end

  # POST /programs
  # POST /programs.json
  def create
    @program = Program.new(params[:program])


    respond_to do |format|
      if @program.save
        format.html { redirect_to @program, notice: 'Program was successfully created.' }
        format.json { render json: @program, status: :created, location: @program }
      else
        format.html { render action: "new" }
        format.json { render json: @program.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /programs/1
  # PUT /programs/1.json
  def update
    @program = Program.find(params[:id])

    respond_to do |format|
      if @program.update_attributes(params[:program])
        format.html { redirect_to @program, notice: 'Program was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @program.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /programs/1
  # DELETE /programs/1.json
  def destroy
    @program = Program.find(params[:id])
    @program.destroy

    respond_to do |format|
      format.html { redirect_to programs_url }
      format.json { head :no_content }
    end
  end
end

Comments_controller.rb

class CommentsController < ApplicationController

  def new
    @comment = @program.comments.build
  end 

  def create
    @program = Program.find(params[:program_id])
    @comment = @program.comments.create(params[:comment])
    redirect_to program_path(@program)
  end

  def destroy
    @program = Program.find(params[:program_id])
    @comment = @program.comments.find(params[:id])
    @comment.destroy
    redirect_to program_path(@program)
  end

  def edit
    @program = Program.find(params[:program_id])
    @comment = @program.comments.find(params[:id])
  end

   def update
    @program = Program.find(params[:program_id])
    @comment = @program.comments.find(params[:id])

    respond_to do |format|
      #if @program.comments.update_attributes(params[:comment])
      if @comment.update_attributes(params[:comment])
        format.html { redirect_to program_path(@program), notice: 'Comment was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
      end
    end

end

In advance, thanks for your help, much appreciated!


Solution

Change your program comment relation to has_one.(has_one :comment in your program.rb)

def create
   @program = Program.find(params[:program_id])
   if @program.comment
     flash[:error] = "Cannot comment more than once"
   else
     @comment = @program.comments.create(params[:comment])
     flash[:notice] = "Comment created"
   end
   redirect_to program_path(@program)
end


Answered By - usha
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get most recent commented post above new submitted post in Wordpress?

 July 08, 2022     comments, mysql, posts, wordpress     No comments   

Issue

I have this function:

$ids = $wpdb->get_col("SELECT DISTINCT comment_post_ID
FROM $wpdb->comments
ORDER BY comment_date DESC
LIMIT 0 , 30");

foreach ($ids as $id) {
  $post = &get_post( $id );
  setup_postdata($post); ?>
  <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
  <?php
}
?>

Which shows the latest commented posts in a list, which is fine. What I want to do is give a priority to this one and combine it with a "get newest post list". So let's say I commented today on a post called Hello World and someone else submitted a post yesterday... Than I want to get the recent commented post above this new post. The problem is that in my code snippet, there is nothing that says to get the newest posts. How can I combine them? So how to combine most recent commented posts and newest posts with each other? Is this even possible?


Solution

Give it a try works perfect for me what it is doing query get the all the posts with a left jon with comments table so when a post has comment them=n it also has the comment_date if no comments posted on the post then in result set it will be null so i have merged the comment_date with post_date so which post has the greater date (for comment_date or post_date) it will first and so on

SELECT p.*,
(CASE WHEN c.comment_date IS NULL THEN p.`post_date` ELSE c.comment_date END) order_column
 FROM `wp_posts` p
LEFT  JOIN `wp_comments` c  ON (p.ID = c.`comment_post_ID` ) WHERE p.post_type='post' AND p.post_status='publish'
GROUP BY p.ID
 ORDER BY order_column   DESC

For displaying the posts you have to first get the results by defining the WP's global variable for the database interaction i.e $wpdb

<?php
global $wpdb;
$results = $wpdb->get_results("    SELECT p.*,
    (CASE WHEN c.comment_date IS NULL THEN p.`post_date` ELSE c.comment_date END) order_column
     FROM `wp_posts` p
    LEFT  JOIN `wp_comments` c  ON (p.ID = c.`comment_post_ID` ) WHERE p.post_type='post' AND p.post_status='publish'
    GROUP BY p.ID
     ORDER BY order_column   DESC"); 
?>

HTML

<?php foreach($results as $result){

<h1><?php echo $result->post_title;?></h1>
<div> <?php echo $result->post_content;?> </div>
// and so on the fields of wp_posts
<?php } // loop end ?>

Hope that is what you were looking for



Answered By - M Khalid Junaid
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to tweet message on logeed in user profile

 July 08, 2022     php, posts, tweets     No comments   

Issue

I Have integrated tweeter connect with my website.I have used oauth code to post on tweeter. I have mentioned part of the code what I have used below.

$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $oAuthToken, $oAuthSecret);
// Your Message
$message = "hi I am fine";
// Send tweet     
$tweet->post('statuses/update', array('status' => "$message"));

But I can not post on the user page who is logged in ,It only shows on application's user page, should I add anything with this code?if so please let me know what should I do with code.


Solution

This code is alright. It will work.

But the main thing is to figure out what is the error and why it's not working. Simply replace

$tweet->post('statuses/update', array('status' => "$message"));

using:

$mytweet=$tweet->post('statuses/update', array('status' => "$message"));
var_dump($mytweet); 
// print the output coming from the post request, that you done using twitterOauth

I already have used the same code, first time it's not working as my Application was Read Only Type and now works properly! So, make sure your Application settings is Read and Write type at least. Here the solution in details: https://stackoverflow.com/questions/18035906/tweeting-with-php-not-working/18036339#18036339



Answered By - Jaber Ibne Mahboob
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to get the index number of my Tumblr posts when in Infinite Scroll

 July 08, 2022     callback, indexing, infinite-scroll, posts, tumblr     No comments   

Issue

$('#content').infinitescroll({
        binder: $(window),
        debug: true,
        itemSelector : ".post",
        navSelector  : "#pagination",
        nextSelector : "#next-page"

        },function(arrayOfNewElems){  

    });

basically, I want to display the number my Tumblr posts. I have made different attempts but each time the index numbering starts again from 0 after the new content is loaded. How can I make the number a continuation from the previously loaded posts.

what kind of function should i be invoking in

function(arrayOfNewElems){

});

this is the plugin im using

https://github.com/paulirish/infinite-scroll


Solution

Just do:

var totalPosts = null;

$.ajax({
    url: "http://[BLOG NAME HERE].tumblr.com/api/read/json",
    dataType: 'jsonp',
    success: function(results){
        totalPosts = results['posts-total'];
        alert(totalPosts);
    }
});

Needs jQuery but can be run before the document is loaded.



Answered By - hhff
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to remove paginated posts' navigation of Genesis 2.0?

 July 08, 2022     pagination, posts, wordpress     No comments   

Issue

I am using Genesis 2.0 (bone stock, no child theme) for my website. And for some of the posts i've divided them into multi parts using the tag of WordPress. Now to navigate these pages, i've made my own functions. However, Genesis 2.0 has its own navigation but I want to remove that. But I cant find the function which executes this navigation, can anyone please tell me how do I remove that?

Thanks.


Solution

The snippet you need to simply remove page navigation (pagination) with Genesis 2.0 is:

remove_action( 'genesis_after_endwhile', 'genesis_posts_nav' );

An example conditional using this is:

add_action ( 'genesis_after_entry', 'sk_remove_pagination' );
function sk_remove_pagination() {
    if ( is_home() ) {

        remove_action( 'genesis_after_endwhile', 'genesis_posts_nav' );

    }
}

Sources:
https://gist.github.com/braddalton/5030437
http://sridharkatakam.com/remove-pagination-posts-page-genesis/
Google 'genesis remove pagination'



Answered By - michaelcarwile
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I set the limit number of the posts of a specify category into a page of that category?

 July 08, 2022     categories, limit, posts, wordpress     No comments   

Issue

I would to know how can I set the limit number of the posts visible into a page of a specify category.


Solution

Put this in your functions.php

function main_query_mods( $query ) {
    if(!$query->is_main_query()) {
        return;
    }
    // show 15 posts per page if category has id 7
    // check http://codex.wordpress.org/Conditional_Tags#A_Category_Page
    if ( is_category('7')) {
        $query->set('posts_per_page',15);
    }
}
add_action( 'pre_get_posts', 'main_query_mods' );


Answered By - offroff
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing