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! :)

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);

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.