Get the_permanlink () in html and then format in functions.php - php

Ok I have an issue here which I'm finding really hard to fix. Although I'm guessing it's probably not that complicated.
I'm using wordpress and in my functions.php I have the following:
<?php
class EXAMPLE {
$this->url=rawurlencode($url);
}
function DO-SOMETHING() {
DO-SOMETHING . $this->url);
}
?>
Then I call the function in my html:
<div>
<?php $obj=new EXAMPLE("www.example.com"); echo $obj->DO-SOMETHING();?>
</div>
I need to replace ("www.example.com") with (the_permalink()).
but it doesn't work. Not sure why. I have tried a number of different ways using trial and error, but can't find a solution
Thanks

If it's just about encoding an URL, the following would do:
echo rawurlencode( get_the_permalink() );
You could also wrap that in a function:
echo myrawurlencode( get_the_permalink() );
function myrawurlencode($url){
rawurlencode( $url );
}
note: get_the_permalink() returns the URL, while the_permalink() echoes it directly by default.
If you're going to use a class, you might want to take a look at http://php.net/manual/en/language.oop5.decon.php
and http://www.php.net/manual/en/language.oop5.basic.php first.

Well like mentioned the_peramlink() displays the url using the echo statement, but you could use get_permalink($id) which returns the url. WordPress makes sure that the url returned by both functions are escaped and can be used without using the rawurlencode() function from PHP.
Unless you need to append something to the permalink you don't need this function and should be just fine with the get_permalink($id) function. You could always check the get_permalink documentation in the Wordpress codex for more information.

Related

How to get some portion in the url?

I am working in php. I want to get some portion of the url using php,
For Example, my url is "http://localhost:82/index.php?route=product/product&path=117&product_id=2153". i want route=product/product only.
Since the variable might not exist, you could (and should) ensure your code does not trigger notices with:
<?php
if (isset($_GET['route'])) {
$route = $_GET['route'];
}else{
// Fallback behaviour goes here
}
Alternatively, if you want to skip manual index checks and maybe add further validations you can use the filter extension:
<?php
echo filter_input(INPUT_GET, 'route');
You can read it using $_REQUEST as below:
<?php
echo $_REQUEST['route'];
?>
It sounds like simply $_GET['route'] will work, although that will only give you product/product. You can just fill in the rest yourself if you know the name of the parameter.
Those URL parameters are called get variables. You can retrieve them using the super global $_GET like so
$route = $_GET['route'];
try this,
<?php
$ans=$_GET['route'];
echo $ans;
?>
Using the following code,
<?php
if(isset($_REQUEST["route"]))
echo $_REQUEST['route'];
?>

Using PHP variables in Wordpress Shortcodes

I'm using the Cart66 Wordpress plugin, and I'm trying to include a variable in a shortcode, you can see the code below:
$price = do_shortcode('[add_to_cart item="test-item" showprice="only" text=""]').' test';
echo do_shortcode('[add_to_cart item="test-item" showprice="no" quantity="1" text="'.$price.'" ]');
I've done some googling, and apparently this is the right way to include variables in Wordpress shortcodes, but this doesn't seem to work for me, Cart66 just falls back and uses the default "Add to Cart" text instead of the text defined in the shortcode above.
Can anyone see where I'm going wrong here?
As you have googled to add text in the shortcode is correct but not fully correct.
You have used "do_shortcode()" function which is used to replace the shortcode functionality and display its functionality in frontend. But, if you want to add a parameter in a shortcode and make it working you need to change the shortcode functionality a bit.
You have to find shortcode in your files containing the shortcode's functionality:
Find code something like below:
add_shortcode('add_to_cart','function_name');
function function_name($atts)
{
$atts //-- will be used to add parameters as you needed
}
You can use PHP's Output Buffering control
PS: do_shortcode() does not natively echo the output; whatever is bound on that action may echo by itself as well, which is when you either (A) edit the plugin, or (B) use OB.
I think there were some weird characters in the returend value that were causing issues, I used the Expression code below, and it seemed to solve my issue:
$value = substr(do_shortcode('[add_to_cart item="test-item" showprice="only" text=""]'), 0, 4).' Test';
$patterns = array();
$patterns[0] = '/"/';
$replacements = array();
$replacements[2] = ' ';
$value = preg_replace($patterns, $replacements, html_entity_decode($price, ENT_QUOTES));
echo do_shortcode('[add_to_cart item="test-item" showprice="no" quantity="1" text="'.$price.'" ]');
Needless to say this was a very ... complicated solution. I ended up using some good old SQL by utilising Wordpresses WPDB class. Turning about 7 lines of code into 2:
$priceValue = $wpdb->get_var("SELECT price FROM wp_cart66_products WHERE id = x");
echo do_shortcode('[add_to_cart item="test-item" showprice="no" quantity="1" text="£'.$priceValue.' Membership" ]');
This is a much better solution, I wouldn't recommend trying to use shortcodes for things they weren't intended to be used for.
The ‘add_shortcode’ function does not allow you to use external variables. It operates with a local scope, so any variables declared INSIDE will be recognized, but any variables OUTSIDE will not be recognized. If you want to use an external variable you will need to use global.
Using global on your external variable will pull it within scope and allow you to use it within the add_shortcode function! :)
$greeting = "hello world!"; //external variable
function run_greeting() {
global $greeting //pulls variable within scope
echo $greeting;
}
add_shortcode( 'greeting_shortcode', 'run_greeting' );

