AMP version of e-commerce without plugin - php

I have two product pages of an ecommerce website: one made with Woocommerce (in WordPress) and one I coded my self in AMP.
Here is the WordPress page, and here is the AMP page. Not taking into account that the two pages are on two different subdomains, how would I redirect mobile users to the AMP version of the page ?
A similar question was asked, but it only specified how to do it for simple pages, not product pages.
Does anyone know how to that?

To answer your question, You have to hard code this following lines in your theme functions.php if you don't want to use plugin.
Following ways to make it work as per your question
Create Metabox in Product Post Type of WooCommerce
Add Input Field to the Created Metabox
Save the Input Field via save_post action hook
Input the Specific URL for each Product
Fetch the saved data from Product and redirect if it is a mobile user.
Step 1: Create Metabox
//Create Metabox
function wc_49570125_register_meta_boxes() {
add_meta_box('meta-box-id', __('Mobile Version URL', 'yourtextdomain'), 'wc_49570125_my_display_callback', 'product');
}
add_action('add_meta_boxes', 'wc_49570125_register_meta_boxes');
Step 2: Add Input Field
// Add Input Field
function wc_49570125_my_display_callback($post) {
$get_id = $post->ID;
$get_value = get_post_meta($get_id, 'wc_mobile_version_url', true);
?>
<p>
<label><?php _e('Mobile URL to Redirect', 'yourtextdomain'); ?></label>
<input type="text" name="wc_mobile_version_url" value="<?php echo $get_value; ?>"/>
</p>
<?php
}
Step 3: Save the Input Field
// save input field
function wc_49570125_save_meta_box($post_id) {
$post_type = get_post_type($post_id);
if ('product' != $post_type) {
return;
}
if (isset($_POST['wc_mobile_version_url'])) {
$mobile_version = $_POST['wc_mobile_version_url'];
update_post_meta($post_id, 'wc_mobile_version_url', $mobile_version);
}
}
add_action('save_post', 'wc_49570125_save_meta_box');
Step 4: Redirect mobile users to mobile version
// redirect input field
function wc_49570125_mobile_redirect() {
global $product, $post;
if (is_product()) {
$get_id = $post->ID;
$amp_location = get_post_meta($get_id, 'wc_mobile_version_url', true);
if (wp_is_mobile() && $amp_location) {
wp_redirect($amp_location);
exit;
}
}
}
add_action('wp', 'wc_49570125_mobile_redirect');
Step 5: Add Discoverable Link for Google
function wc_49570125_amp_google_link() {
global $product, $post;
if (is_product()) {
$get_id = $post->ID;
$amp_location = get_post_meta($get_id, 'wc_mobile_version_url', true);
if ($amp_location) {
?>
<link rel="amphtml" href="<?php echo $amp_location; ?>"/>
<?php
}
}
}
add_action('wp_head', 'wc_49570125_amp_google_link');
I tested above code and seems it works well.

Related

WordPress i want custom link in user list when i click the link get the images by user

I try to add link in user list by adding this code
function frontend_profile_action_link($actions, $user_object) {
$actions['view profile'] = "<a class='view_frontend_profile' href='".admin_url().'user-detail.php'."'>".__('View Profile', 'frontend_profile')."</a>";
return $actions;
}
add_filter('user_row_actions', 'frontend_profile_action_link', 10, 2);
I want to add custom link in user list like default edit link and then when I click this link get all images by user
I think you should tackle
<?php $user = get_user_by( $field, $value ); ?>
or if you specified a custom field in the registration form you can use
<?php get_userdata( $field ); ?>

Wordpress can't access globals and functions.php category edit page

