mardi 31 mars 2015

Mamp Pro Permissions on Wordpress

Use the last pro version of MAMP on Yosemite


Every time when wordpress install or load a file I have to necessarily change the permissions, this is inconvenient to do every time.


Is there a way to use the permissions without changing them every time?


This is my config: http://ift.tt/1Fgk2dC


Thanks.


JSON API wordpress plugin response is sometimes too slow

Sometimes the response (in json format) provided by JSON API wordpress plugin is too slow. So is there any way to cache the json response ?


Any help will be very much appreciated.


Revolution slider won't scale properly on mobile

The revolution slider on http://ift.tt/1C5Gf9o will not scale properly on mobile. The revolution slider conists of just background images.


I really need to fix this! I've looked everywhere to find a solution, but can't!


Genesis - Turn off menu on certain pages

I want to turn off a the menu on certain pages in a genesis framework for WP. I have the following code:



function turn_off_menu() {
if (!is_front_page() || !is_page('blog')) {
remove_action( 'genesis_after_header','genesis_do_nav' ) ;
}
}

add_action( 'init', 'turn_off_menu');


But this is turning off the menu on every page.


Does voice theme of wordpress supports facebook, twitter and instagram feeds?

I am looking for buying voice theme for my website , one query i have is does it support facebook, twitter and instagram feeds? and if not what are best free plugins from where i can get these.


After user registration sending mail subject wordpress

Wordpress after registration,I got one mail with username,password,login link,And the mail is coming from from: WordPress

wordpress@mywebsitename.com ,

why and how can I change It to mywebsite like that Can you help me(I dont want wordpress name to display to client or customers)...


And I got the link like that Password: mI11kzfmySDb

http://ift.tt/YD36Oc

How can I change Thins link to

http://ift.tt/1IOvEFR


From advanced rest client to wordpress with json

How to get simple fields from an post. If i'm typing an "http://ift.tt/19BZMIn" in advanced rest client then i'm not getting any simple field . I'm getting all data related to that post.


WooCommerce disable local delivery for specific catagory

I am using WC 2.3.7 on WP 4.1.1 with Bluehost as my host. I have successfully (through research and trial and error) disabled free shipping for a specific category (id 64) "toys". I can not figure out how in gods name to disable the option for local delivery or local pick up for this category. All of the items in this category will be drop shipped. Please help.


display one array randomly on other array

i have some problem, I need to display one array randomly on other array For example : i need to display $advertises on $abc but there are display many more post


$args =array( 'post_type' => 'post',



'meta_query' =>
array(
'relation'=>'OR',
array(
'key' => 'to_event_date',
'value' => date('Y/m/d'),
'type' => 'date',
'compare'=>'>=',
),
'relation'=>'OR',
array(
'key' => 'to_event_date',
'value' => '',
'compare'=>'=',
)
)
);


$test = query_posts( $args );


$advertise1 = array( 'posts_per_page' => 1,



'order' => 'DESC',
'post_type' => 'advertise',
'post_status' => 'publish',

'suppress_filters' => true);



$advertises=get_posts($advertise1);

$rand_position=rand(0,2);


foreach($advertises as $mpost){
$advertise=$mpost;

}
array_splice($test, $rand_position, 0, $advertise);


somebody help me?


Wordpress redirect

I have a wordpress installation on a wp folder.


I need my clients write


www.example.com


in the browser, and the page


'about'


to be displayed, preserving the www.example.com address, not showing the http://ift.tt/19BAcTz address.


Which are the proper way to do this?.


Open ad clicking anywhere in wordpress

I have wordpress site and I'm using this script



onclick="<?php if(!isset($_COOKIE['visited'])){echo"window.open('http://link', '_blank')"; setcookie("visited", "1", time()+3600*24); header("Refresh:0");} ?>"


in body line. So it means I'm using



<body <?php body_class(); ?> onclick="<?php if(!isset($_COOKIE['visited'])){echo"window.open('http://link', '_blank')"; setcookie("visited", "1", time()+3600*24); header("Refresh:0");} ?>">


on header.php file of the theme.


But it opens the link in every click. I want to open it only one time until I refresh the page or open new page. How can I do it. Please help. Thanks in advance.


Greetings.


Why MySql query update with guid don't affect rows?

I have a MySql query update:



UPDATE wp_posts SET guid = REPLACE (guid, 'http://oldcomain.com/', 'http://ift.tt/1bP7JLx') WHERE post_type = 'attachment';


I'm using it on wordpress domain, inside amazon rds database, i'm updating it via MySQL Workbench and get there results:



0row(s) affected Rows matched: 24103 Changed: 0 Warning: 0



As you can see it finds rows that i need, but it does not update, i'm trying update all my wordpress media that is on wordpress to my cdn amazon s3 url.


Update: Also tried:



UPDATE wp_posts SET post_content = REPLACE (post_content, 'olddocmain.com', 'newcdndomain.com') WHERE post_type = 'attachment';



Doesn't work ether.


Homestead 403 Error / Directory Permissions / Serving From Root

I'm currently developing a couple WordPress sites using Laravel's Homestead for local development.


I had things setup and working, but recently upgraded to a Mac workstation and can't remember exactly what I did to get things setup on my old machine.


I'm serving the sites from the root of the mapped folder instead of the /public/ directory, the default of Homestead.


When I try and load the site in the browser I get a 403 Permission error.


I remember on my old machine I had to edit some directory permissions for Homestead server to get things working, but can't remember exactly where or what.


Thanks for any help,


Setting up in-video ads with JWplayer wordpress plugin

I've tried and tried to make this code work but with no success.



<script src="http://ift.tt/13qgtmt"></script>
<script type="text/javascript">
jwplayer().onReady(function() {
var currentItem = jwplayer().getPlaylistItem().file + ‘?wmode=transparent’;
jwplayer().load({file: currentItem});
var params = {
ignore_swfobject: '1'
});
</script>
<script type="text/javascript">
var exoOpts = {
cat: '118',
login: 'thelogin',
idzone_300x250: '720635',
idzone_468x60: '720635',
idsite: '243347',
pause: {},
postroll: {},
show_thumb: '1'
};
</script>
<script type="text/javascript" src="http://ift.tt/1FJcLUu"></script>


The ad appears when the video is on pause. It just makes the video disappear and there is no way back to the video other than reloading the page. I tried to put this code before the video in the post page to set wmode to transparent and the -



var params = {
ignore_swfobject: '1'
};


As specified by the ad network. I'm pretty new to this.. Did I messed up something? Did added it in the wrong place? I put it in single-video.php. I use Wordpress self hosted. Can you help me with this?


Thanks a lot


Wordpress: Shortcut to 'Create gallery'?

I want to make a button which opens a box just like Add Media does when creating a new post, however I want that button to switch to the Create gallery tab automatically. Here's a screenshot so you can understand what I mean: enter image description here


Basically I want a button just like the Add media button, but which automatically switches to the Create Gallery section.


Is there any way I can do that?


$_GET['email'] did not include the '@' character?

I made a custom form for forget password in WP.


below is the code that use:



<form name="lostpasswordform" id="lostpasswordform" action="'.wp_lostpassword_url().'" method="post">
<label for="user_login">Username:<br>
<input name="user_login" id="user_login" class="input" value="" size="" type="text"></label><br><br>
<label for="user_email">E-mail Address:<br>
<input name="user_email" id="user_email" class="input" value="" size="" type="text"></label>
<input type="hidden" name="" id="url_temp" value="'.str_replace( '%7E', '~', $_SERVER['REQUEST_URI']).'&axcelerate=forgotpassword">
<input name="redirect_to" value="&user_login=&user_email=" type="hidden" id="lostpasswordform_addon"><br><br>
<p class="submit">
<input name="wp-submit" id="wp-submit" class="button button-primary button-large" value="Get New Password" type="submit">
</p>
</form>

<script>
jQuery('#lostpasswordform #user_login').blur(function() {
jQuery('#lostpasswordform_addon').val( jQuery('#url_temp').val() + '&user_login=' + jQuery(this).val() + '&user_email=' + jQuery('#lostpasswordform #user_email').val());
});

jQuery('#lostpasswordform #user_email').blur(function() {
jQuery('#lostpasswordform_addon').val( jQuery('#url_temp').val() + '&user_login=' + jQuery('#lostpasswordform #user_login').val() + '&user_email=' + jQuery(this).val());
});
</script>


I have a problem in the email value when I check into redirect_to the email format is correct eg. nameof@mail.com


but when I try to set up in a function suing this code:



if($_GET['axcelerate'] == 'forgotpassword'){
echo $_GET['user_email'];
}


it returns nameofmail.com and not nameof@mail.com ?


does anyone have an idea about my case?


Trying to hide image styling, if no image is present - Advanced Custom Fields images

I have styled my images on my Content Page Template to have borders, backgrounds and box-shadow. If I don't use the optional image field and leave it empty, it leaves the css styling with a small box. I have been trying to hide the entire .content-img class if there is no image present. The code below works fine for rendering the images if they are present. How to hide it if no image is present.


<?php the_field('top_headline'); ?></h1>

<div class="content-top"><?php the_field('content_top'); ?></div> <div class="content-img"><?php $image = get_field('content_image'); $size = 'medium'; // (thumbnail, medium, large, full or custom size) if( $image ) { echo wp_get_attachment_image( $image, $size ); } ?>


Thanks for your help in advance.


Saving add_meta_box data to multiple post_types

I have the following code to create and save custom meta boxes within my Wordpress site. This solution works fine for my 'work' post_type, but will not save on a standard 'post'. The meta boxes appear fine on both post_types, but will only save on 'work'. Therefore I believe the issue lies within the save function, but I cannot decipher any reason why this works on only the one post_type?


I have pared the below code down to what I believe is the essential code.


Thanks.



// Allow registering of custom meta boxes
add_action( 'add_meta_boxes', 'add_custom_metaboxes' );

// Register the Project Meta Boxes
function add_custom_metaboxes() {
$post_types = array ( 'post', 'work' );
foreach( $post_types as $post_type )
{
add_meta_box('xx_introduction', 'Introduction', 'xx_introduction', $post_type, 'normal', 'high');
add_meta_box('xx_more', 'More', 'xx_more', 'work', 'normal', 'high');
}
}

// Add Introduction Metabox
function xx_introduction() {
global $post;

// Noncename needed to verify where the data originated
echo '<input type="hidden" name="introductionmeta_noncename" id="introductionmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';

// Get the introduction data if its already been entered
$introduction = get_post_meta($post->ID, '_introduction', true);

// Echo out the field
echo '<textarea name="_introduction" class="widefat" rows="5">' . $introduction . '</textarea>';

}

// Add More Metabox
function xx_more() {
global $post;

// Noncename needed to verify where the data originated
echo '<input type="hidden" name="moremeta_noncename" id="moremeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';

// Get the more data if its already been entered
$more = get_post_meta($post->ID, '_more', true);

// Echo out the field
echo '<textarea name="_more" class="widefat" rows="5">' . $more . '</textarea>';

}

// Save the Metabox Data
function xx_save_custom_meta($post_id, $post) {

// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !wp_verify_nonce( $_POST['introductionmeta_noncename'], plugin_basename(__FILE__) )) {
return $post->ID;
}
}

// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;

// OK, we're authenticated: we need to find and save the data
// We'll put it into an array to make it easier to loop though.

$introduction_meta['_introduction'] = $_POST['_introduction'];
$more_meta['_more'] = $_POST['_more'];

// Add values of $introduction_meta as custom fields
foreach ($introduction_meta as $key => $value) { // Cycle through the $testimonial_meta array
if( $post->post_type == 'revision' ) return; // Don't store custom data twice
$value = implode(',', (array)$value); // If $value is an array, make it a CSV (unlikely)
if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
update_post_meta($post->ID, $key, $value);
} else { // If the custom field doesn't have a value
add_post_meta($post->ID, $key, $value);
}
if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
}
}

// Add values of $more_meta as custom fields
foreach ($more_meta as $key => $value) { // Cycle through the $more_meta array
if( $post->post_type == 'revision' ) return; // Don't store custom data twice
$value = implode(',', (array)$value); // If $value is an array, make it a CSV (unlikely)
if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
update_post_meta($post->ID, $key, $value);
} else { // If the custom field doesn't have a value
add_post_meta($post->ID, $key, $value);
}
if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
}
}

add_action('save_post', 'xx_save_custom_meta', 1, 2); // save the custom fields


UPDATE: Having experimented with this for a couple of days, I have a semi solution to the issue I was experiencing. In the original code, I was attempting to register three meta boxes, but placing two of them in multiple post types ($post_type) and the other in just a single post type (work). I have not determined the cause, but this is what was causing the meta data not to save in one of the post types.


Whilst this isn't a full answer with a detailed breakdown, it at least locates the source of the issue, and my initial thought that the issue lies within the save function is correct, I just don't know how to fix this myself. This solution works fine for me however so I won't be investing anymore time into this issue.


Hopefully this is of use to others at least as a starting point.



// Register the Project Meta Boxes
function add_custom_metaboxes() {
$post_types = array ( 'post', 'work' );
foreach( $post_types as $post_type )
{
add_meta_box('xx_introduction', 'Introduction', 'xx_introduction', $post_type, 'normal', 'high');
add_meta_box('xx_more', 'Introduction', 'xx_introduction', $post_type, 'normal', 'high');
}
}

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in /clientdata/apache-www/r/i/http://ift.tt/1EApsm8 on line 17 [duplicate]


This question already has an answer here:




I am receiving the following error message on my site: Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in /clientdata/apache-www/r/i/http://ift.tt/1EApsm8 on line 17


I am not a programmer, simply a pleb attempting to teach myself something. I have searched the interwebs for some ideas on how to fix the problem and have made every change I'm game to, to see if I can fix it myself. However, when I make changes I either receive the same error or a similar one.


The site was working perfectly less than a week ago!


I guess one of my problems is that I don't understand what T_CONSTANT_ENCAPSED_STRING means so I don't know what might be wrong. Although I guess there's a string that is encapsulated incorrectly - but what?


The index.php file is:



<?php
/**
* Front to the WordPress application. This file doesn't do anything, but loads
* wp-blog-header.php which does and tells WordPress to load the theme.
*
* @package WordPress
*/

/ **
* Tells WordPress to load the WordPress theme and output it.
*
* @var bool
*/
define('WP_USE_THEMES', true);

/** Loads the WordPress Environment and Template */
require('dirname( __FILE__ )./wordpress/wp-blog-header.php');(include path '.:/clientdata/php/pear-5-3:/clientdata/php/lib');

How can I invoke a form when an item from the navigation menu is clicked?

I am trying to develop a website where I want to have a 'Contact Us' tab in the navigation menu on all pages however, I don't want it to take the user to a new page where he can do his submission. I want to invoke a new dialog/window when this is clicked that has the form. After the submission, the dialog/window is closed with a message of successful submission and the user remains on the same page as where he was when he clicked 'Contact Us'. Any help would be appreciated. Thank you.


Details: I am using WordPress for my website and the plugin - Quforms for the form.


Building affiliate program link to track

My business is selling products on our website (Wordpress based) and we are trying to set up an affiliate program so people can get paid for promoting our products when someone purchases one of them.