Is it bad practice to echo out functions in php?

Is it bad practice to echo out a bunch of HTML using a function in php and having it something like this:
function my_function() {
global $post;
$custom_fields = get_post_custom();
$some_field = $custom_fields ['some_field'][0];
?>
<div class="something <?php if ($some_field) { echo $special-clas;} ?>">
<div class="something-else">
/* bunch more of html code */
</div>
</div>
}
And then in the page where you want to use that to echo it?
<html>
<body>
.....
....
<?php echo my_function(); ?>
....
I'm unsure how "accepted" it is to echo out functions?
Consider two functions:
function does_return() {
return 'foo';
}
function does_echo() {
echo 'bar';
}
does_return(); // nothing displayed
echo does_return(); // 'foo' displayed
does_echo(); // 'bar' displayed
echo does_echo(); // 'bar' displayed
In both cases, output CAN be performed, but how it happens differs. Since does_return() does not itself have ANY code to perform output within its definition, output is up to the calling code, e.g. the echo you perform.
With does_echo(), it doesn't matter how you call the function (with or without echo), since the function does the output itself. you'll get bar regardless.
Now consider this:
function this_is_fun();
echo 'foo';
return 'bar';
}
this_is_fun(); // outputs 'foo'
echo this_is_fun(); // outputs 'foobar';
This is bad practice, because it makes your code hard to maintain.
With a function like that you are mixing the logic and presentation. So, when you see something in your output that you don't like you can not be sure where to go first to go and change it. Do you go to the page code or the function code?
Functions are supposed to return data, and then your application deals with it how you wish, whether that’s assigning it to a variable or echoing it out.
I don't see how it's bad practice. As long as you're reusing the function, then it seems like you're using it the right way.
The only thing you shouldn't be doing is using global; rather pass $post to the function. See this answer for why.
Since your function already has an output, you don't need the echo.
my_function( $post );
That's fine. I'd rather see that than the PHP mixed in completely to the HTML.
You can use <?= my_function() ?> instead if you want to write a little less code.
What #DaveRandom said in his comment. Aside from that, no, it's not necessarily bad practice. It can though make for code that's hard to debug. Consider a MVC approach instead where the logic is largely in the Controller and the View simply handles rendering the view based on that logic.

Wordpress Enqueue Js scripts

I am having trouble getting wp_enqueue functions to work. I've looked at all the documentation on it but am having trouble sifting through and finding out what is supposed to go where.
so far I understand that I am supposed to register and enqueue the files from the functions.php file of the theme I am creating. So that is exactly what I do. I create some PHP tags and drop it in the middle of them, at the bottom of the page. Save and Upload.
When I reload, it just returns a blank white screen, must be an error in the code or something.
Here is the function:
<?php
function add_scripts(){
wp_register_script('jquery', 'http://code.jquery.com/jquery-1.5.2.min.js');
wp_register_script('nivo', get_bloginfo('url').'/scripts/nivo.js');
wp_register_script('slimbox',get_bloginfo('url').'/scripts/slimbox2.js');
wp_register_script('picasa', get_bloginfo('url').'/scripts/jquery.EmbedPicasaGallery.js');
wp_register_script('pwi',get_bloginfo('url').'/jquery.pwi-min.js');
wp_register_script('swf', get_bloginfo('url').'/jquery.swfobject.1-1-1.min.js');
wp_register_script('simpletube',get_bloginfo('url').'/scripts/jquery.simpletube.js');
wp_register_script('jqvalidate', get_bloginfo('url').'/jquery.jqvalidate.js');
wp_enqueue_script('jquery');
wp_enqueue_script('nivo');
wp_enqueue_script('slimbox');
wp_enqueue_script('picasa');
wp_enqueue_script('pwi')
wp_enqueue_script('swf');
wp_enqueue_script('simpletube')
wp_enqueue_script('jqvalidate');
}
add_action('init','add_scripts');
?>
So is there some sort of problem with my syntax? I'm not that strong with PHP.
Any help is greatly appreciated. Thanks!
It's kind of hard to debug it without seeing the whole file but the fact you get a 'blank page' suggests there's definitely something larger than a syntax problem somewhere.
Do you definitely have correctly nested php tags? i.e.
<?php
some code
<?php
some more code
?>
some more code
?>
will give you problems.
Also, it's now common practice to leave the last ?> from the end of the file (it means you wont have any issues with having whitespace after the closing tags and they're not necessary)
On top of that, you've used wp_register_script('jquery'...) - WordPress already has jquery registered. If you wish to re-register it, you need to wp_deregister_script('jquery') first. I'd also only do that outside of the admin, so:
if(!is_admin()){wp_deregister_script('jquery'); <your wp_register_script stuff> }
If these things don't help, copy and paste your entire functions.php file (use pastebin.com and give us a link)
As an aside, you're using get_bloginfo('url') several times - which means you're running lots of unnecessary calls to the database. Stick it into a variable and save yourself a little overhead:
$my_url = get_bloginfo('wpurl');
wp_register_script('thing', $my_url.'/script/location/file.js');
Oh! One more thing, I don't think url is an allowed argument for get_bloginfo() I think you want wpurl
Codex page on get_bloginfo() function
Good luck!
Missing ; for the following two lines:
wp_enqueue_script('pwi')
wp_enqueue_script('simpletube')
Instead of your code I would use:
<?php
function add_scripts(){
wp_enqueue_script('jquery', 'http://code.jquery.com/jquery-1.5.2.min.js');
wp_enqueue_script('nivo', get_bloginfo('url').'/scripts/nivo.js');
wp_enqueue_script('slimbox',get_bloginfo('url').'/scripts/slimbox2.js');
wp_enqueue_script('picasa', get_bloginfo('url').'/scripts/jquery.EmbedPicasaGallery.js');
wp_enqueue_script('pwi',get_bloginfo('url').'/jquery.pwi-min.js');
wp_enqueue_script('swf', get_bloginfo('url').'/jquery.swfobject.1-1-1.min.js');
wp_enqueue_script('simpletube',get_bloginfo('url').'/scripts/jquery.simpletube.js');
wp_enqueue_script('jqvalidate', get_bloginfo('url').'/jquery.jqvalidate.js');
}
add_action('wp_enqueue_scripts', 'add_scripts');
So please notice I have removed "wp_register_script" as using that is totally unnecessary if you are going to call wp_enqueue immediately after register.
wp_register_script
Is used so that you can afterwards call it ANYWHERE else in code without including the path.
Also big change is that I'm not calling the function from
init
But I'm calling it from
wp_enqueue_scripts
Also please consider adding additional parameters to your wp_enqueue_script such as
wp_enqueue_script( string $handle, string $src = '', array $deps = array(), string|bool|null $ver = false, bool $in_footer = false )

