Quantcast
Channel: WordPress › Support » Forum: Hacks - Recent Topics
Viewing all 8245 articles
Browse latest View live

robbiet63 on "Thickbox height/width on admin menu page sized to default- Can I overwrite size?"

$
0
0

My thickbox is working, displaying a photo from URL, but the height and width are not adjusted. (The code from my plugin is below.) The result is a thickbox that appears to be sized according to a WP default, (used by WP for instance when providing more information on plugins etc). Is there any way to overwrite this default?

Here's my code:

add_thickbox();
echo "<a href='".$photo_url."TB_iframe=true&width=600&height=550' class='thickbox'>Click to enlarge: <img src=".$photo_url." height='30'></a>";

In the above code I include height and width settings but they are not applied by WP. Instead the default is applied making the modal window too narrow and too high.

I have found a few other posts on this topic, such as "Custom height/width for thickbox in WP Backend" but it remains unclear whether the WP default settings can be overwritten, and if they can be overwritten whether this is true both for front-end and back-end. And if the proposed solution does work I need more details to figure out how to make it work in my plugin.

Better yet, is there another way of employing modal windows as lightboxes when making WP plugins - specifically for use in the admin menu? Ideally the size of the modal window would be set according to the size of the viewer's screen, instead of being a static pre-set.

Thx


m0nty on "How to make Displayname & nicknames Unique"

$
0
0

I've seen many requests for this, but no solutions. So a colleague and I spent the last few hours figuring this out.

It's quite dirty, but does the job, just place it in your theme functions.php on a single site, or in a functions.php file inside your mu-plugins folder on a multisite.

The script will also scan existing users (if your site already has many) and any non unique display names will be updated and replaced with username.

I know this isn't totally ideal, but any suggestions for dealing with existing users or improvements are always welcome.

// Make nickname & display_name unique
// and automatically change non unique nicks & display name to username
// in case you already have existing users
// by Ashok & Vaughan Montgomery
/*
 * adding action when user profile is updated
 */
add_action('personal_options_update', 'check_display_name');
add_action('edit_user_profile_update', 'check_display_name');
function check_display_name($user_id) {
        global $wpdb;
    // Getting user data and user meta data
        $err['display'] = $wpdb->get_var($wpdb->prepare("SELECT COUNT(ID) FROM $wpdb->users WHERE display_name = %s AND ID <> %d", $_POST['display_name'], $_POST['user_id']));
    $err['nick'] = $wpdb->get_var($wpdb->prepare("SELECT COUNT(ID) FROM $wpdb->users as users, $wpdb->usermeta as meta WHERE users.ID = meta.user_id AND meta.meta_key = 'nickname' AND meta.meta_value = %s AND users.ID <> %d", $_POST['nickname'], $_POST['user_id']));
    foreach($err as $key => $e) {
        // If display name or nickname already exists
        if($e >= 1) {
            $err[$key] = $_POST['username'];
            // Adding filter to corresponding error
            add_filter('user_profile_update_errors', "check_{$key}_field", 10, 3);
        }
    }
}
/*
 * Filter function for display name error
 */
function check_display_field($errors, $update, $user) {
        $errors->add('display_name_error',__('<span id="IL_AD9" class="IL_AD">Sorry</span>, Display Name is already in use. It needs to be unique.'));
        return false;
}
/*
 * Filter function for nickname error
 */
function check_nick_field($errors, $update, $user) {
        $errors->add('display_nick_error',__('Sorry, Nickname is already in use. It needs to be unique.'));
        return false;
}
/*
 * Check for duplicate display name and nickname and <span id="IL_AD2" class="IL_AD">replace with</span> username
 */