i got my registered sidebars listing function in functions.php
everything works perfect on post options page (wp-admin/post.php)
i can get all the registered sidebars via my function.
but in the category edit page (wp-admin/edit-tags.php) ,
i can't even access the global variable $wp_registered_sidebars , not mentioning about the function itself.
here is the function
function sidebars_list(){
global $wp_registered_sidebars;
$sidebar = array();
if (!empty($wp_registered_sidebars)):
foreach ($wp_registered_sidebars as $key => $access):
$sidebar[$key] = $access['name'];
endforeach;
endif;
var_dump($sidebar);
return $sidebar;
}
as i said it works perfect on editing post and pages at the backend (frontend as well)
i tried to add_action it , no luck.
can't even access the global variable in category edit page.
global $wp_registered_sidebars;
var_dump($wp_registered_sidebars);
returns empty array.
but when i var_dump inside the function it returns as expected.
what's wrong ?
As you said that the global variable value not found. I assume that your variable got overwritten the value with empty array.
I suggest you to change the variable name and retry with var_dump the variable.
global $wp_registered_sidebars_custom;
var_dump($wp_registered_sidebars_custom);
After wasting a lot of time for searching this and thought out this solution. Accessing through a category page is earlier before sidebar values are loaded. So You can make a work around by placing a placeholder div in that place and load the values in the dropdown or checkbox using Ajax & jQuery after the page is loaded. that would work for you.
Paste the following code in functions.php of your theme
// Call Actio to modify form on Add New Category
add_action( 'category_add_form_fields', 'edit_category_fields');
// Call Action to modify form on Edit Category
add_action( 'category_edit_form_fields', 'edit_category_fields');
function edit_category_fields($tag, $taxonomy)
{
// Get the Current Value if any
$leftsidebar_to_show = get_term_meta( $tag->term_id, 'leftsidebar_to_show', true);
?>
<tr class="form-field">
<th scope="row" valign="top"><label for="leftsidebar_to_show">Select Left Sidebar to Show</label></th>
<td>
<div id="leftsidebar_to_show_wrap">
<select name="leftsidebar_to_show" id="leftsidebar_to_show">
</select>
</div>
<!-- Store the current value as hidden input in order to Get Selected Option in jQuery -->
<input type="hidden" id="leftsidebar_to_show_val" value="<?php echo $leftsidebar_to_show; ?>" />
<!-- Category ID as hidden Input -->
<input type="hidden" name="term_id_val" value="<?php echo $tag->term_id; ?>" />
</td>
</tr>
<?php
}
// Call Actio to Save Values on Add New Category
add_action( 'edited_category', 'save_category', 10, 2);
// Call Action to Save Values on Edit Category
add_action( 'create_category', 'save_category', 10, 2);
function save_category(){
update_term_meta( $_POST['term_id_val'], 'leftsidebar_to_show', $_POST['leftsidebar_to_show']);
}
// Function to enqueue Javascript file in admin
function my_enqueue($hook) {
wp_enqueue_script( 'my_custom_script', get_template_directory_uri() . '/js/sidebars.js' );
}
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
// Action Function to get Sidebars through Ajax Call
function prefix_ajax_get_sidebars() {
$sidebarval = $_REQUEST['sidebarval'];
$sidebarid = $_REQUEST['sidebarid'];
$string = '<select id="'.$sidebarid.'" name="'.$sidebarid.'">';
foreach ( $GLOBALS['wp_registered_sidebars'] as $sidebar ) {
if($sidebarval == $sidebar['id']){
$selected = ' selected';
}else{
$selected = '';
}
$string .= '<option value="'.$sidebar['id'].'"'.$selected.'>'.$sidebar['name'].'</option>';
}
$string .= '</select>';
echo $string;
die();
}
add_action( 'wp_ajax_get_sidebars', 'prefix_ajax_get_sidebars' );
add_action('wp_ajax_nopriv_get_sidebars', 'prefix_ajax_get_sidebars');
Create a file named sidebars.js and Paste the following code
(function ($) {
"use strict";
$(document).ready(function(){
var leftsidebar_to_show_val = $('#leftsidebar_to_show_val').val();
$.post(
ajaxurl,
{
'action': 'get_sidebars',
'sidebarval': leftsidebar_to_show_val,
'sidebarid' : 'leftsidebar_to_show'
},
function(response){
$('#leftsidebar_to_show_wrap').html(response);
});
});
})(jQuery);
And move the above created file to js folder of your theme. Now you can see the sidebars listed as dropdown in the Add & Edit Category Forms.
Hope this is clear.
Thanks!

Link title to external link instead of permalink

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.

How do I use a checkbox value from a wordpress meta box?

I'm trying to use custom meta boxes in wordpress. My goal at the moment is to create a meta box with a checkbox that I can use as a switch to turn on certain content. I've been scouring the web trying to piece together something that works, and so far I've gotten far enough to where I can generate a meta box with a checkbox, but the checked value isn't carrying over to the loop for some reason. When I try to output the array to see if I can get anything out of it, it's empty. I've looked at a ton of things and tried several meta box creation scripts, but I can't get any of them to work. This method looked to be the most promising, but now I'm stuck. Is there something important I'm missing here? It's as if the data isn't being saved. Code included below:
Meta Box functions. Located in functions.php:
// Checkbox Meta
add_action("admin_init", "checkbox_init");
function checkbox_init(){
add_meta_box("checkbox", "Checkbox", "checkbox", "post", "normal", "high");
}
function checkbox(){
global $post;
$custom = get_post_custom($post->ID);
$field_id = $custom["field_id"][0];
echo '<label>Check for yes</label>';
$field_id_value = get_post_meta($post->ID, 'field_id', true);
if($field_id_value == "yes") {
$field_id_checked = 'checked="checked"';
}
echo ' <input type="checkbox" name="field_id" value="yes" '.$field_id_checked.' />';
}
// Save Meta Details
add_action('save_post', 'save_details');
function save_details(){
global $post;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $post->ID;
}
update_post_meta($post->ID, "field_id", $_POST["field_id"]);
}
Code used to output content when checkbox is checked. This is also located in functions.php. The function is used in the loop.
function custom_content() {
if(isset($_POST['field_id']) && $_POST['field_id'] == 'yes') {
echo "It works!";
}
}
change your function on functions.php to
function custom_content($id) {
$field_id = get_post_meta($id, 'field_id', true);
if($field_id == yes) {
echo "It works!";
}
else{
echo 'Not working...';
}
}
And your template, call it inside the loop like the ff:
custom_content(get_the_ID());