Best way to get post info into variables without displaying them in Wordpress

I am writing a Wordpress plugin and need to go through a number of posts, grab the data from them (for the most part title, permalink, and content), and apply processing to them without displaying them on the page.
What I've looked at:
I've looked at get_posts() for getting the posts, and then
getting title via the_title(),
content via the_content(),
and permalink via the_permalink()
Keep in mind that I need this data after all filters had already been applied, so that I get the exact data that would be displayed to the user. Each of the functions above seems to apply all necessary filters and do some postprocessing already, which is great.
The Problem:
The problem is all these functions, at least in WP 2.7.1 (latest released version right now) by default just echo everything and don't even return anything back. the_title() actually supports a flag that says do not print and return instead, like so
the_title(null, null, false)
The other 2, however, don't have such flags, and such inconsistency is quite shocking to me.
I've looked at what each of the_() functions does and tried to pull this code out so that I can call it without displaying the data (this is a hack in my book, as the behavior of the_() functions can change at any time). This worked for permalink but for some reason get_the_content() returns NULL. There has to be a better way anyway, I believe.
So, what is the best way to pull out these values without printing them?
Some sample code
global $post;
$posts = get_posts(array('numberposts' => $limit));
foreach($posts as $post){
$title = the_title(null, null, false); // the_title() actually supports a "do not print" flag
$permalink = apply_filters('the_permalink', get_permalink()); // thanks, WP, for being so consistent in your functions - the_permalink() just prints /s
$content = apply_filters('the_content', get_the_content()); // this doesn't even work - get_the_content() returns NULL for me
print "<a href='$permalink'>$title</a><br>";
print htmlentities($content, ENT_COMPAT, "UTF-8"). "<br>";
}
P.S. I've also looked at What is the best method for creating your own Wordpress loops? and while it deals with an already obvious way to cycle through posts, the solution there just prints this data.
UPDATE: I've opened a ticket with Wordpress about this. http://core.trac.wordpress.org/ticket/9868
Most functions the_stuff() in WP that echo something have their get_the_stuff() counterpart that returns something.
Eg get_the_title(), get_permalink()...
If you can't find the exact way to do it, you can always use output buffering.
<?php
ob_start();
echo "World";
$world = ob_get_clean();
echo "Hello $world";
?>
OK, I got it all sorted now. Here is the final outcome, for whoever is interested:
Each post's data can be accessed via iterating through the array returned by get_posts(), but this data will just be whatever is in the database, without passing through any intermediate filters
The preferred way is to access data using get_the_ functions and them wrapping them in an call to apply_filters() with the appropriate filter. This way, all intermediate filters will be applied.
apply_filters('the_permalink', get_permalink())
the reason why get_the_content() was returning an empty string is that apparently a special call to setup_postdata($post); needs to be done first. Then get_the_content() returns data properly
Thanks everyone for suggestions.
Is there any reason you can't do your processing at the time each individual post is posted, or when it's being displayed?
WP plugins generally work on a single post at a time, so there are plenty of hooks for doing things that way.

Categories