function display_name_and_nickname_duplicate_check() {
    global $wpdb;
    $query = $wpdb->get_results("SELECT * FROM $wpdb->users");
    $query2 = $wpdb->get_results("SELECT * FROM $wpdb->users as users, $wpdb->usermeta as meta WHERE users.ID = meta.user_id AND meta.meta_key = 'nickname'");
    $c = count($query);
    for($i = 0; $i < $c; $i++) {
        for($j = $i+1; $j < $c; $j++) {
            if($query[$i]->display_name == $query[$j]->display_name){
                wp_update_user(
                        array(
                              'ID' => $query[$i]->ID,
                              'display_name' => $query[$i]->user_login
                        )
                    );
            }
            if($query2[$i]->meta_value == $query2[$j]->meta_value){
                update_user_meta($query2[$i]->ID, 'nickname', $query2[$i]->user_login, $prev_value);
            }
        }
    }
}
// Call the function
display_name_and_nickname_duplicate_check();

/*
 * Calling the display_name_and_nickname_duplicate_check() again when a new user is registered
 */
add_action( 'user_register', 'check_nickname', 10, 1 );
function check_nickname() {
    display_name_and_nickname_duplicate_check();
}

victor_jonsson on "Best way to create a css file dynamically"

$
0
0

Hi there!

What would be the best way to dynamically generate a stylesheet in a theme? I can think of three different solutions:

1) Having a separate file in theme and assume where the file wp-load.php is located and include it like '/../../wp-load.php'.

2) In the file functions.php check if a certain variable is set and if so generate the stylesheet and terminate the script.

3) Register an ajax function and link to the url of the ajax function (not sure if wordpress checks if AJAX-requests is sent with correct request headers).

Is there any other way to accomplish this? I know that the first solution is most straight forward but I consider it to be something of a hack, especially if it exists a "correct" way of doing it.

/ vic

jaruzelskee on "Saving email-adress to other DB than WP while registering"

$
0
0

I'm trying to save an user email to separate DB while registering and I'm modifying wp-includes/user.php file but I can't make it work.
I will be grateful for your help.

line 1394:

<?php
if ( $update ) {
		$wpdb->update( $wpdb->users, $data, compact( 'ID' ) );
		$user_id = (int) $ID;
	} else {
		$wpdb->insert( $wpdb->users, $data + compact( 'user_login' ) );
		$user_id = (int) $wpdb->insert_id;

	mysql_close($connect);

		$hostname = 'xxx.xxx.xxx';
		$dbname   = 'xxx_xxx';
		$username = 'xxx';
		$password = 'xxx';             

		$new_connect = mysql_connect($hostname, $username, $password) or DIE('Connection to host is failed, perhaps the service is down!');
		mysql_select_db($dbname) or DIE('Database name is not available!');
		mysql_query("SET NAMES 'utf8'");

		$result = mysql_query("SELECT * FROM user WHERE user_email = '$user_email'");
		$num_rows = mysql_num_rows($result);

		if ($num_rows = 0)
		{
		 $qry = "INSERT INTO user (user_email,user_registered) VALUES ('$user_email','$date')";
		}
		mysql_close($new_connect);

	$hostname = 'xxx.xxx.xxx';
	$dbname   = 'xxx_xxx';
	$username = 'xxx';
	$password = 'xxx';              

	$connect = mysql_connect($hostname, $username, $password) or DIE('Connection to host is failed, perhaps the service is down!');
	mysql_select_db($dbname) or DIE('Database name is not available!');
	mysql_query("SET NAMES 'utf8'");

	}

?>

damian.smith on "calling featured images from child pages"

$
0
0

Hey guys I have this function below, that calls the information of child pages into the parent page. All works perfectly except the featured images act strangely.

The featured imahes should sit inside the featured-img div but for some reason they all sit outside of the ul completely, like so:

<img...../>
<ul class="childrens">
<li>.... etc etc</li>
</ul>

Any ideas?? :/

function get_children() {
	global $post;

	$args = array(
		'post_parent' => $post->ID,
		'post_type' => 'page'
	);
	$subpages = new WP_query($args);

	// create output
	if ($subpages->have_posts()) :
		$output = '<ul class="childrens">';
		while ($subpages->have_posts()) : $subpages->the_post();
			$output .= '<li>
						<div class="featured-img">'.the_post_thumbnail().'</div>
						<div class="childrens-content">
						<h3><a href="'.get_permalink().'">'.get_the_title().'</a></h3>
						<p>'.get_the_excerpt().'<br />
						</div>
						<a class="read-more" href="'.get_permalink().'">Read More > ></a></p>
						</li>';
		endwhile;
		$output .= '</ul>';
	else :
		$output = '<p>No subpages found.</p>';
	endif;

	// reset the query
	wp_reset_postdata();

	// return something
	return $output;
}