My questions is how could I set up a URL link (http://ift.tt/19ABsqd) and be able to not only track it but see when that person has paid with PayPal so we can pay the proper affiliate


People have suggested clickbank and jvzoo but we would like to do this on our own


Any help would be much appreciated


Java jpa error querying a wordpress database that contains empty fields

I have a java application that needs to access a wordpress database as I can not do all I need to using wordpress xml-rpc. The main table I need to access in wordpress is the wp_posts table. I am using eclipseLink 2.6 and mysql 5.1.34


The following is my wp_posts entity



@Entity
@Table(name="wp_posts")
public class WpPost implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@Column(name="ID")
private Integer id;

@Column(name="comment_count")
private Integer commentCount;

@Column(name="comment_status")
private String commentStatus;

@Column(name="guid")
private String guid;

@Column(name="menu_order")
private Integer menuOrder;

@Column(name="ping_status")
private String pingStatus;

More vars + getters and setters etc.....


And I run my query like so



public final static String SELECT_ALL_WP_POST_ENTITIES_SQL = "SELECT o FROM WpPost AS o";

public List<WpPost> getAllEntities() {

final EntityManager entityManager = DaoUtilities
.getEntityManagerFactory().createEntityManager();
final List<WpPost> posts;
try {
posts = (List<WpPost>) entityManager.createQuery(
SELECT_ALL_WP_POST_ENTITIES_SQL).getResultList();
} finally {
entityManager.close();
}

return posts;

}


I get the following error



[EL Info]: server: 2015-03-31 10:10:59.234--ServerSession(472654579)--Detected server platform: org.eclipse.persistence.platform.server.NoServerPlatform.
[EL Info]: server: 2015-03-31 10:10:59.682--ServerSession(472654579)--Detected server platform: org.eclipse.persistence.platform.server.NoServerPlatform.
[EL Info]: 2015-03-31 10:11:00.296--ServerSession(472654579)--EclipseLink, version: Eclipse Persistence Services - 2.6.0.v20150309-bf26070
[EL Info]: connection: 2015-03-31 10:11:00.752--ServerSession(472654579)--/file:/home/alex/Dropbox/eclipseProjects/docoCrawler/wordpressDB/target/classes/_DefaultPersistence login successful
[EL Warning]: sql: 2015-03-31 10:11:00.818--ServerSession(472654579)--java.sql.SQLException: Value '390open;http://ift.tt/19sJaCH
[EL Warning]: 2015-03-31 10:11:00.82--UnitOfWork(91430202)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Value '390open;http://ift.tt/19sJaCH
Error Code: 0
Call: SELECT ID, comment_count, comment_status, guid, menu_order, ping_status, pinged, post_author, post_content, post_content_filtered, post_date, post_date_gmt, post_excerpt, post_mime_type, post_modified, post_modified_gmt, post_name, post_parent, post_password, post_status, post_title, post_type, to_ping FROM wp_posts
Query: ReadAllQuery(referenceClass=WpPost sql="SELECT ID, comment_count, comment_status, guid, menu_order, ping_status, pinged, post_author, post_content, post_content_filtered, post_date, post_date_gmt, post_excerpt, post_mime_type, post_modified, post_modified_gmt, post_name, post_parent, post_password, post_status, post_title, post_type, to_ping FROM wp_posts")
Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Value '390open;http://ift.tt/19sJaCH
Error Code: 0
Call: SELECT ID, comment_count, comment_status, guid, menu_order, ping_status, pinged, post_author, post_content, post_content_filtered, post_date, post_date_gmt, post_excerpt, post_mime_type, post_modified, post_modified_gmt, post_name, post_parent, post_password, post_status, post_title, post_type, to_ping FROM wp_posts
Query: ReadAllQuery(referenceClass=WpPost sql="SELECT ID, comment_count, comment_status, guid, menu_order, ping_status, pinged, post_author, post_content, post_content_filtered, post_date, post_date_gmt, post_excerpt, post_mime_type, post_modified, post_modified_gmt, post_name, post_parent, post_password, post_status, post_title, post_type, to_ping FROM wp_posts")
at org.eclipse.persistence.internal.jpa.QueryImpl.getDetailedException(QueryImpl.java:382)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:260)
at org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:473)
at dao.PostDao.getAllEntities(PostDao.java:43)
at dao.PostDao.main(PostDao.java:33)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Value '390open;http://ift.tt/19sJaCH
Error Code: 0
Call: SELECT ID, comment_count, comment_status, guid, menu_order, ping_status, pinged, post_author, post_content, post_content_filtered, post_date, post_date_gmt, post_excerpt, post_mime_type, post_modified, post_modified_gmt, post_name, post_parent, post_password, post_status, post_title, post_type, to_ping FROM wp_posts
Query: ReadAllQuery(referenceClass=WpPost sql="SELECT ID, comment_count, comment_status, guid, menu_order, ping_status, pinged, post_author, post_content, post_content_filtered, post_date, post_date_gmt, post_excerpt, post_mime_type, post_modified, post_modified_gmt, post_name, post_parent, post_password, post_status, post_title, post_type, to_ping FROM wp_posts")
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:331)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.getObject(DatabaseAccessor.java:1331)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.fetchRow(DatabaseAccessor.java:1077)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.processResultSet(DatabaseAccessor.java:770)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:657)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:560)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:2055)
at org.eclipse.persistence.sessions.server.ServerSession.executeCall(ServerSession.java:570)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:242)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeSelectCall(DatasourceCallQueryMechanism.java:299)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.selectAllRows(DatasourceCallQueryMechanism.java:694)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRowsFromTable(ExpressionQueryMechanism.java:2740)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRows(ExpressionQueryMechanism.java:2693)
at org.eclipse.persistence.queries.ReadAllQuery.executeObjectLevelReadQuery(ReadAllQuery.java:541)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1173)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:904)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1132)
at org.eclipse.persistence.queries.ReadAllQuery.execute(ReadAllQuery.java:442)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1220)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2896)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1857)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1839)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1804)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:258)
... 3 more
Caused by: java.sql.SQLException: Value '390open;http://ift.tt/19sJaCH
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:996)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:935)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:924)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:870)
at com.mysql.jdbc.ResultSetRow.getTimestampFast(ResultSetRow.java:928)
at com.mysql.jdbc.BufferRow.getTimestampFast(BufferRow.java:555)
at com.mysql.jdbc.ResultSetImpl.getTimestampInternal(ResultSetImpl.java:5943)
at com.mysql.jdbc.ResultSetImpl.getTimestamp(ResultSetImpl.java:5609)
at com.mysql.jdbc.ResultSetImpl.getObject(ResultSetImpl.java:4582)
at org.eclipse.persistence.internal.databaseaccess.DatabasePlatform.getObjectFromResultSet(DatabasePlatform.java:1392)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.getObject(DatabaseAccessor.java:1302)
... 26 more


On the wp_posts table all columns have 'not null' selected however they are not all given default values. From my error message I can see from the line



java.sql.SQLException: Value '390open;http://ift.tt/19sJaCH


that it is getting the first row from the database with the values '39, 0, open, http://ift.tt/1CF08ck, 0, open' that map to 'SELECT ID, comment_count, comment_status, guid, menu_order, ping_status'. However the next field in the query 'pinged' has no value in the database and this is where it fails. If I add a value to this field then the new value is added to the sql exception error message but I run into problems a few fields later where there are more fields that have no values. If I add values to all fields then the query runs.


I dont want to start modifying the wordpress database. How can I handle empty fields in the database that are not null but have no value?


UPDATE: I think it is the date fields that are causing the problems. The default value for a date in the wordpress database is 0000-00-00 00:00:00. If I have a row in the database that has values for all fields then the dates like 0000-00-00 00:00:00 don't cause a problem. However if I have a row that has fields with no value and other date fields have values like 0000-00-00 00:00:00 then I get the above error. Alternatively if all date fields have proper date values then fields with no value don't cause any problems. So it appears that the problem is only caused when I have rows with 0000-00-00 00:00:00 as the value for date fields and I also have other fields with no value. All my date fields are marked with @Temporal(TemporalType.TIMESTAMP) like so:



@Temporal(TemporalType.TIMESTAMP)
@Column(name="post_modified")
private Date postModified;

Why is my AngularJS module never loaded?

I am an AngularJS newbie, and am having difficulty getting an AngularJS form to work correctly. Chrome Dev Tools tells me my module is not being loaded.


Below is my html; it is a div within a Wordpress template:



<div ng-app="contact" style="float: left;">
<form method="post" name="form" role="form" ng-controller="ContactFormController" ng-submit="form.$valid && sendMessage(input)" novalidate>
<p ng-show="success">Thanks for getting in touch!</p>
<p ng-show="error">Something wrong happened!, please try again.</p>
<legend>Contact</legend>
<fieldset>
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" ng-model="input.name" required>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" ng-model="input.email" required>
</div>
<div>
<label for="messsage">Message:</label>
<textarea id="messsage" name="message" ng-model="input.message" required></textarea>
</div>
<div>
<label for="honeypot">I promise I'm not a bot</label>
<input type="text" id="honeypot" name="honeypot" ng-model="input.honeyPot">
</div>
</fieldset>
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</div>


This is my angular code:



angular.module("contact", [])
.controller("ContactFormController", ['$scope', '$http', function($scope, $http) {
$scope.success = false;
$scope.error = false;

$scope.sendMessage = function( input ) {
$http({
method: 'POST',
url: 'http://ift.tt/1agAL6f',
data: input,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success( function(data) {
if ( data.success ) {
$scope.success = true;
} else {
$scope.error = true;
}
} );
}
}]);


The code is adapted from a tutorial. Can anyone help me out with what I am doing wrong?


Trying to display google doc files under parent folder in php for Wordpress

I am currently building a google drive plugin for wordpress that read a users google document files and displays them in the admin page and allows a user to convert them.



<div class="wrap">
<h2>Wordpress x Google Drive</h2>
<h3>How To Use:</h3>
<h4>Click on a Google Drive Document to open it in your Google Drive account to edit it.</h4>
<h4>Click on the <img src='DrivePluginIcons/convert.png'> icon to convert your document into a Wordpress draft.</h4>

<?php if( isset($message) ): ?>
<div class="updated"><p><?php echo $message; ?></p></div>
<?php elseif( isset($error) ): ?>
<div class="error"><p><strong><?php echo $error; ?></strong></p></div>
<?php endif; ?>
<?php if($settings === FALSE or empty($settings) ): ?>
<p>You have not set up any accounts yet.</p><a href="<?php echo $client- >createAuthUrl(); ?>">Add a new account</a></p>
<?php else: ?>
<h3>Logged In Drive Account:</h3>
<ol>
<li><?php echo $settings->email; ?><a href="<?php echo $url; ?>&remove=<? php echo urlencode( $settings->email);?>">(Remove)</a></li>
</ol>
<h3> Here are the documents on your drive:</h3>
<?php $files_list = $service->files->listFiles(array())->getItems(); ?>
<ol>

<?php foreach($files_list as $item):?>

<?php if ($item['mimeType']== "application/vnd.google-apps.folder" or $item['mimeType']=='application/vnd.google-apps.document'):
if (!empty($item['parents'])):
echo '<li><span><img src="' . $item['iconLink'] . '" alt="Icon"> <a href="' . $item['downloadUrl'] . '" target=_self"' . '">' . $item- >title . '</a>';
//echo "<form action=./cexdrive.php' method='get'>";
// echo '<input type="hidden" name="DocId" value=$item["id"]>';
//edited here /image/google_drive_icon.png
echo "<a href=".$url."&DocId=".$item['id']."> <img src='DrivePluginIcons/convert.png'> </a></span></li>";?>



<?php endif; ?>
<?php endif; ?>
<?php endforeach; ?>



</ol>
<br>


I am able to display the folders and the documents but I can't have the child documents underneath their parent folders.


Any help would be much appreciated.


Adding Extra Fields to the WordPress User Profile

I have a strange problem. I have added custom field to User Profile and used the_author_meta() function for display fields content. Yeasterday works everything great. But today it doesn't work.


Custom field is in User Profile. When I click update profile - the content of fields remains in place (so information should be saved). But on authors page where I have <?php the_author_meta( 'skills' ); ?> happens nothing.


I followed this tutorial when I was creating my own custom field: http://ift.tt/1reTxAH


And this one when I tried to find the error in my code: http://ift.tt/1xUQBy8


They both are similar. I worked with page templates since yesterday, so it maybe caused the problem. So I deleted everything what I've added since yesterday. But nothing changed.


Here is my code:



// CUSTOM FIELD IN USER ADMIN - SAVE
add_action( 'personal_options_update', 'my_save_extra_profile_fields' );
add_action( 'edit_user_profile_update', 'my_save_extra_profile_fields' );


function my_show_extra_profile_fields( $user ) { ?>

<h3>Skills - Färdigheter</h3>

<table class="form-table">

<tr>
<th><label for="skills">Skills</label></th>

<td>
<textarea type="text" name="skills" rows="4" cols="50" id="skills" class="regular-text"><?php echo esc_attr( get_the_author_meta( 'skills', $user->ID ) ); ?></textarea><br>
<span class="description">Please enter your skills.</span>
</td>
</tr>

</table>
<?php }

// CUSTOM FIELD IN USER ADMIN
add_action( 'show_user_profile', 'my_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'my_show_extra_profile_fields' );

function my_save_extra_profile_fields( $user_id ) {

if ( !current_user_can( 'edit_user', $user_id ) )
{return false;}

/* Copy and paste this line for additional fields. Make sure to change 'twitter' to the field ID. */
update_user_meta( $user_id, 'skills', $_POST['skills'] );
}

auto complete woocommerce order every x minutes?

All the plugins I can find for this auto complete the order on payment. What I want to do is wait 10minutes and call a script that then updates the status depending on whether something else has been completed...either via a cron or some other process. Is there a way to auto update the orders through a woocommerce extension?


Yoast SEO Breadcrumbs, Custom Post Type Not Working

I've set up a custom post type on my blog. On the individual posts, the Yoast SEO breadcrumbs don't seem to link to the parent post type. For example, you can see in this entry...


http://ift.tt/1bOuLlM


The home and parent links are styled correctly (orange), and the parent link is correct. So why is it not displaying as a link?


PHP - Send option to style.php using get_option

I am not sure how to formulate the question so I start saying that in my plugin folder I have 2 files:


1 - "index.php"



add_action( 'wp_enqueue_scripts', 'register_plugin_styles' );

function my_admin_setting() {
include('includes/my_admin.php');
include('css/wp-admin.php');
}

function custom_admin_actions() {
add_menu_page("Customise-Admin", "Custom-Admin", 1, "Custom_Admin", "my_admin_setting");
add_submenu_page('Custom_Admin', 'About', 'About', 1, 'info', "my_admin_info");

}

function my_admin_theme_style() {

wp_register_style('my-admin-theme', plugins_url('css/wp-admin.php', __FILE__));
wp_enqueue_style('my-admin-theme');
}


add_action('admin_enqueue_scripts', 'my_admin_theme_style');
add_action('login_enqueue_scripts', 'my_admin_theme_style');
add_action('admin_menu', 'custom_admin_actions');


add_option( 'my_adminbar_color', 'red' );


2 - wp_admin.php (style)



<?php header('Content-type: text/css');
?>

<?php
$blue = '#0e70d1';
$dkgray = '#333';
$dkgreen = '#008400';
?>
<?php $myplugin_color = get_option( 'my_adminbar_color' ); ?>

#wpadminbar {

background-color: <?php echo $myplugin_color;?> !important;
}


The problem here is that I am trying to pass an option to a php style. When I don't insert the "get_option" function my custom style is visible however, as soon as I pass the value the style is not rendered anymore.


I can see that the option is passed to the style file as the css code get printed in the plugin page, instead of running the code as CSS seems that it becomes formatted as normal text.


Could someone explain to me why this happens? And How could I pass the option to my style file?


Editing function in WordPress template - can edit just one variable?

I know pretty much no PHP other than what I've tinkered with on WordPress, but I'm trying to customize my theme to allow two authors to be listed on the front-end of posts.


I installed the Co-Authors Plus plugin (Here) And from the back end it's working well, both authors show up.


For it to show up on the front end, according to several support articles I need to adjust the theme functions to check if there are multiple authors, and if so display them.


I understand the basics and identified the theme file, but have no idea how to incorporate it because it seems that the theme isn't calling a function to display the authors, it's calling a variable in a much larger function (again, I don't know php, so if I'm wrong here, please let me know).


This is the bare bones code provided by Co-Authors Plus:



if ( function_exists( 'coauthors_posts_links' ) ) {
coauthors_posts_links();
} else {
the_author_posts_link();
}


But when I look in the functions file I don't see where that could go. I see this:



// mom_post_meta
function mom_posts_meta ($class = '', $display = null) {
$num_comments = get_comments_number(); // get_comments_number returns only a numeric value

if ( comments_open() ) {
if ( $num_comments == 0 ) {
$comments = __('No Comments', 'theme');
} elseif ( $num_comments > 1 ) {
$comments = $num_comments .' '. __(' Comments', 'theme');
} else {
$comments = __('1 Comment', 'theme');
}
$write_comments = '<a href="' . get_comments_link() .'">'. $comments.'</a>';
} else {
//$write_comments = __('Comments off', 'theme');
$write_comments = '';
}
$author_link = esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) );
if (class_exists('userpro_api')) {
global $userpro;
$author_link = $userpro->permalink(get_the_author_meta( 'ID' ));
}

$categories = get_the_category();
$separator = ', ';
$cats = '';
if($categories){
foreach($categories as $category) {
$cats.= '<a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s", 'theme' ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator;
}
}
$output = '<div class="mom-post-meta '.$class.'">';
$author = mom_option('post_meta-author') == 1 ? '<span class="author vcard">'.__('Posted by:', 'theme').' <span class="fn"><a href="'.$author_link.'">'.get_the_author().'</a></span></span>': '';
$date = mom_option('post_meta-date') == 1 ? '<span>'.__('On:', 'theme').' <time datetime="'.get_the_time('c').'" itemprop="datePublished" class="updated">'.get_mom_date_format().'</time></span>': '';
//$date = mom_option('post_meta-date') == 1 ? '<span>'.__('The last Update:', 'theme').' <time datetime="'.get_the_time('c').'" itemprop="datePublished" class="updated">'. get_post_modified_time(mom_option('date_format')).'</time></span>': '';
$cat = mom_option('post_meta-cat') == 1 ? '<span>'.__('In', 'theme').': '.trim($cats, $separator).'</span>': '';
$comments = mom_option('post_meta-comments') == 1 ? '<span>'.$write_comments.'</span>': '';
if ($display == 'date_comments') {
$output .= $date.$comments;
} else {
$output .= $author.$date.$cat.$comments;
}
if(function_exists('the_views')) {
$output .= '<span>'.__('Views:', 'theme').' '.the_views(false).'</span>';
}
$output .= get_mom_show_review_score();
$output .= '</div>';
echo $output;
}


I see that the $author line is what defines the output on the front end, but without an understanding of php I'm not sure how to include an if-else statement in there. I tried a few amateur edits, and just got errors. Any guidance of how to incorporate this while preserving the theme styling would be so very much appreciated.


I'm using Momizat's Goodnews theme.


Load another product in wc_get_template_part

If i use a custom meta name original_post_id to store the id of a related post in woocommerce how can i Load this particular post id in a specific template part?


I tried this but it simply does not work. Please help me correct this.





if ($original_post_id != '' && $original_post_id != 'deleted') {
$original_post = get_post($original_post_id);
$post_title = $original_post->post_title;
$post_content = $original_post->post_content;
wc_get_template_part($post_ID->$original_post_id, 'content', 'single-product' );
}



Combine Multiple MySQL Queries on the Same Table Into One

How do you make multiple queries on the same table, selecting different columns?


If it helps at all... All of the queries have a common column in the select part of the SQL statement. They all select the ID, then followed by something specific.


So every query needs the ID and either of the following: post_name, post_title, or post_excerpt.


Also if it helps to simplify things. I'm trying to search for broad matches and exact matches in these columns.


So in my example, I will be looking for: "floor finish", "floor", or "finish" in the following columns: post_name, post_title, and post_excerpt. All within the same table.


I've attempted to accomplish this with UNION.


Here are my queries:



Array
(
[broad] => Array
(
[floor] => Array
(
[slugs] => SELECT `ID`, `post_name` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_name` LIKE '%floor%'
[titles] => SELECT `ID`, `post_title` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_title` LIKE '%floor%'
[excerpts] => SELECT `ID`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_excerpt` LIKE '%floor%'
)

[finish] => Array
(
[slugs] => SELECT `ID`, `post_name` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_name` LIKE '%finish%'
[titles] => SELECT `ID`, `post_title` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_title` LIKE '%finish%'
[excerpts] => SELECT `ID`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_excerpt` LIKE '%finish%'
)

)

[exact] => Array
(
[slugs] => SELECT `ID`, `post_name` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_name` LIKE '%floor-finish%'
[titles] => SELECT `ID`, `post_title` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_title` LIKE '%floor finish%'
[excerpts] => SELECT `ID`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_excerpt` LIKE '%floor finish%'
)

[combined] => ( SELECT `ID`, `post_name` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_name` LIKE '%floor-finish%' ) UNION ( SELECT `ID`, `post_name` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_name` LIKE '%floor%' ) UNION ( SELECT `ID`, `post_name` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_name` LIKE '%finish%' ) UNION ( SELECT `ID`, `post_title` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_title` LIKE '%floor finish%' ) UNION ( SELECT `ID`, `post_title` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_title` LIKE '%floor%' ) UNION ( SELECT `ID`, `post_title` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_title` LIKE '%finish%' ) UNION ( SELECT `ID`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_excerpt` LIKE '%floor finish%' ) UNION ( SELECT `ID`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_excerpt` LIKE '%floor%' ) UNION ( SELECT `ID`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_excerpt` LIKE '%finish%' )
)


However, the above result is interesting. I appear to get all the correct results except the key of each result value (which is supposed to be the name of the column) always remains the same. It's always post_name even though the value assigned to it might be a post_title or post_excerpt.


So every result has an ID and post_name. Basically they keys are wrong but the values appear to be accurate.


I also tried something like this:



Array
(
[broad] => Array
(
[floor] => SELECT `ID`, `post_name`, `post_title`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND ( `post_name` LIKE '%floor%' OR `post_title` LIKE '%floor%' OR `post_excerpt` LIKE '%floor' )
[finish] => SELECT `ID`, `post_name`, `post_title`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND ( `post_name` LIKE '%finish%' OR `post_title` LIKE '%finish%' OR `post_excerpt` LIKE '%finish%' )
)

[exact] => SELECT `ID`, `post_name`, `post_title`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND ( `post_name` LIKE '%floor-finish%' OR `post_title` LIKE '%floor finish%' OR `post_excerpt` LIKE '%floor finish%' )
[combined] => SELECT `ID`, `post_name`, `post_title`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND ( `post_name` LIKE '%floor-finish%' OR `post_title` LIKE '%floor finish%' OR `post_excerpt` LIKE '%floor finish%' ) UNION (SELECT `ID`, `post_name`, `post_title`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND ( `post_name` LIKE '%floor%' OR `post_title` LIKE '%floor%' OR `post_excerpt` LIKE '%floor%' )) UNION (SELECT `ID`, `post_name`, `post_title`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND ( `post_name` LIKE '%finish%' OR `post_title` LIKE '%finish%' OR `post_excerpt` LIKE '%finish%' ))
)

)


This is more along the lines of what I'm trying to accomplish. I would like each result to have ID, post_excerpt, post_slug, and post_title. If there's no match, display they key with an empty value, or just completely don't even display the key.


The problem with the second attempt is that it's only requiring a match in one of the three desired columns. So if it matched in the post_excerpt and no where else, it will still pull values from the post_title and post_name. Thus making the results inaccurate.


I've read several what appear to be similar questions however most don't have real solid clear answers... OR ... The questions/answers are more geared to multiple queries on SEPARATE tables.


Any guidance or advice on combining multiple MySQL queries on the same table?


BY THE WAY... I am using the "combined" in both my examples as my final query to send to the database.


So just one more time... If there's no match in a column, display they key as null or just completely omit the key from the results entirely.


Echo variable from frontend in widget dashboard form

I create a WordPress widget and want to echo $widget_id variable inside



function form($instance);


to be visible inside WP dashboard. Variable exists http://ift.tt/1n7vqxu and is echoed in frontend using



function widget( $args, $instance )


without issues. Is that possible? (when I try to echo variable I get notice that variable is undefined, and it is not displayed)


remove \u2028 and \u2029 from post when updating it

I wan't to remove the invisible line and paragraph separator from the input when the user creates or edit a post. But it seems to be very inefficient. Is there other way to do this without that many DB operations?


I came with this solution adapting several examples on the internet. I added this code in functions.php:



// Add custom validation to clean the post fields.
// Originally used to remove \u2028 and \u2029 from the contents.
//----------------------------------------
function post_custom_validation ($post_id) {
//check post
if ( $post_id == null || empty($_POST) )
return;

if ( wp_is_post_revision( $post_id ) )
$post_id = wp_is_post_revision( $post_id );

global $post;
if ( empty( $post ) )
$post = get_post($post_id);

global $wpdb;

// remove \u2028 and \u2029 characters.
// From post table
$content = preg_replace('/[\p{Zp}\p{Zl}]+/u','',$post->post_content);
$title = preg_replace('/[\p{Zp}\p{Zl}]+/u','',$post->post_title);
$excerpt = preg_replace('/[\p{Zp}\p{Zl}]+/u','',$post->post_excerpt);

//update DB
$where = array( 'ID' => $post_id );
$wpdb->update( $wpdb->posts, array( 'post_content' => $content, 'post_title' => $title , 'post_excerpt' => $excerpt ), $where );

// From postmeta table
$lead = preg_replace('/[\p{Zp}\p{Zl}]+/u','',get_post_meta($post->ID, 'wm_lead', true));
$subheader = preg_replace('/[\p{Zp}\p{Zl}]+/u','',get_post_meta($post->ID, 'wm_subheader', true));
$footer = preg_replace('/[\p{Zp}\p{Zl}]+/u','',get_post_meta($post->ID, 'wm_footer', true));

//update DB
$where = array( 'ID' => $post_id , 'meta_key' => 'wm_lead');
$wpdb->update( $wpdb->wp_postmeta, array( 'meta_value' => $lead), $where );

$where = array( 'ID' => $post_id , 'meta_key' => 'wm_subheader');
$wpdb->update( $wpdb->wp_postmeta, array( 'meta_value' => $subheader), $where );

$where = array( 'ID' => $post_id , 'meta_key' => 'wm_footer');
$wpdb->update( $wpdb->wp_postmeta, array( 'meta_value' => $footer), $where );

}
add_action('save_post', 'post_custom_validation', 12 );

WooCommerce get order shipping address as seperate feilds

I am building a WooCommerce plugin which sends orders to a 3rd party api.


However i have found there not to be a way to get the individual fields/properties of the order shipping address since v2.3. The only function available is



get_formatted_shipping_address()



Which returns a string and it seems the function which returns a address array "get_shipping_address()" has been Deprecated in version 2.3.


Does anyone know a way to get the shipping address as an array for an order? i don't really want to resort to using a old version of WooCommerce...perhaps there is a hook, action or class override i can do to achieve this?


Any ideas welcome.


how to get wordpress post tags using fishpig in magento

I am unable to fetch post tags added from wordpress admin panel. I am using fishpig magento extension and everything is working perfectly.


I am fetching posts using the code


$posts = $this->getPosts();


and I need tags associated with each post.


Please help.


Wordpress custom post type meta box into URL

I am trying to make a custom post type meta box into a field that accepts URL, so the field would contain http://


Here is what I have.


Registering the custom post type:



function custom_post_type() {

// Set UI labels for Custom Post Type
$labels = array(
'name' => _x( 'Adverts', 'Post Type General Name', 'westanglia' ),
'singular_name' => _x( 'Advert', 'Post Type Singular Name', 'westanglia' ),
'menu_name' => __( 'Adverts', 'westa' ),
'parent_item_colon' => __( 'Parent Advert', 'westa' ),
'all_items' => __( 'All Adverts', 'westa' ),
'view_item' => __( 'View Advert', 'westa' ),
'add_new_item' => __( 'Add New Advert', 'westa' ),
'add_new' => __( 'Add New', 'westa' ),
'edit_item' => __( 'Edit Advert', 'westa' ),
'update_item' => __( 'Update Advert', 'westa' ),
'search_items' => __( 'Search Advert', 'westa' ),
'not_found' => __( 'Not Found', 'westa' ),
'not_found_in_trash' => __( 'Not found in Trash', 'westa' ),
);

// Set other options for the Adverts Custom Post Type

$args = array(
'label' => __( 'adverts', 'westa' ),
'description' => __( 'Front page scrolling adverts', 'westa' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'thumbnail' ),
'taxonomies' => array( 'ads' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-slides',
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
'register_meta_box_cb' => 'add_events_metaboxes'
);

// Registering the Adverts Custom Post Type
register_post_type( 'adverts', $args );

}

// Call the function
add_action( 'init', 'custom_post_type', 0 );


Then I'm adding 3 meta boxes, the last one being the URL one where I'd like to have it with htpp://



add_action( 'add_meta_boxes', 'add_events_metaboxes' );

// Add the Events Meta Boxes
function add_events_metaboxes() {
add_meta_box('wpt_advert_upper', 'Advert Upper Title', 'wpt_advert_upper', 'adverts', 'normal', 'high');
add_meta_box('wpt_advert_lower', 'Advert Lower Title', 'wpt_advert_lower', 'adverts', 'normal', 'high');
add_meta_box('wpt_advert_url', 'Advert Link URL', 'wpt_advert_url', 'adverts', 'normal', 'high');
}

// Add function for the Upper advert title field
function wpt_advert_upper() {
global $post;

// Noncename needed to verify where the data originated
echo '<input type="hidden" name="advertmeta_noncename" id="advertmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';

// Get the location data if its already been entered
$upperTitle = get_post_meta($post->ID, '_upperTitle', true);

// Echo out the field
echo '<input type="text" name="_upperTitle" value="' . $upperTitle . '" class="adH1" />';

}

// Add function for the Lower advert title field
function wpt_advert_lower() {
global $post;

// Noncename needed to verify where the data originated
echo '<input type="hidden" name="advertmeta_noncename" id="advertmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';

// Get the location data if its already been entered
$lowerTitle = get_post_meta($post->ID, '_lowerTitle', true);

// Echo out the field
echo '<input type="text" name="_lowerTitle" value="' . $lowerTitle . '" class="adH2" />';

}

function wpt_advert_url() {
global $post;

// Noncename needed to verify where the data originated
echo '<input type="hidden" name="advertmeta_noncename" id="advertmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';

// Get the location data if its already been entered
$advertUrl = get_post_meta($post->ID, '_advertUrl', true);

// Echo out the field
echo '<input type="text" name="_advertUrl" value="' . $advertUrl . '" class="adUrl" />';

}


And finally saving all the data added to the fields.



function wpt_save_advert_meta($post_id, $post) {

// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !wp_verify_nonce( $_POST['advertmeta_noncename'], plugin_basename(__FILE__) )) {
return $post->ID;
}

// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;

// OK, we're authenticated: we need to find and save the data
// We'll put it into an array to make it easier to loop though.

$advert_meta['_upperTitle'] = $_POST['_upperTitle'];
$advert_meta['_lowerTitle'] = $_POST['_lowerTitle'];
$advert_meta['_advertUrl'] = $_POST['_advertUrl'];

// Add values of $events_meta as custom fields

foreach ($advert_meta as $key => $value) { // Cycle through the $events_meta array!
if( $post->post_type == 'revision' ) return; // Don't store custom data twice
$value = implode(',', (array)$value); // If $value is an array, make it a CSV (unlikely)
if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
update_post_meta($post->ID, $key, $value);
} else { // If the custom field doesn't have a value
add_post_meta($post->ID, $key, $value);
}
if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
}

}

add_action('save_post', 'wpt_save_advert_meta', 1, 2); // save the custom fields


add_action('do_meta_boxes', 'change_image_box');
function change_image_box()
{
remove_meta_box( 'postimagediv', 'adverts', 'side' );
add_meta_box('postimagediv', __('Advert Image'), 'post_thumbnail_meta_box', 'adverts', 'normal', 'high');
}


Sorry it's so long, thought someone might need everything to best advise. Hope someone can help, never done a custom post type before :/


Geoff


When I add custom post type permalink rewrite, my regular post permalinks stop working. Can't get both to work at the same time

really struggling with this one, so any help would be much appreciated. My site has both regular post posts, and a custom post type called "articles."


I'm trying to get it to work so that my regular posts will use the /%category%/postname%/ permalink structure, (which I have set up in settings). This is working fine, until I add a custom rewrite for my article post type. I'd like articles to follow a /%issue%/%postname%/ structure. I can get this working great with the following:



add_filter( 'post_type_link', 'wpa_show_permalinks', 1, 2 );

function wpa_show_permalinks( $post_link, $id = 0 ){
$post = get_post($id);
if ( is_object( $post ) && $post->post_type == 'article' ){
$terms = wp_get_object_terms( $post->ID, 'issue_tax' );
if( $terms ){
return str_replace( '%issue%' , $terms[0]->slug , $post_link );
}
}
return $post_link;
}


where my post type is registered like this:



function article_post_type() {

$labels = array(
'name' => _x( 'Magazine Articles', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Magazine Article', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Magazine Articles', 'text_domain' ),
'name_admin_bar' => __( 'Magazine Articles', 'text_domain' ),
'parent_item_colon' => __( 'Parent Article:', 'text_domain' ),
'all_items' => __( 'All Articles', 'text_domain' ),
'add_new_item' => __( 'Add New Article', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'new_item' => __( 'New Article', 'text_domain' ),
'edit_item' => __( 'Edit Article', 'text_domain' ),
'update_item' => __( 'Update Article', 'text_domain' ),
'view_item' => __( 'View Article', 'text_domain' ),
'search_items' => __( 'Search Article', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
);
$rewrite = array(
'slug' => '%issue%',
'with_front' => false,
'pages' => true,
'feeds' => true,
);
$args = array(
'label' => __( 'article', 'text_domain' ),
'description' => __( 'Magazine Articles and Features', 'text_domain' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'trackbacks', 'revisions', 'custom-fields', 'page-attributes', ),
'taxonomies' => array( 'issue_tax', 'category', 'featured_media', 'tag' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-welcome-write-blog',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'rewrite' => $rewrite,
'capability_type' => 'page',
);
register_post_type( 'article', $args );

}


add_action( 'init', 'article_post_type', 0 );


I add that, reset permalink settings, and the article permalinks start working as indended - BUT - as soon as I get that working, my regular posts start displaying a 404.


Why am I unable to get both to work at the same time? Am I missing a piece somewhere?


Thanks for any advice!


-erin


Is it possible to use Facebook OG tag in an tag in the body of a page?

In a WordPress site I'm building, I'd ideally like to make the first post image the og:image for that page. I don't yet know what that image is when the header is called, however.


Is there a way to specify the og:image within the <img> tag itself, or somewhere else in the <body>?


Unlimited Colour Schemes in wp theme for Zurb Foundation with reduxframework

I am developing a WordPress theme with Zurb Foundation 5 framework and ReduxFramework as Theme Options panel. So, there is various way that i can implement Colour Schemes for WordPress theme.



  1. Using Different Style Sheets with different colour Schemes.

  2. Using css class and id

  3. +many more way........


But, I don't want to do this way. ReduxFramework can dynamically change css files and write class or id. And I want to do this way. So i can modify Foundation 5 css style sheet class and id from ReduxFramework Options panel dynamically. And After changing, it's must change Theme colour schemes.


Foundation 5 comes with 6 main colour options. I want to change those from ReduxFramework options panel.



  1. Primary Color

  2. Secondary Color

  3. Alert Color

  4. Success Color

  5. Body Font Color

  6. Header Font Color


Also is there any way that i can modify or change every options that comes with Foundation 5 CSS framework from Redux Framework.


Please go to this image link. {Open this image in a new tab for bigger view}



http://ift.tt/1OSWO2B


Now question is, How can i do those things ?


I know short of PHP, JS, HTML, CSS, MYSQL etc. If you describe everything in your answer, it's will be more helpful for me.


This Question is RE-POSTED from Unlimited Colour Schemes in wp theme for Foundation 5 - WordPress Development Stack Exchange: . One reputed user suggested me to ask this question here!


Hide/show radio buttons stop working on save

Here's my case: I'm developing a little widget, and I was looking for a way to hide/show different DIVs on selecting a set of radio buttons. I found the proper code and adjusted it to my needs. The only problem is that the hide/show feature stops working after clicking on save while configuring the widget :S


Here's the JS:



jQuery(document).ready(function($) {
$(document).ready(function() {
$('input[type="radio"]').click(function(){
if($(this).attr("value")=="link_to_image"){
$(".radio-option").hide();
$(".linked-image").show();
}
if($(this).attr("value")=="link_to_page"){
$(".radio-option").hide();
$(".linked-page").show();
}
});
});
});


And the HTML:



<p>
<label>Link:</label><br>
<label>
<input type="radio" name="link_to" value="link_to_image">
Link to image
</label><br>
<label>
<input type="radio" name="link_to" value="link_to_page">
Link to page
</label>
</p>
<div class="linked-image radio-option">
<label for="linked_image">Linked image:</label>
<p>
Content for linked_image DIV
</p>
</div>
<div class="linked-page radio-option">
<label for="linked_page">Linked page:</label>
<p>
Content for linked_page DIV
</p>
</div>


And the [JSFiddle] (http://ift.tt/1Doewqc)


Could you give me a hand with this, guys?


https to http redirect for two pages

My site (WordPress, in case it’s important) has ssl enabled with the following ‘rewrite’ rule in the htaccess file …



<IfModule mod_rewrite.c>
# RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ http://ift.tt/1droZBe [R,L]
</IfModule>


I have two pages I would ‘disable’ ssl for …



http://ift.tt/1GdzCrV
http://ift.tt/19zbqDy


The problem I have is that each of these pages has a highcharts chart on. For some reason, the highcharts rendering server that is used for exports doesn’t like the fact ssl is enabled on a page. This results in, horrible ‘this is insecure’ messages, and missing images when exporting a chart. Highcharts suggest here that a way to avoiding these issues is to, basically, build your own rendering engine … but I think this might be overkill.


So may I ask how I would remove ssl for the pages mentioned above. I know you like to see something I have tried but I have two problems.




  1. I think I may well, make some catastrophic mistake with this file and cause some real damage.




  2. I really don’t know where to start, as I seem to be understanding very little of what I read here on SO. For example, I did try the following based on this question.



    redirect 301 /firstpage.php http://ift.tt/1GdzCIk



May I ask SO for some pointers / help please ?


Outdated attachments loop in Wordpress

I have a client that has run into issues when they updated Wordpress. Basically a loop designed to pull in media attachments with a walker, e.g. pull the latest media attachment into the latest post, is no longer working.


Here's the loop:



<?php
$attachments = attachments_get_attachments();
$total_attachments = count($attachments);
?>
<?php if( $total_attachments > 0 ) : ?>
<?php for ($i=0; $i < $total_attachments; $i++) : ?>
<a href="<?=$attachments[$i]['location']?>" title="<?=$attachments[$i]['caption']?>" class="lightbox" rel="<?php the_ID(); ?>"><img src="<?=$attachments[$i]['location']?>" alt="<?=$attachments[$i]['caption']?>" class="attachment-thumbnail" /></a>

<?php endfor ?>
<?php endif ?>


I need to change this so that it works with the current version of Wordpress as of 2015.


Has anyone here encountered this before?


Many thanks, Jake


webmatrix wordpress rewrite rule in plugin

I wrote some simple php code to add a watermark on images. This code is in file wp-content/plugins/Watermark/Watermark.php. Then I instructed Wordpress to use that code to handle requests for uploaded resources. This is done in web.config, using the following tag:



<rewrite>
<rules>
<rule name="MyRule" stopProcessing="true">
<match url="^(.*)wp-content/uploads/(.*)$" ignoreCase="false" />
<action type="Rewrite" url="{R:1}wp-content/plugins/Watermark/Watermark.php?src=wp-content/uploads/{R:2}" appendQueryString="false" />
</rule>
</rules>
</rewrite>


I would like to achieve the same behavior in a plugin, without having to affect the web.config file.


Therefore, I cleaned the web.config file and created this plugin file:



<?php

/*
Plugin Name: Watermark
Plugin URI:
Description: Plugin to automatically add watermark on images
Author:
Version: 1.0
Author URI:
*/

function watermark_plugin_activate() {
watermark_plugin_rules();
flush_rewrite_rules();
}

function watermark_plugin_deactivate() {
flush_rewrite_rules();
}

function watermark_plugin_rules() {
add_rewrite_rule('^wp-content/uploads/(.*)', 'wp-content/plugins/Watermark/Watermark.php?src=wp-content/uploads/$matches[1]', 'top');
}

//register activation function
register_activation_hook(__FILE__, 'watermark_plugin_activate');
//register deactivation function
register_deactivation_hook(__FILE__, 'watermark_plugin_deactivate');
//add rewrite rules in case another plugin flushes rules
add_action('init', 'watermark_plugin_rules');
?>


This looks quite straightforward, but does NOT work!


I activated it from the Wordpress dashboard. I noticed that the plugin does not add any 'rewrite_rules' in the 'wp_options' table of the database. I tried to save the Permalink Settings, but I had no luck.


I also tried to replace the calls like flush_rewrite_rules and add_rewrite_rule to method of a



global $wp_rewrite;


class, but, of course, nothing changed.


I also attempted to hook 'generate_rewrite_rules', but, again, I was still missing something.


I'm using Wordpress 4.1.1


Any suggestions?


Thanks!


youtube iframe API- play one video at a time on ajax content

I'm working on a webpage. I'm using jQuery load (AJAX) function to dynamically load new content (articles) into the content div. In this div, multiple videos gets loaded. What I want is to play only one youtube video at a time. If one video is in playing state, and the user clicks on another video, the previous one should get paused. I have used onYouTubeIframeAPIReady() script code for the functionality. The code is working only for the videos that are loaded on first instance. As I scroll down the page, different videos are loaded on page (through AJAX call) and the code doesnot work on new content. Also shows error like:


TypeError: this.pauseVideo is not a function-- this.pauseVideo();


I have added the script code below:



var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
var num = firstScriptTag.length;
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

function onYouTubeIframeAPIReady() {

var $ = jQuery;
var players = [];
$("iframe").filter(function(){
return this.src.indexOf('http://ift.tt/wjgBk1') == 0}).each( function (k, v) {

var $urls_get=$(this).attr("src");
var $new_url=$urls_get+"&enablejsapi=1";
if (!this.id) {
this.id='embeddedvideoiframe' + k;
this.src=$new_url;
}

players.push(new YT.Player(this.id, {
events: {
'onStateChange': function(event) {
if (event.data == YT.PlayerState.PLAYING) {
$.each(players, function(k, v) {

if ('embeddedvideoiframe' + k != event.target.getIframe().id) {
this.pauseVideo();
}
});
}
}
}
}))
});
}


Please help. Thanks in advance.


Return array from foreach

I have a problem with this class in the administrative area of wordpress.


I would like to return the value of foreach, but unfortunately returns an empty variable!


If I use the print_r inside the foreach everything works!


Can you help me to understand where I wrong?


This is my code:



class MyClass{
function __construct(){
add_action( 'admin_init',array( $this, 'getPostType' ) );
}
function getPostType(){
$args = array(
'public' => true,
'_builtin' => false
);

$output = 'names';
$operator = 'and';

$post_types = get_post_types( $args, $output, $operator );
$types = array();

foreach($post_types as $postype){
$types[] = array(
'value' => $postype,
);
return $types;
}
}
}

$var = new MyClass();
foreach($var->getPostType() as $type){
echo $type;
}


Thanks in advance and sorry for my bad English!


Change



class MyClass{
function __construct(){
add_action( 'admin_init',array( $this, 'getPostType' ) );
}
function getPostType(){
$args = array(
'public' => true,
'_builtin' => false
);

$output = 'names';
$operator = 'and';

$post_types = get_post_types( $args, $output, $operator );
$types = array();

foreach($post_types as $postype){
$types[] = array(
'value' => $postype,
);
} return $types;
}
}

$var = new MyClass();
print_r($var->getPostType());


I get this: Array ( )


$post_types return a correct value.


Debug:



class MyClass{
function __construct(){
add_action( 'admin_init',array( $this, 'getPostType' ) );
}
function getPostType(){
$args = array(
'public' => true,
'_builtin' => false
);

$output = 'names';
$operator = 'and';

$post_types = get_post_types( $args, $output, $operator );
var_dump($post_types); // array(1) { ["book"]=> string(4) "book" }

$types = array();
foreach($post_types as $postype){
$types[] = array(
'value' => $postype,
);
var_dump($postype); // string(4) "book"
} return $types;
}
}

pdf is not showing properly wordpress flipbook

I use flipbook plugin for viewing pdfs beautifully, but have one problem pdf is working properly on some screens but there are screens that pdf is all gray but pages need to be in white also pages aren't loading properly.


Once I got that screen where pdf is not showing properly, in console log I saw that jquery isn't defined, then I added jquery to that page template and that error lost but still can't understand what's the problem that in my screen pdf is ok but in the other one not.


Why WordPress attachments LINK TO settings are not working?

Using this code below, I added some on-hover share icons for all images of the content. But, now these images are not getting any "Link To" setting from authors. I don't know what is the problem. Can anyone please look at this code below and guide me?



public function
Add_Pin_Button($content){
global $post;

// Get the post urls
$posturl = urlencode(get_permalink());

// Define a pattern to find all images inside the content
$pattern = '/<img(.*?)src="(.*?).(bmp|gif|jpeg|jpg|png)" (.*?) width="(.*?)" height="(.*?)" \/>/i';

// Replace the images with the following div and pin button
$button_div = '<div class="democlass">
<div class="secondclass">
<div class="thirdclass">
<a href="http://ift.tt/OxyLGR' . get_permalink().'&title='.get_the_title().'">
<img src="http://ift.tt/1DkDhoJ" width="45px" />
</a>
</div>

</div>

<div class="disdemo"><img$1src="$2.$3" $4 width="$5" height="$6" /></div> </div>
';

// Replace the images with a containing div with a pin button on the image
$content = preg_replace( $pattern, $button_div, $content );

return $content;
}


And how to add attachment link to all images of the content?


Wordpress metabox order data location

Wordpress makes it possible to drag & drop metaboxes. Where does wordpress save the data in which order the meta boxes must be rendered?


I know it fires a AJAX request to admin-ajax.php the moment you drop a metabox but I haven't got any further than that.


I could not find any documentation on it regarding the alteration or the functionality of the Javascript's Wordpress uses to do this.


I need to be able to retrieve the order of meta boxes per post. Each post can have it's own order of metaboxes.


Getting ACF field value in functions.php

I try to add a link to a file (uploaded in ACF field) in a Gravity form notification, in Wordpress.


So, as given in Gravity form and ACF documentation, I tried in my functions.php to add a hook to the gravity form notification mail function :



add_filter( 'gform_notification_1', 'my_gform_add_link', 10, 3 );
function my_gform_add_link( $notification, $form, $entry ) {
$postID = intval($entry[2]); //return the ID of the post as an int
$notification['message'] .= '\n <a href="'.get_field('spec-file', $postID).'">See this furniture specs</a>';

return $notification;
}


In the code above : $postID works as expected (it returns the expected post ID). The thing is : get_field('spec-file', $postID) (which is the recommended method to get a field value outside the loop - http://ift.tt/1xngHJm) returns empty.


Why ? Any idea ?


EDIT : The post ID wasn't correct, I fixed it and the code above works as expected.


Duplicator fails for more than one websites Wordpress

I am using Duplicator plugin to import my local website to server. On my web server, I have multiple sites of wordpress.


When I import my second website using Wordpress, I encounter problem with the first website, it starts redirecting towards the second one.


I am using different databases for the two websites in question. I am new in using duplicator am I missing a trick here.?


lundi 30 mars 2015

shuffle two different loops

I am working on two loops, each pulling 5 posts from their category.


The loops have a simple float:left, now I am trying to find a way to exchange locations from one loop to another...


Basic layout would be something like this


1 2 3 4 5 ( posts from category numbers )


A B C D E ( posts from category letters )


What I am trying to make would be something like


1 2 C 4 5


A B 3 D E


I can use position and move them by css3 hand but that would give too much additional work with responsive design.


Thanks


How to print custom post type category name in a post/page

I have been googling a lot of time to find a solution to this. I am using dream themes' nimble wordpress theme. I want to print the "dt_portfolio" custom post type's category name in th portfolio page. I have tried many ways to do that. But no use. Finally I am stuck with this and used this code :



$ctname = get_the_terms( get_the_ID(), 'dt_portfolio_category' );
print_r ($ctname);


This gave me an output as below:



Array ( [27] => stdClass Object ( [term_id] => 27 [name] => Magazine [slug] => magazine [term_group] => 0 [term_taxonomy_id] => 33 [taxonomy] => dt_portfolio_category [description] => [parent] => 0 [count] => 3 [object_id] => 8560 [filter] => raw ) )


I want to print the "slug" from this array. Please help me to do that.


The description is not prominent by default; however, some themes may show it

I'm using the latest wp version. When I go to edit a category to add descriptions specifically for each category, there is a note that says, "The description is not prominent by default, however some themes may show it."


My theme does not show it. What code do I need to make this visible/prominent? And where would I insert it?


certain section's permalinks are throwing a 404

We have migrated our WP site to new hosting and since then one section using custom content types manager is throwing a 404. The other ~4 work correctly.


I have cleared the plugin's cache and imported the .json file correctly.


When I change the permalinks to default from post name they load properly. Any idea on how to get this section working?


What is the global class name in this plugin php wordpress?

I am trying to remove_filter from this plugin, as wordpress refrence global $my_class; remove_filter( 'the_content', array($my_class, 'class_filter_function') ); In this code, there is 'add_filter('bp_core_fetch_avatar', array($this, 'set_buddypress_avatar'), 10, 1);' that I would like to remove_filter, the big issue here, what is $this? I cannot global $this, so what is the $my_class in the following code? I had tried global $BuddyPress_First_Letter_Avatar and global BuddyPress_First_Letter_Avata, it gave me error.





<?php
class BuddyPress_First_Letter_Avatar {

// Setup (these values always stay the same):
const BPFLA_IMAGES_PATH = 'images'; // avatars root directory
const BPFLA_GRAVATAR_URL = 'http://ift.tt/1iagL5P'; // default url for gravatar - we're using HTTPS to avoid annoying warnings

// Default configuration (this is the default configuration only for the first plugin usage):
const BPFLA_USE_PROFILE_AVATAR = TRUE; // TRUE: if user has his profile avatar, use it; FALSE: use custom avatars or Gravatars
const BPFLA_USE_GRAVATAR = TRUE; // TRUE: if user has Gravatar, use it; FALSE: use custom avatars or user's profile avatar
const BPFLA_AVATAR_SET = 'default'; // directory where avatars are stored
const BPFLA_LETTER_INDEX = 0; // 0: first letter; 1: second letter; -1: last letter, etc.
const BPFLA_IMAGES_FORMAT = 'png'; // file format of the avatars
const BPFLA_ROUND_AVATARS = FALSE; // TRUE: use rounded avatars; FALSE: dont use round avatars
const BPFLA_IMAGE_UNKNOWN = 'mystery'; // file name (without extension) of the avatar used for users with usernames beginning
// with symbol other than one from a-z range
// variables duplicating const values (will be changed in constructor after reading config from DB):
private $use_profile_avatar = self::BPFLA_USE_PROFILE_AVATAR;
private $use_gravatar = self::BPFLA_USE_GRAVATAR;
private $avatar_set = self::BPFLA_AVATAR_SET;
private $letter_index = self::BPFLA_LETTER_INDEX;
private $images_format = self::BPFLA_IMAGES_FORMAT;
private $round_avatars = self::BPFLA_ROUND_AVATARS;
private $image_unknown = self::BPFLA_IMAGE_UNKNOWN;



public function __construct(){

// add Settings link to plugins page:
add_filter('plugin_action_links_' . plugin_basename(__FILE__), array($this, 'bpfla_add_settings_link'));

// add stylesheets/scripts:
add_action('wp_enqueue_scripts', array($this, 'bpfla_add_scripts'));

// add filter to get_avatar:
add_filter('get_avatar', array($this, 'set_comment_avatar'), 10, 5); // this will only be used for anonymous WordPress comments

// add filter to bp_core_fetch_avatar:
add_filter('bp_core_fetch_avatar', array($this, 'set_buddypress_avatar'), 10, 1);

// get plugin configuration from database:
$options = get_option('bpfla_settings');
if (empty($options)){
// no records in DB, use default (const) values to save plugin config:
$settings = array(
'bpfla_use_profile_avatar' => self::BPFLA_USE_PROFILE_AVATAR,
'bpfla_use_gravatar' => self::BPFLA_USE_GRAVATAR,
'bpfla_avatar_set' => self::BPFLA_AVATAR_SET,
'bpfla_letter_index' => self::BPFLA_LETTER_INDEX,
'bpfla_file_format' => self::BPFLA_IMAGES_FORMAT,
'bpfla_round_avatars' => self::BPFLA_ROUND_AVATARS,
'bpfla_unknown_image' => self::BPFLA_IMAGE_UNKNOWN
);
add_option('bpfla_settings', $settings);
} else {
// there are records in DB for our plugin, let's assign them to our variables:
$this->use_profile_avatar = $options['bpfla_use_profile_avatar'];
$this->use_gravatar = $options['bpfla_use_gravatar'];
$this->avatar_set = $options['bpfla_avatar_set'];
$this->letter_index = $options['bpfla_letter_index'];
$this->images_format = $options['bpfla_file_format'];
$this->round_avatars = $options['bpfla_round_avatars'];
$this->image_unknown = $options['bpfla_unknown_image'];
}

}


?>public function set_buddypress_avatar($html_data = ''){

$html_doc = new DOMDocument();
$html_doc->loadHTML($html_data);
$image = $html_doc->getElementsByTagName('img');
foreach($image as $data) {
$original_image = $data->getAttribute('src');
$size = $data->getAttribute('width');
$alt = $data->getAttribute('alt');

if (stripos($alt, 'Profile picture of ') === 0){ // if our alt attribute has "profile picture of" in the beginning...
$name = str_replace('Profile picture of ', '', $alt);

} else if (stripos($alt, 'Profile photo of ') === 0){ // or profile photo of...
$name = str_replace('Profile photo of ', '', $alt);

} else { // if there is some problem - just assign alt to name
$name = $alt;

}
}

// something went wrong, just return what came in function argument:
if (empty($original_image) || empty($size) || empty($name) || empty($alt)){
return $html_data;
}

// if there is no gravatar URL it means that user has set his own profila avatar,
// so we're gonna see if we should be using it;
// if we should, just return the input data and leave the avatar as it was:
if ($this->use_profile_avatar == TRUE){
if (stripos($original_image, 'gravatar.com/avatar') === FALSE){
return $html_data;
}
}

// check whether Gravatar should be used at all:
if ($this->use_gravatar == TRUE){
// gravatar used as default option, now check whether user's gravatar is set:
if ($this->gravatar_exists_uri($original_image)){
// gravatar is set, return input data (nothing changes):
return $html_data;
} else {
// gravatar is not set, proceed to choose custom avatar:
$avatar_output = $this->choose_custom_avatar($name, $size, $alt,$gender);
}
} else {
// gravatar is not used as default option, only custom avatars will be used; proceed to choose custom avatar:
$avatar_output = $this->choose_custom_avatar($name, $size, $alt,$gender);
}

return $avatar_output;

}