Wordpress add_meta_box() weirdness

The code below is working nearly flawlessly, however my value for page title on one of my pages keeps coming up empty after a few page refreshes... It sticks for awhile, then it appears to reset to empty. I'm thinking I must have a conflict in the code below, but I can't quite figure it.
I'm allowing the user to set a custom page title for posts as well as pages via a custom "post/page title input field). Can anyone see an obvious issue here that might be resetting the page title to blank?
// ===================
// = POST OPTION BOX =
// ===================
add_action('admin_menu', 'my_post_options_box');
function my_post_options_box() {
if ( function_exists('add_meta_box') ) {
//add_meta_box( $id, $title, $callback, $page, $context, $priority );
add_meta_box('post_header', 'Custom Post Header Code (optional)', 'custom_post_images', 'post', 'normal', 'low');
add_meta_box('post_title', 'Custom Post Title', 'custom_post_title', 'post', 'normal', 'high');
add_meta_box('post_title_page', 'Custom Post Title', 'custom_post_title', 'page', 'normal', 'high');
add_meta_box('postexcerpt', __('Excerpt'), 'post_excerpt_meta_box', 'page', 'normal', 'core');
add_meta_box('categorydiv', __('Page Options'), 'post_categories_meta_box', 'page', 'side', 'core');
}
}
//Adds the custom images box
function custom_post_images() {
global $post;
?>
<div class="inside">
<textarea style="height:70px; width:100%;margin-left:-5px;" name="customHeader" id="customHeader"><?php echo get_post_meta($post->ID, 'customHeader', true); ?></textarea>
<p>Enter your custom html code here for the post page header/image area. Whatever you enter here will override the default post header or image listing <b>for this post only</b>. You can enter image references like so <img src='wp-content/uploads/product1.jpg' />. To show default images, just leave this field empty</p>
</div>
<?php
}
//Adds the custom post title box
function custom_post_title() {
global $post;
?>
<div class="inside">
<p><input style="height:25px;width:100%;margin-left:-10px;" type="text" name="customTitle" id="customTitle" value="<?php echo get_post_meta($post->ID, 'customTitle', true); ?>"></p>
<p>Enter your custom post/page title here and it will be used for the html <title> for this post page and the Google link text used for this page.</p>
</div>
<?php
}
add_action('save_post', 'custom_add_save');
function custom_add_save($postID){
if (!defined('DOING_AUTOSAVE') && !DOING_AUTOSAVE) {
return $postID;
}
else
{
// called after a post or page is saved and not on autosave
if($parent_id = wp_is_post_revision($postID))
{
$postID = $parent_id;
}
if ($_POST['customHeader'])
{
update_custom_meta($postID, $_POST['customHeader'], 'customHeader');
}
else
{
update_custom_meta($postID, '', 'customHeader');
}
if ($_POST['customTitle'])
{
update_custom_meta($postID, $_POST['customTitle'], 'customTitle');
}
else
{
update_custom_meta($postID, '', 'customTitle');
}
}
}
function update_custom_meta($postID, $newvalue, $field_name) {
// To create new meta
if(!get_post_meta($postID, $field_name)){
add_post_meta($postID, $field_name, $newvalue);
}else{
// or to update existing meta
update_post_meta($postID, $field_name, $newvalue);
}
}
?>
Wordpress's auto save system may well be your problem, as I think custom fields are not passed along for auto saves (so your customHeader and customTitle post variables will be empty during an auto save).
In your save function you should check if the DOING_AUTOSAVE constant is set (this seems to be preferable to checking the post action) and return if so. Something like this:
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
See this ticket for more info: http://core.trac.wordpress.org/ticket/10744
The WordPress Codex has got an function reference for add_meta_box(), with a great example.
And yes, it uses
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post_id;
and I think you've implemented it the right way.
FYI, the solution posted here http://wordpress.org/support/topic/custom-post-type-information-disappearing worked for me and I think is much more elegant.

Categories