somtam on "get the attachment only if the post status of the parent is published"

$
0
0

Hello everybody.

I have to made an attachment archive by custom taxonomy.
I don't know why the page of the term, like mysite.com/custom_taxonomy/attachment_term, doesn't work.

Anyway I decide to write a custom query by myself and run it inside a template page.
It works, but I have a problem.
When I get the attachments, I get all the of them, even if the parent is not published. This cause a 404 if someone clicks on them. Instead, if the post_parent is 0, with a click we arrive to the attachment page mysite.com/?attachment_id=x. Moreover if the attachment is regularly inside a post, it goes to mysite.com/post_name/attachment.

So how can I check all of these and get the attachments with parent 0 or the parent Publish?

Here's the query right now

$sql = "
	SELECT p.*
	FROM $wpdb->posts p
	LEFT JOIN $wpdb->term_relationships r
		ON r.object_id = p.ID
	LEFT JOIN $wpdb->term_taxonomy t
		ON t.term_taxonomy_id = r.term_taxonomy_id
	LEFT JOIN $wpdb->terms te
		ON te.term_id = t.term_id
	WHERE te.slug = 'OneOfmMyTerms'
";

thanks!!!

zen047 on "how i can create page - post of user login (online now)"

$
0
0

hello ;
i need help plz
i want to create a page containing the addresses and links of post for the user online now(is login), by Category
For example
page : post user online
Category 1
xxxxx - xxxxxx
xxxxxx xxxxxx

Category 2
yyyyy yyyyyyy
yyyyy yyyyyyy

(xxxxx,yyyyy is the post of user online now)

saracup on "My Custom Permalink Variable Plugin"

$
0
0

I developed a small plugin to be able to add a custom taxonomy as a string to a post. I've included the variable in a custom permalink string. This string is used by Apache to determine if external login is required. This part is working fine -- the permalink is being changed, redirecting to Apache, and then causing the login to be prompted (it's our institution's flavor of PubCookie). I've tested other custom permalink structures, without variables, just to see that I had Permalinks set up correctly (mod_rewrite, etc.). So, in general, custom permalinks are functioning without 404 errors.

However, once I put that particular string into the permalink, I am getting a 404. Here is the code for the plugin.

//REGISTER THE TAXONOMY
add_action('init','uvasom_restriction_init');
function uvasom_restriction_init() {
    if (!taxonomy_exists('uvasomrestriction')) {
        register_taxonomy( 'uvasomrestriction', 'post',
		   array(   'hierarchical' => TRUE, 'label' => __('UVA SOM Restriction'),
				'public' => TRUE, 'show_ui' => TRUE,
				'query_var' => 'uvasomrestriction',
				'rewrite' => true,
				'capabilities'=>array(
					'manage_terms' => 'manage_options',//or some other capability your clients don't have
					'edit_terms' => 'manage_options',
					'delete_terms' => 'manage_options',
					'assign_terms' =>'edit_posts')
				)
				);

	}

//ADD DEFAULT TERMS IF THEY ARE NOT THERE
$parent_term = term_exists( 'uvasomrestriction', 'uvasomrestriction' ); // array is returned if taxonomy is given
$parent_term_id = $parent_term['term_id']; // get numeric term id
wp_insert_term(
  'UVA Only', // the term
  'uvasomrestriction', // the taxonomy
  array(
    'description'=> 'Require UVA Netbadge credentials to read.',
    'slug' => 'privatenbauth-uva-only',
    'parent'=> $parent_term_id
  )
);
}

//INSERT THE PROPER TERM INTO THE CUSTOM PERMALINK
add_filter('post_link', 'uvasom_restriction_permalink', 10, 3);
add_filter('post_type_link', 'uvasom_restriction_permalink', 10, 3);

