Jump to content

[SOLVED] Passing a Variable into an Argument


nz_mitch

Recommended Posts

Hi there,

 

I've been trying for the last couple of hours to build some code that will change the number of items in a sidebar if they're specified using a custom field.

 

Here's what I've got so far:

 

<?php
		global $post;
			$custom_length = get_post_meta($post->ID, 'custom-sidebar-length', true);
			if ($custom_length=="") {
				$myposts = get_posts('numberposts=3'); // Change number of posts and category as you want	
			}
			else {
				$myposts = get_posts('numberposts=$custom_length');
				echo $custom_length;
			}
		foreach($myposts as $post) :
		?>

 

The echo $custom_length is only showing up when the custom length is specified and it's showing the right numbers—so I've got that part working.

 

The issue is just in feeding it into the function get_posts. I'm guessing the way I've written the function [get_posts('numberposts=$custom_length');], doesn't allow the $custom_length value to be read properly.

 

Is there a better way I can write this?

 

Thanks in advance! :)

Link to comment
Share on other sites

Well, it's because you're using single quotes, so PHP will take the value $custom_length as a string, and not execute it like a variable. Either use double quotes ( " ) or you need to concatenate the value.

 

Or change the way your function takes arguments, to just have like:

function get_posts($number = 3) {
// function here
}

// calling the function:
get_posts($custom_length);

// using the default value of 3:
get_posts();

// or set your own:
get_posts(9);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.