I'm trying to get the same effect as the plugin Pages Link To where the title of the post is linked to an external link. The reason I don't want to use the plugin is the link is generated dynamically when the post is saved, but I'm unable to update the the permalink of the post with the external link.
Below is my code in functions.php:
function savepost( $post_id ) {
if( $_POST['post_type'] == 'books' ){
$genre = strip_tags(get_field('genre'));
$author = strip_tags(get_field('author'));
$extlink = "http://www.".$genre."/".$author.".com";
update_post_meta( $post_id, 'extlink', $extlink);
$url = strip_tags(get_field('extlink',$post));
update_post_meta( $post_id, 'post_link', $url);
}
}
add_action( 'save_post', 'savepost' );
i m trying another method in which i assigned a template to the post so that when the post loads it redirects to the link but it doesn't redirect
my code
<?php
ob_start();
?>
<?php
/**
* Template Name: post Redirection Template
*/
get_header();
$redirecturl = strip_tags(get_field('extlink',$post));
wp_redirect($redirect_url);
get_sidebar();
get_footer();
?>
<?php
ob_end_flush();
?>
What you should do, is insert the external link as a custom field in the post editor, then display the custom field value in place of the_permalink(). You could use a plugin such as Advanced Custom Fields to grab the URL from the custom field.
EDIT 1: More clarification using the Advanced Custom Fields plugin as an example. The field name for this example is url.
You should use this wherever you want the custom permalink to appear throughout your site, such as in your archive.php, category.php, etc. Replace the code that looks something like this:
<?php the_title(); ?>
with this:
<?php
$value = get_field( "url" );
if( $value ) { ?>
<?php the_title(); ?>
<?php } else { ?>
<?php the_title(); ?>
<?php } ?>
EDIT 2: Clarifying additional information.
You can add a function to the header.php of your theme that checks if the url is set, then redirects to the external link that way, if your user goes directly to the permalink, it will still redirect them. In fact, you could use this code without using the above code to display the external link.
<?php
$value = get_field( "url" );
if( $value ) {
header('Location: '.$value);
die();
} else {} ?>
Warning: make sure to use this code before any HTML (or text) has been passed to the browser, or it will not work correctly.
Related
i added following code to use custom template for my recipes single page
function override_single_template( $single_template ){
global $post;
if ($post->post_type == "recipes"){
$single_template = plugins_url('/recipe-single-page-template.php',__FILE__);
}
return $single_template;
}
add_filter( 'single_template', 'override_single_template',10);
and in my template i added following code
<?php
/*
Template Name: recipe-single-page-template
Template Post Type: recipes
*/
require_once("../../../wp-load.php");
?>
<?php get_header(); ?>
<?php echo $post->ID?>
<?php get_footer(); ?>
but i do not access the post and echo out post id will cuses the following error
Trying to get property of non-object
var dump $post outputs null
NULL
and following code will print out my custom template address
$current_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
echo $current_url;
top code result:
https://charter.test/wp-content/plugins/recipe-plugin/templates/single-recipes.php
now whate should i do?
Are you trying to redirect a custom post type called recipes to a custom template? You don't need to override, by default wordpress has a built in dynamic content display system.
In your case, upon displaying a recipe it will search first for single-recipe.php, if not found, fallback on single.php, if not found, fallback on 404.php and finally on index.php
You just have to create a file called single-recipe.php.
Your second problem is that there is no loop displayed in your file, you have to tell to wordpress that if a post exist, it should retrieve it and present it to you. For that we use the loop system.
Your single-recipe.php file should look like something like this:
<?php
/**
* Get theme header
*/
get_header();
/**
* Start loop
*/
if ( have_posts() ):
while ( have_posts() ):
the_post();
/**
* If we find a post, output the tilte
*/
echo the_title().'<br/>';
/**
* End loop
*/
endwhile;
endif;
/**
* Get theme footer
*/
get_footer(); ?>
I'm trying to create a tabbed version of "My Account" in woocommerce.
I have built my pages in php using bootstrap css and included the wordpress header and footer so the page loads correctly.
The tabs display as expected by I am having an issue with the endpoint urls in woocommerce:
- 'edit-address'
- 'view-order'
These endpoints are generated dynamically and appended to the url: www.site-name.com/my-account/edit-address
Here's the function call (in file .plugins/woocommerce/myaccount/form-edit-address.php):
<a href="<?php echo wc_get_endpoint_url( 'edit-address', $name ); ?>
I've included 'my-addresses' in my tabbed page which dispays ok. However, the link to edit the shipping and billing addresses is generated by the above call to the endpoints. When the link is clicked the page fails to load and returns a 404 error.
My custom php page is basically www.site-name.com/account/edit-address
The problem is:
The 'edit-address' page content is not loading and I get a 404 error
I'm guessing the issue is caused because my pages are external php pages and not stored with wp database?
Is there a way I can customise the endpoint url so it appends correctly and loads the page?
Link to the page on my site: www.thecookerytutor dot co dot uk/account
Origional woocommerce my-account page: www.thecookerytutor dot co dot uk/my-account
(You will need to create a login to view both pages)
It's had me stumped for days!
Thanks in advance.
Code for my addresses tab on my custom php page as promised...
echo "<div id = 'edit-addresses' class='tab-pane fade'>";
echo "<div id = 'content' class = 'page col-full'>";
echo "<section id = 'main' class = 'col-left'>";
echo "<BR>";
include "my-address.php";
echo "</section>";
echo "</div>";
echo "</div>";`
As you can see I'm including the wc page that loads the addresses (I've copied to the local folder)
Here's the content of edit-address.php (I've copied to my local folder and added wp header). The page loads the header but the get address function fails at line 50.
<?php
define('WP_USE_THEMES', false);
require('../wp-blog-header.php');
add_filter( 'wp_title', 'wp_title_so_18381106', 10, 3 );
function wp_title_so_18381106( $title, $sep, $seplocation )
{
return 'Your Account | ';
}
get_header();
?>
<?php
/**
* Edit address form
*
* #author WooThemes
* #package WooCommerce/Templates
* #version 2.1.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
global $current_user;
$page_title = ( $load_address === 'billing' ) ? __( 'Billing Address', 'woocommerce' ) : __( 'Shipping Address', 'woocommerce' );
get_currentuserinfo();
?>
<?php wc_print_notices(); ?>
<?php //if ( ! $load_address ) : ?>
<?php //wc_get_template( 'myaccount/my-address.php' ); ?>
<?php //else : ?>
<form method="post">
<h3><?php echo apply_filters( 'woocommerce_my_account_edit_address_title', $page_title ); ?></h3>
<?php do_action( "woocommerce_before_edit_address_form_{$load_address}" ); ?>
/fails to load here/
<?php foreach ( $address as $key => $field ) : ?>
<?php woocommerce_form_field( $key, $field, ! empty( $_POST[ $key ] ) ? wc_clean( $_POST[ $key ] ) : $field['value'] ); ?>
<?php endforeach; ?>
<?php do_action( "woocommerce_after_edit_address_form_{$load_address}" ); ?>
<p>
<input type="submit" class="button" name="save_address" value="<?php _e( 'Save Address', 'woocommerce' ); ?>" />
<?php wp_nonce_field( 'woocommerce-edit_address' ); ?>
<input type="hidden" name="action" value="edit_address" />
</p>
</form>
<?php //endif; ?>
WooCommerce is a plugin for WordPress, you can't use it without WordPress... for example /my-account/edit-address/, that my-account is actually the page you are rendering and edit-address is just a variable. edit-address was added as an endpoint to my-account. you need to do the same for your account.
You should get an idea of what endpoints are.
Other thoughts about this. If you really want to use account and not my-account, look into your pages for "My Account" and change it's permalink. You can also create another page that can use account in it's permalink. Then use that page in your WooCommerce > Settings > Account tab > My Account Page.
If you have some custom php codes, you can just copy the template from your woocommerce plugin to your theme folder and edit the file you need. Read Template Structure + Overriding Templates via a Theme.
And if I have not addressed your problem, comment down below.
I am customizing a wordpress plugin which is used for popup email subscribing. when the user submits email he gets a confirmation email in which iam sending my custom html to him. I have five different pages on my web site and every page has that popup. what iam doing is that i want to get the name of my page than according to that i want to send html in email. I did exactly the same thing for other plugin and it worked but in this popup plugin iam unable to get the page name from where it is called.
I have tried following things but failed.
global $post; /* this worked perfect on other plugin */
$pagename = $post->post_name;
if($pagename=="page1")
{
// html page1 //
}
else
{
// html page2 //
}
Just tried this
$slug = basename(get_permalink());
if($slug=="page1") and so on
Here you go, you need to get title for this, as
$post = get_post( $post );
$pagename = isset( $post->post_title ) ? $post->post_title : '';
Hope it helps.
The best way is to use get_queried_object. It retrieve the currently-queried object - page, post, taxonomy, whatever...
You can try this code, its working for me:
$qo = get_queried_object();
if ( 'page' !== $qo->post_type ) {
//Here you can be sure, that you are in page query, so this is available
$pagename = $qo->post_name;
}
Please try to use this:
$pagename = get_query_var('pagename');
if ( !$pagename && $id > 0 ) {
// If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object
$post = $wp_query->get_queried_object();
$pagename = $post->post_name;
}
I'm new to Wordpress & PHP, so kindly excuse the naivety of the question, if any.
I'm building a plugin where I need to select values from the database and create a new HTML page with the values. I'm using a custom template file.
What I've done till now
Extracted the values from database
Load & display my own template in my plugin file
add_action( 'init', 'leb_add_endpoint' );
function leb_add_endpoint()
{
add_rewrite_endpoint( 'result', EP_PERMALINK );
}
add_action( 'template_include', 'leb_render_template' );
function leb_render_template($default_template) {
//some code removed for brevity
if ( ! is_singular() || !isset($wp_query->query_vars['result']) )
{
return $default_template;
}
$sample_result = $wpdb->get_var($wpdb->prepare($sql));
$default_template = plugin_dir_path(__FILE__) . '/my-custom-template.php';
return $default_template;
}
The content of my-custom-template.php is as follows
<?php
/* Template Name: My Template*/
echo '<h1>Testing</h1>';
?>
The page gets displayed without any problem. All I want is to insert $sample_result and other similar results pulled form database into my-custom-template.php
I need to generate dynamic pages based on values pulled from DB. So each time, the final page created might be different. E.g. if one hits www.example.com/sample-post/result, a page will be shown with values pulled from the DB. If one hits www.example.com/another-sample-post/result, a different page will be shown with different values. Both these pages will have the same design, only a few values will be different. This is what I'm trying to achieve.
How can I do that? Please help me. I'm stuck. :(
You need to define "result" in query vars.
Use EP_ROOT Endpoint Mask ( result/{var} is located in the root )
Inside template_include hook, you can find result value inside $wp_query object.
I've already tested the code
// Add a new var to query vars
function result_add_query_vars( $vars ){
$vars[] = 'result';
return $vars;
}
add_filter( 'query_vars', 'result_add_query_vars' );
// Add endpoint
function result_add_endpoint() {
add_rewrite_endpoint( 'result', EP_ROOT );
}
add_action( 'init', 'result_add_endpoint');
// change the template
function result_render_template($template)
{
global $wp_query;
if ( array_key_exists( 'result', $wp_query->query_vars ) ) {
$result = get_query_var('result');
$new_template = plugin_dir_path(__FILE__) . '/my-custom-template.php';
return $new_template;
} else {
return $template;
}
}
add_action( 'template_include', 'result_render_template' );
Now you can retrieve the query var in your custom template
/*
* Template Name: My Custom Template
*/
$result = get_query_var('result');
echo $result;
Well why don't you use $wp_query Inside your my-custom-template.php
<?php
/* Template Name: My Template*/
global $wp_query;
echo '<pre>';
print_r($wp_query); // Use this in case you want to see what else do you have with you.
echo '<pre/>';
// Now you can use $wp_query to build your dynamic query at run time.
// This will allow you to perform task at run time
?>
To Retrieve Meta
If you have saved something as a meta then
<?php
$meta_values = get_post_meta( $post_id, $key, $single );
?>
To Retrieve Child Post
If you want to retrieve child posts then
<?php
if ( have_posts() ) :
// Start the Loop.
while ( have_posts() ) : the_post();
// Do your stuff here such as below
the_title();
the_content();
endwhile;
else:
echo 'No Post Found';
endif;
?>
1) Write this function in function.php in your active template.
function leb_render_template() {
//some code removed for brevity
//$sql = 'YOUR_QUERY_CODE'
$sample_result = $wpdb->get_var($wpdb->prepare($sql));
return $my_template;
}
add_action('wp_ajax_leb_render_template', 'leb_render_template');
add_action('wp_ajax_nopriv_leb_render_template', 'leb_render_template');
2) Call function in your custom template.
<?php
/* Template Name: My Template*/
echo '<h1>Testing</h1>';
$result = leb_render_template();
print_r($result); // Print Your function output.
?>
I am making a plugin, to register a shortcode, which when used like this: [append_css mycss] it will look for a custom field called mycss and add the contents to the head of the document. It all works great, except that the code is being added to the body, and I don't know how to get it to add to the head.
I have tried adding an action wp_head but I don't know how to pass variables whilst doing that, and it does not seem to fire from within the shortcode callback anyway.
function append_css_short($params){
global $post;
if(sizeof($params)){
$key = $params[0];
} else {
$key = 'css';
}
return '<style type="text/css">'.
get_post_meta($post->ID, $key, true)
.'</style>';
}
add_shortcode('append_css','append_css_short');
How would I get this to write to the head instead of body?
Is there a better approach to the problem?
If you want to print something to the head of the document you need use add_action with wp_head hook.
A better approach might be to not use a shortcode at all. Shortcodes are intended to add content or modify content. Instead create a function that you can attach to wp_head that will print your css. You may want to force the user to keep the custom field name consistent. Or better yet have your plugin add a metabox to posts that they can enter custom css into. Then you will always be certain of the name of the field.
function append_css() {
global $post;
if ( ! get_post_meta( $post->ID, 'mypluginname_css', true ) ) {
return;
}
return '<style type="text/css">'. get_post_meta($post->ID, $key, true) .'</style>';
}
add_action( 'wp_head', 'append_css' );
The only thing i am not certain of is whether or not $post with the custom field data will be available outside the loop. So you may have to add some extra querying in there to pull the custom data at the time that wp_head is fired.
With some minor adjustments to the answer provided by #Jrod, here is the complete working plugin, with usage as follows:
Create custom field called append_css (or append_js) with required code
... of course, there is no number 2 ;)
Code
<?php
/**
* #package Append_CSS_JS
* #version 0.1
*/
/*
Plugin Name: Append CSS JS
Plugin URI: http://itaccess.org/wordpress-plugins/append-css-js/
Description: Append Css or Js to any page using Custom Fields
Author: Billy Moon
Version: 0.1
Author URI: http://billy.itaccess.org/
*/
function append_css() {
global $post;
if ( ! get_post_meta( $post->ID, 'append_css', true ) ){
return;
}
echo '<style type="text/css">'. get_post_meta($post->ID, 'append_css', true) .'</style>';
}
add_action( 'wp_head', 'append_css' );
function append_js() {
global $post;
if ( ! get_post_meta( $post->ID, 'append_js', true ) ) {
return;
}
echo '<script type="text/javascript">'. get_post_meta($post->ID, 'append_js', true) .'</script>';
}
add_action( 'wp_head', 'append_js' );
?>
I don't think this is possible that way, because shortcodes will be called after wp_head(), so you cannot hook on it.
Here's the list of all wordpress hooks http://adambrown.info/p/wp_hooks
EDIT:
Here's a workaround:
In your template:
<?php
//get the content of your post:
if(have_posts()) while(have_posts()) the_post();
$pcontent = get_the_content();
endwhile;
?>
<html>
<head>
...
</head>
<body>
...
<?php echo $pcontent; ?>
</body>
</html>