function uvasom_restriction_permalink($permalink, $post_id, $leavename) {
    if (strpos($permalink, '%uvasomrestriction%') === FALSE) return $permalink;

        // Get post
        $post = get_post($post_id);
        if (!$post) return $permalink;

        // Get taxonomy terms
        $terms = wp_get_object_terms($post->ID, 'uvasomrestriction');
        if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) $taxonomy_slug = $terms[0]->slug;
        else $taxonomy_slug = 'unrestricted';

    return str_replace('%uvasomrestriction%', $taxonomy_slug, $permalink);
}

Debug is showing nothing. Here is the URL. Click on any post on the home page and you will get a 404:

http://news.med.virginia.edu/deansoffice/

I'm sure it's something obvious to a more trained eye. Please let me know, and thanks.


linnieA on "Add class to first and last div"

$
0
0

Hello!

Unfortunately, my php skills aren't great, so I could really use some help on the following. I'm displaying related posts in single.php. Now I'd like to add the class .first to the first post en .last to the last post.

Here's the code I'm using:

<div id="related">
	<?php $orig_post = $post;
	global $post;
	$tags = wp_get_post_tags($post->ID);
	if ($tags) {
	$tag_ids = array();
	foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
	$args=array(
	'tag__in' => $tag_ids,
	'post__not_in' => array($post->ID),
	'posts_per_page'=>5, // Number of related posts that will be shown.
	'caller_get_posts'=>1
	);
	$my_query = new wp_query( $args );
	if( $my_query->have_posts() ) {
	echo '<div id="relatedposts"><h3>You might also like...</h3><div>';
	while( $my_query->have_posts() ) {
	$my_query->the_post(); ?>
	<div class="fourcol"><div class="relatedthumb"><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_post_thumbnail( 'related' ); ?></a></div>
	<div class="relatedcontent">
	<h2><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>
	</div>
	</div>
	<? }
	echo '</div></div>';
	}
	}
	$post = $orig_post;
	wp_reset_query(); ?>
	</div>

One234 on "Adding meta box with action button"

$
0
0

Hey guys,
i want to create a small newsletter plugin, which can send the mails out of the edit post page. I will add a metabox, and dont know how to create a button in this metabox which will start my action. I think its easy but i couldnt find the right example.

TIA

LeoAltair on "remove_action not removing action (on wp_widgets_init)"

$
0
0

Hi !
I'm trying to get rid of the default Wordpress widgets, as I do not use them. Since they are launched by
add_action('init', 'wp_widgets_init', 1);
I tried
remove_action('init', 'wp_widgets_init', 1);

I also use

add_action( 'init', 'other_widgets_init') ;
function other_widgets_init() {
	if ( !is_blog_installed() )
		return;
	do_action('widgets_init');
}

to launch all the other widgets, since this call is in wp_widgets_init.

But remove_action does not do its job ! The default widget are still loaded...

Everythings works fine if I comment the add_action in the core file, but I don't want to do it this way, I want to do the thing proper.

Why doesn't the remove_action do its job of removing the call to wp_widgets_init like the Codex says it should ?!

sora4222 on "Pretty Urls and get_query_var being used"

$
0
0

I am attempting to use get_query_var to perform pagination however this is not on a static homepage its on a news page that is certainly not the main page.

Originally I thought it was my syntax with the query function, however my issue is that whether I use the standard query links or the pretty URL link setting, the get_query_var is not returning a page or paged value at all.

I did however try $_GET and that worked with the normal query string, but understandably this did not work. Any help would be appreciated.

McGuive7 on "How to get URL of admin menu item?"

$
0
0

Hi there,

Is there a simple way to get the URL of admin menu items? I've grabbed the gobal $menu and $submenu arrays which contain quite a bit of info about each menu item, but digging into menu_header.php, it appears that there's quite a bit of conditional logic going on behind the scenes to generate basic urls (e.g. /wp-admin/options-general.php?page=easy-custom-templates, or /wp-admin/admin.php?page=wpcf-import-export). Some of the logic, for example, looks like this:

if ( ! empty( $menu_hook ) || ( ( 'index.php' != $sub_item[2] ) && file_exists( WP_PLUGIN_DIR . "/$sub_file" ) && ! file_exists( ABSPATH . "/wp-admin/$sub_file" ) ) ) {
	// If admin.php is the current page or if the parent exists as a file in the plugins or admin dir
	if ( ( ! $admin_is_parent && file_exists( WP_PLUGIN_DIR . "/$menu_file" ) && ! is_dir( WP_PLUGIN_DIR . "/{$item[2]}" ) ) || file_exists( $menu_file ) )
		$sub_item_url = add_query_arg( array( 'page' => $sub_item[2] ), $item[2] );
	else
		$sub_item_url = add_query_arg( array( 'page' => $sub_item[2] ), 'admin.php' );

	$sub_item_url = esc_url( $sub_item_url );
	echo "<li$class><a href='$sub_item_url'$class>$title</a></li>";
} else {
	echo "<li$class><a href='{$sub_item[2]}'$class>$title</a></li>";
}

Does anyone know of a simple, reliable way to get admin menu item URLs for use in plugins? Thanks!

SchwarzwaldFalke on "add_rewrite_rule if permalinks are disabled"

$
0
0

Hi,

I'm working on a simple wordpress plugin for my university, which uses some rewrite rules. Currently I try to rewrite all requests to wp-login.php to a post with a custom post type. This is absolutly easy with directly adding the rewrite rule to the .htaccess file, but I have some problems with the Rewrite API of WordPress.

So what I'm currently doing is the following:

In the constructor of my plugin:

add_action( 'init', array( 'Fum_Redirect', 'redirect_wp_login' ) );

The called function:

$page = get_page_by_title( 'Title', OBJECT, 'fum_post' );
$ID   = $page->ID;
add_rewrite_rule( 'wp-login\.php.*$', '?p=' . $ID, 'top' );
flush_rewrite_rules();

I know that it's bad practice to call flush_rewrite_rules(); on each reload, it's just for testing.

First problem:
If I disable permalinks (set to "Standard"), WordPress clears the complete .htaccess file. It does NOT add my rewrite_rule, so wp_login is not redirected.

Second problem:
WordPress seems to ignore the flush_rewrite_rules() in my function, it does not change the .htaccess file if I change the parameters of my add_rewrite_rule call.
But if I change the permastructure in the dashboard, it adds my new rewrite rule.

Maybe I missunderstand something in the Rewrite API, hopefully you can tell me what's the problem!

Best Regards,
Chris

Laura Fischer on "Use radio value from $wp_customize->add_control in function"

$
0
0
function wf_customize_register( $wp_customize ) {

    // Colour Schemes
    $wp_customize->add_section('colour_scheme', array(
        'title'    => __('Colour Scheme', 'wf'),
        'priority' => 200,
    ));

    $wp_customize->add_setting('wf_theme_options[colour_scheme]', array(
        'default'        => 'jungle',
        'type'           => 'option',
        'capability'     => 'edit_theme_options',
    ));

    $wp_customize->add_control('colour_scheme', array(
        'label'      => __('Colour Scheme', 'wf'),
        'section'    => 'colour_scheme',
        'settings'   => 'wf_theme_options[colour_scheme]',
        'type'       => 'radio',
        'choices'    => array(
            'jungle' => 'Jungle',
            'sea' => 'Sea',
            'mountain' => 'Mountain',
            'woods' => 'Woods',
            'desert' => 'Desert',
        ),
    ));
}
add_action( 'customize_register', 'wf_customize_register' );

function wf_customize_css()
{
	$mods = get_theme_mods();
	var_dump($mods);

	$skin = get_theme_mod('wf_theme_options');
    ?>
    	<link rel="stylesheet" href="<?php bloginfo('template_directory') ?>/css/<?php echo $skin ?>.css" />
    <?php
}
add_action( 'wp_head', 'wf_customize_css');

I'm using customize_register( $wp_customize ) to add a skin/colour scheme option to my theme but don't know how to grab the value from the radio button in the menu.

When I do a var_dump, the output contains: ["wonderfort_theme_options"]=> array(1) { ["colour_scheme"]=> string(3) "sea" }

How do I grab the 'sea' to use where $skin is? Currently it echos 'Array'.

Thanks.


Jonas Lundman on "Manipulating register_post_status() setup on pageload"

$
0
0

When register custom post status in my functions.php. Can I provide diffrent args for diffrent user views? Will this type of manipulating totally be "out of how to?". Ive been searching for an answer many months, but cant se anyone doing this, so I finally have to post it here.

Here is my code:

function my_custom_post_status(){

if(current_user_can( 'update_core')) $p = true;
    else $p = false;
register_post_status('archive', array(
    'label'                     => _x( 'Archive', 'post' ),
    'public'                    => $p,
    'exclude_from_search'       => true,
    'show_in_admin_all_list'    => true,
    'show_in_admin_status_list' => true,
    'label_count'               => _n_noop( 'Archive <span class="count">(%s)</span>', 'Archive <span class="count">(%s)</span>' )
));

}
add_action( 'init', 'my_custom_post_status' );

This actually is working, but do I mess with the database or are this kind of register just a "page to page load" variables? ( I mean, "register", is it just instructions how to handle the "already stored" and "to be stored" in the database? )

Don ask why Im doing this (!), just if I can do it -or if Im making a mess...

Thanks to all of you who contributes on this forum !

hanbr on "Modify post meta before inserting new post"

$
0
0

Hi!

I'm trying to modify the post meta before inserting a new post. I can't finda anyway to do this. The closest I get is the wp_insert_post_data filter, but there I think I can only modify the $data array and not the $postarr array where the post meta are located:

add_filter( 'wp_insert_post_data' , 'modify_post_meta_before_insert' , '99', 2 );
function modify_post_meta_before_insert( $data , $postarr )
{
if($data['post_type'] == 'special_post_type') {
// Here I would like to modify $postarr
// $postarr['post_meta_type'] = ...
}
return $data; // Here I can only return $data and not $postarr ?
}

Eliot Akira on "Object-oriented programming advice: Custom Content Shortcode"

$
0
0

Hello all - I'm pretty familiar with PHP for building templates and plugins, but only recently started studying OOP and using classes.

I'm writing a plugin with two shortcodes, [loop] and [content]. The first does queries, and the second displays fields. For a list of the 3 most recent post titles:

[loop type="post" count="3"]
    <ul>
       <li>[content field="title]</li>
    </ul>
[/loop]

The [content] shortcode can be used stand-alone or inside a loop. The loop passes each post ID found to the content fields, according to the given query.

I would like to update the plugin to use classes for these functions. I have a plan for add-on features, for example: better meta query (relations, compare, range and series of fields, taxonomies, tags); calculate fields and formulae (like a simple spread-sheet); better query of date/time fields for events; etc.

Currently, I'm using a global variable (an array) to store the loop state, the post ID list from the query, if the loop is in attachments or gallery images, etc.

My question is, how would you recommend building these two functions into class objects? I guess I have to think about what data needs to be passed to/from, which should stay private and which public. Would a Singleton pattern be useful in this context? Any suggestions would be welcome.

dcumberland on "Adding featured image to custom RSS feed"

$
0
0

I'm working on setting up a custom RSS feed so that I can offer a nice & clean weekly summery of my blog to my readers via Mailchimp.

I followed these instructions by Yoast to set up a custom feed. My feed is working great and looks great in Mailchimp, BUT I would like to add the featured images to it.

Here's my custom feed.

I would prefer not to alter the way other RSS feeds look on my site, as I have some readers using them and I use them for other Mailchimp purposes. Is there a simple way to do this?

Thanks in advance!

ps- I don't know a ton of code, but I know enough to get myself this far ;-)

Rahul Chowdhury on "Create a Page like FaceMash using Wordpress"

$
0
0

Hi,

I want to create a page which is similar to the site FaceMash set up by Mark Zuckerberg. There are plugins for it, but I want to do this without any plugin.

The idea is showing random images on a page, and whenever any user clicks on any photo, the photo gets a +1 point and reloads the page to show more random pics.

I have got a Random pic plugin, which shows random pics, but I am not able to add points whenever a user clicks on any photo.

Help is appreciated. :-)

Viewing all 8245 articles
Browse latest View live




Latest Images