INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Infinite Scroll on Self-hosted Wordpress Trying to move a Wordpress website from Wordpress.com to a self-hosted version. < The site automatically had infinite scroll on Wordpress.com and I'm trying to implement that on the self-hosted version. Is that feature part of the JetPack plugin? If not does WordPress offer a way to simulate that functionality on self-hosted?
Jetpack does provide the infinite scroll, but unlike other functionality it may require you to modify your theme to support it. Here's a link to the documentation.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin jetpack" }
How to include admin-ajax when loading external javascript I'm creating a plugin that has some external Javascript and some AJAX calls ... but I don't know the best way to make reference to the `admin-ajax.php` file since the path requires some input from PHP (paths and such). Should I declare a global javascript variable? What is the best way to accomplish this?
What you need to do is register and/or enqueue your script and then use `wp_localize_script` to include a Javascript variable on your page. The Codex page has this example: wp_enqueue_script( 'some_handle' ); $translation_array = array( 'some_string' => __( 'Some string to translate' ), 'a_value' => '10' ); wp_localize_script( 'some_handle', 'object_name', $translation_array ); You can then access the variable with, to quote the same Codex page: <script> alert(object_name.some_string); // alerts 'Some string to translate' </script>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "plugins, ajax, javascript" }
remove_filter( 'the_content', 'wpautop' ); only for certain post types I want to try and remove automatic `<p>` tag and `<br>` tag addition for my custom post type. It looks like remove_filter( 'the_content', 'wpautop' ); will do this, but how would I make the change only for my chosen post type I've tried writing a function for this, but it doesn't seem to work: function remove_tags() { global $post_type; if ( 'client' == $post_type ) { remove_filter( 'the_content', 'wpautop' ); } }
remove_filter('the_content','wpautop'); //decide when you want to apply the auto paragraph add_filter('the_content','my_custom_formatting'); function my_custom_formatting($content){ if(get_post_type()=='my_custom_post') //if it does not work, you may want to pass the current post object to get_post_type return $content;//no autop else return wpautop($content); } found this code on stackoverflow - looks to do the trick.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 6, "tags": "filters" }
how to force caching of wordpress admin Because of using slow connection these days, I would like to force WordPress's Admin section to be cached in browser (FF,IE) so that it it takes less time to load admin pages (because in fact, most of items never change.). Is there any way to do that?
your problem is not with the admin pages themself, they are simply not big enough to be hugely impacted by slow connection, but with JS and CSS files. You can set an expiry date for them which will signal to the browser it may cache them until that time. To cache them for a week in your .htaccess file add (idea taken from askapache) # 1 WEEK <FilesMatch "\.(jpg|jpeg|png|gif|swf|js|css)$"> Header set Cache-Control "max-age=604800, public" </FilesMatch> The max age parameter specifies the time in seconds after which the url have to be fetched again. If this is not good enough, maybe because your browser cache is full with other files which you access more frequently, then you should install a caching proxy on your PC, configure it to always cache JS and CSS from your site, and configure the browser to use the proxy.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "wp admin, cache" }
Running WP Cron on specific local time The scenario is to run insert_post function every midnight (00:00) of local time. Must run daily on weekday. function add_daily_task(){ if((date('l', time()) != 'Saturday') || (date('l', time()) != 'Sunday')){ // insert post } } if(!wp_next_scheduled( 'add_daily_task_schedule')){ wp_schedule_event(time(), 'daily', 'add_daily_task_schedule'); // how should change time() to meet my local schedule? } add_action('add_daily_task_schedule', 'add_daily_task');
Not sure what is the question, but the use of `time()` is wrong as it will give you at best the local time of the server and not the local time of the site which takes into consideration the time zone configuration of WordPress. The function that you should use is current_time.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 4, "tags": "date time, wp insert post, cron, localization" }
wp_insert_post() Callback? After I added a post by wp_insert_post(); Any callback after I added ? I need permalink of added post. I have idea only search by title and post-type (I use custom post-type in my case), But any better function ?
$post_id = wp_insert_post( $arg ); #returns post ID $permalink = get_permalink( $post_id ); #returns the permalink Codex: <
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "wp insert post, callbacks" }
Categorize wordpress tags I have problem about categorizing wordpress TAG, in my case for language. for example: **postA** : englishtag1,englishtag2,englishtag3, chinesetag1,chinesetag2, **postB** : englishtag2,englishtag5,englishtag4, chinesetag1,chinesetag3, i want to show tag cloud based on the "language": **english tag cloud** : englishtag1,englishtag2,englishtag4,englishtag5 **Chinese tag cloud** : chinesetag1,chinesetag3,chinesetag2,chinesetag4 etc.. is it possible? how to achieve this? Thank you
finally found plugin to achieve this using plugins below 1. < 2. < << complex one hope help someone htat need to groups the tags, catgeory or taxonomy
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "taxonomy, tags" }
Disable all scripts and styles from NextGEN Gallery? I use nextgen gallery in a multisite. How can I disable all scripts and styles? These thing are loaded in the code of my site: <link rel='stylesheet' id='NextGEN-css' href=' type='text/css' media='screen' /> <script type='text/javascript' src=' <script type='text/javascript' src=' <!-- <meta name="NextGEN" version="1.9.7" /> -->
This takes care of NextGEN's slideshow and CSS, as well as the Shutter script and CSS that it also enqueues by default. add_action('wp_print_scripts', 'wpse_82982_removeScripts'); add_action('wp_print_styles', 'wpse_82982_removeStyles'); function wpse_82982_removeScripts() { wp_dequeue_script('ngg-slideshow'); wp_dequeue_script('shutter'); } function wpse_82982_removeStyles() { wp_dequeue_style('NextGEN'); wp_dequeue_style('shutter'); } But: are you _sure_ you want to do that? Maybe you can be a little selective, and only do that on selected pages / posts / categories. Edit: to remove the commented-out meta tag too, add this filter: add_filter('show_nextgen_version', '__return_null');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, plugin nextgen gallery" }
How can I enqueue protocol relative external (//ajax.googleapis.com/...) scripts? According to the Codex, wp_enqueue_script supports protocol relative, or protocol agnostic external links: "Remote assets can be specified with a protocol-agnostic URL, i.e. '//otherdomain.com/js/theirscript.js'." But I'm not seeing it: wp_enqueue_script('google-maps', '//maps.googleapis.com/maps/api/js?&sensor=false', array(), '3', true); Output: <script type='text/javascript' src=' Notice that the protocol relative URL is appended to the site URL.
The code you posted works fine and results in this in the HTML output: <script type='text/javascript' src='//maps.googleapis.com/maps/api/js?sensor=false&#038;ver=3'></script> Tested on WordPress 3.5 with this code snippet: add_action('wp_enqueue_scripts', 'test'); function test() { wp_enqueue_script('google-maps', '//maps.googleapis.com/maps/api/js?&sensor=false', array(), '3', true); }
stackexchange-wordpress
{ "answer_score": 18, "question_score": 14, "tags": "wp enqueue script" }
Perform action on WPMU blog deletion Hi guys :) I know there is the `wpmu_new_blog` action hook which enables us to perform an action when a new WPMU blog is created. Is there something similar to this which enables us to perform an action when a WPMU blog is deleted? Something which looks like this: `add_action('blog_deletion_hook', 'function_to_perform')`
Yes, inside `/wp-admin/includes/ms.php` there is the action hook `delete_blog`. This test prevents a blog deletion: add_action( 'delete_blog', 'prevent_blog_delete_wpse_82961', 10, 2 ); /** * @param int $blog_id Blog ID * @param bool $drop True if blog's table should be dropped. Default is false. */ function prevent_blog_delete_wpse_82961( $blog_id, $drop ) { wp_die( 'aborting delete_blog' ); }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "multisite, hooks, actions" }
add new permalink structure from dynamic page I created page "play" url: ` and inside of page "play" I include PHP code to make the new search from outside Wordpress. And all worked, if I search from my page "play" the url will be: ` Now, I want my search result url to be fancy url, like: ` I have tried several add_rewrite_rules but not worked, return "404 not found": add_action('generate_rewrite_rules', 'add_rewrite_rules'); function add_rewrite_rules( $wp_rewrite ) { add_rewrite_rule('^^([^-]*)_([^-]*)\.html$ play&m=$1&pageno=$2[1]', 'top'); flush_rewrite_rules(false); } ps: sorry my english is not good
Only way I knowit to do this it's using this function: /* * Redirects search results from /?s=query to /search/query/, converts %20 to + * @link * ======================================= */ function search_redirect() { if (is_search() && strpos($_SERVER['REQUEST_URI'], '/wp-admin/') === false && strpos($_SERVER['REQUEST_URI'], '/find/') === false) { wp_redirect(home_url('/finde/' . str_replace(array(' ', '%20'), array('+', '+'), urlencode(get_query_var('s')))), 301); exit(); } } add_action('template_redirect', 'search_redirect'); It's this you wanna do?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "permalinks, url rewriting, mod rewrite" }
Different logo on homepage I have uploaded a file as my main logo within the theme settings but would like a different logo on the main page. The theme I am using has a custom css option within the theme settings, can I use custom css to only change it on the front page and not the rest of the site? Theme: <
It looks like the theme designer has a means for you to use a different logo on the homepage. Looking at your `header.php` on lines 83-93. If your theme detects that this is the front page, the title is enclosed with an `<h1>` tag, otherwise it is enclosed in a `<div>`. Both have `id='logo'`. If you can add custom css, you could use css image replacement to replace this `<h1>` tag with a different image on your homepage.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "themes, customization, css" }
Target all posts that are NOT aside or link post formats I want to add a post title to all of my posts apart from those that are marked as "aside" or "link" post formats. I'm currently using this code to hide the post title for aside posts; <?php if (! has_post_format('aside')) { ?> <?php the_title();?> <?php } ?> How can I target the "link" post format aswell using this method?
**Edited:** Now that I understand your question, try this... Place this above your title to enable the post_class function. <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> Then add `</div>` below your title (or excerpt, or wherever you want this special styling to end). Now, a special class will be added in which you can use the classes for post formats. for example, you may now use `.format-aside` in your CSS to style the aside.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 3, "tags": "post formats" }
prepare() not working When I do this: $transients = $wpdb->get_col( " SELECT option_name FROM $wpdb->options WHERE option_name LIKE '_transient_wb_tt_%' " ); It works fine, but when I use prepare like so: $transients = $wpdb->get_col( $wpdb->prepare( " SELECT option_name FROM %s WHERE option_name LIKE '_transient_wb_tt_%' ", $wpdb->options ) ); It doesn't work, what am I doing wrong here?
I agree with @bainternet. You don't need `$wpdb->prepare`. There isn't any user supplied content. The answer to the question is that to get a wildcard `%` to pass through `prepare` you need to double it in your code. LIKE '_transient_wb_tt_%%' Try that or this if you want a good look at the generated query: var_dump($wpdb->prepare(" SELECT option_name FROM %s WHERE option_name LIKE '_transient_wb_tt_%%' ", 'abc')); die; Other than being unnecessary, using `$wpdb->prepare` like this won't work. The attempt to use `prepare` to swap in the tablename will result in a tablename with quotes around it. That is invalid SQL. The query should be simple: SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '_transient_wb_tt_%%'
stackexchange-wordpress
{ "answer_score": 1, "question_score": 4, "tags": "sql, wpdb" }
getting values from a shortcode with an include I have a checked a few links but nothing seems to for me in getting the attribute value of a shortcode so that I can use it in a condition. function bf_shortcode_slideshow($atts) { extract(shortcode_atts(array( 'location' => '' ), $atts)); ob_start(); if ( $location = 'home' ) { classslider = 'homeslider'; } include(dirname(dirname(__FILE__)) . '/templates/slideshow.php'); return ob_get_clean(); } add_shortcode('rotator', 'bf_shortcode_slideshow'); In the `slideshow.php` I have a echo 'classslider=' . $classslider; My result for `$classslider` is blank ( nothing is displayed ) Is there another way you should compare `$location` to a string value set ?
`include` changes the scope. You would need to declare `$classslider` global before defining it, and then use `global $classslider;` before using it. function bf_shortcode_slideshow($atts) { global $classslider; extract(shortcode_atts(array( ... I think that will fix your problem. I don't understand why you are using `include` at all though. There must be a better way to make that slideshow work.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "shortcode, customization" }
Second page (and next) of search results redirects me to the home page WP 3.5, nginx (latest) and PHP5-FPM (latest). If you visit < the page is properly loaded. When you click on the link to go to the next page, you are redirected to the home page. Try it out: < I don't know what's the cause to this... I think it's something related to my nginx conf for WP (because it happens on also another installation on the same VPS with same config but different theme). Here's my nginx config: location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; include /etc/nginx/fastcgi.conf; fastcgi_pass unix:/var/run/php5-fpm.sock; } location / { # if you're just using wordpress and don't want extra rewrites # then replace the word @rewrites with /index.php try_files $uri $uri/ /index.php; }
Solved changing the location block with this: location / { try_files $uri $uri/ /index.php?$args; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "search, server, configuration, nginx" }
Make Author Archive Page URL be a Subdirectory of a Custom Post Type URL I have a custom post type with a custom URL structure so it works like: etc. Now I have multiple authors of these posts, so I want to enable an "Author Archive" for only these custom post types at urls like this: Is this possible? Any ideas? Thanks! UPDATE: @Milo points out (I believe correctly) that "WordPress wouldn't be able to discern what is a post title and what is an author name," so given that, how would I get URLs like < ? Thanks!
Change `custom-post-type` in the following to the name of your CPT, both the slug and `post_type=` in the query vars. Visit your Permalinks Settings page to flush rewrite rules. You could also put this in a plugin and flush rules on plugin activation. function wpa83047_author_rewrite_rule(){ add_rewrite_rule( '^custom-post-type/author/([^/]+)/?$', 'index.php?author_name=$matches[1]&post_type=custom-post-type', 'top' ); } add_action( 'init', 'wpa83047_author_rewrite_rule' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "url rewriting" }
Taxonomy Tag Conditionals I'm using jigoshop as main ecommerce plugin. Jigoshop use Taxonomies call, product_cat and product_tag. In my theme I use a default (h5bp) 404.php, so every time a tag doesn't exist I get the default 404. But I need to have a special template that give a `THIS TAG DO NOT EXIST` how can I do this? I'm using pointless: @@@ <?php if (is_tax()){ jigoshop_get_template( 'product_taxonomy-no.php' ); }else{ jigoshop_get_template( 'product_taxonomy-no.php' ); } ?> @@@ thanks
If you want to use an entirely different template, you could filter `404_template` and check query vars for a specific taxonomy: function wpa83050_404_template( $template = '' ){ global $wp_query; if( isset( $wp_query->query_vars['product_cat'] ) ) $template = locate_template( array( "product_taxonomy-no.php", $template ), false ); return $template; } add_filter( '404_template', 'wpa83050_404_template' ); You could also just put logic similar to the above in your 404 template and use that single template for all 404s, check `$wp_query` for what query vars are set and print some text accordingly. add `var_dump( $wp_query );` to your template to see what query vars get set under different conditions.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "taxonomy, tags, conditional tags, jigoshop" }
How to create this kind of sub-menu in new line? In my design I need use this kind of wordpress custom menu. Menu (I am able to do this) !enter image description here Menu element with sub menu. (but not this one) !enter image description here In this UI , I can not able to separate sub-menu to the new line with CSS. Then how can I add specific menu sub menu to new line.
I think, your question is similar to mine. I tried a similar thing earlier. Can check this StackOverflow thread started and answered by me.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, customization" }
How to access the so called "Posts page" This might be a dumb question - I'm sorry for that but: If I decide to alter "Reading Settings" and choose a front page for home I can define a "Static Page" and a "Posts Page". "Static Page" ain't leaving a question to me since it's what's gonna be grabbed if I click on my Logo. But where will I face this so called "Posts Page"? I'm feeling confused somehow :-)
< > "Posts page - Select in the drop-down box the name of the Page that will now contain your Posts. If you do not select a Page here, your Posts will only be accessible via other navigation features such as category, calendar, or archive links. Even if the selected Page is Password protected, visitors will NOT be prompted for a password when viewing the Posts Page. Also, any Template assigned the Page will be ignored and the theme's index.php (or home.php if it exists) will control the display of the posts."
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "blog, frontpage, homepage" }
Trigger a cron every 24h GMT -8 I' like to run a cron every 24 hours at midnight PST ( = GMT -8 ) This is what I have if ( !wp_next_scheduled( 'cron_hook' ) ) { //reset on 00:00 PST ( GMT -8 ) == GMT +16 $timeoffset = strtotime('midnight')+((24-8)*HOUR_IN_SECONDS); if($timeoffset < time()) $timeoffset+(24*HOUR_IN_SECONDS); wp_schedule_event($timeoffset, 'daily', 'cron_hook'); } This sets a daily cron on midnight GMT -8 (24-8) and postpone it 24 hours if it's already in the past so the cron doesn't get triggered at the time of creating. Am I correct with this approach or do I miss something? I've already tested it but since my server is running with GMT + 0 I cant verify that for other timezone
Almost, WP Cron jobs do not run at specific times, they are approximate, and all timestamps should be UTC, as WordPress **_always_** deals in UTC timestamps. If you want midnight PST, you'll want to specify 8PM UTC. Also for example, your above code suggests midnight PST, but it may not run at midnight PST. If nobody visits the site at the specified time, and there's 4 hours before someone arrives, then the cron job will occur at 4am. If you're wanting accurate cron jobs that are not approximate, you will need to setup a server cron job to call the wp cron URL at fixed intervals. I would also choose a more specific name than 'cron_hook' to prevent clashes and issues in the future You can test this easily by just figuring out what time midnight PST is in UTC, aka 8AM, does your cornjob fire at 8AM UTC?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "cron, wp cron, timezones" }
Image Upload "exceeds the maximum upload size for this site", but php.ini is correct I'm getting an "file.png exceeds the maximum upload size for this site" error. It's saying the upload limit is 1MB when trying to upload an image that is 2.5M on WP 3.5. It is setup in multi-blog mode (if that matters). I have set my php.ini file to 64M for post_max_size and upload_max_size, and it's working for other (non WordPress) sites on my server. I have no idea where the 1MB limit is coming from. I don't have a host, we run out own servers. Any ideas? From `phpinfo();` : upload_max_filesize 64M 64M post_max_size 65M 65M
> It is setup in multi-blog mode (if that matters) That will matter a lot. you probably need to ask the super admin to change the upload setting for your site <
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "php, uploads" }
Conditional Custom Image Header I thought there was a conditional for a custom image header that could check whether an image had been added (not whether the feature was enabled, but actually being used). I wanted to use it to add a body class, but I can't find it again. Does anyone know of how to check if the site has a custom header?
you could try the following right before you call the `body_class()` function: <?php $header_image = get_header_image(); if( !empty( $header_image) ){ $custom_body_class = 'has-header-image'; } else { $custom_body_class = 'no-header-image'; } ?> <body <?php body_class($custom_body_class); ?>>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "conditional tags, custom header" }
How do you change the theme location? To change the upload directory I have to do this: define ( "upload", "<new upload location>" ); How can you change the themes location? I like to create a folder themes in the root directory.
You can register _additional_ directory or directories with themes by using `register_theme_directory()` function, that accepts filesystem path to folder. Note that this isn't typical and even while core handles it mostly fine, third party code in themes and plugins might not.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 5, "tags": "themes" }
Displaying child page content of a certain parent What I would like to do is to create a WP loop that will display info from a child page of an adult page ID, so the Page ID is 2. I would like to pick a page ID to display what page. So that way I could display information from another child page on an alternative page. Owen
This is a near duplicate of a number of questions here, but the "single random result" might make it somewhat distinct. $args = array( 'post_type' => 'page', 'post_parent' => $post->ID, 'orderby' => 'rand', 'posts_per_page' => 1, 'no_found_rows' => true ); $child = new WP_Query($args); var_dump($child->posts); You are telling `WP_Query` to pick 1) pages, 2) with the parent of the current page, 3) ordered randomly, 4) one result, and 5) don't bother tracking found rows since we already know it should be 0 or 1. There are numerous examples of creating multiple loops here and in the Codex. You should be able to find plenty of information to flesh this out. In short you want: while ($child->have_posts()) { $child->the_post(); var_dump($post); // raw dump of your child post }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, child pages" }
How can i listing current category and Featured Category post list? I have a Featured Post Category. Im marked some post Featured. When i viewing a category page(e.g. Sport), i want to list on sidebar both marked post list (e.g Featured and Sport,) I tryed with that following code.It's worked for me but when i using my code i see two category post (e.g Sport ), category post list affected by my code and listing same post list. My example picture! Here How can i fix that? My Code: <?php //55 is my Featured Category id if ( is_category() ) { $current_cat = get_query_var('cat'); } query_posts(array('category__and' => array(55, $current_cat ))); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <li><a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a> </li> <?php endwhile; else: ?> <?php endif; ?>
I think you're asking about your custom secondary loop affecting your main loop, correct? `query_posts()` alters the main loop. A quick fix would be to call `wp_reset_query()` after your custom loop to reset the query data: <?php wp_reset_query(); ?> However, it's more efficient and friendlier to use `WP_Query()` instead of `query_posts()` (especially if you're making a secondary loop). This should be the equivalent of your provided code using `WP_Query()`: <?php if ( is_category() ) { $current_cat = get_query_var('cat'); } $args = array( 'category__and' => array( 55, $current_cat ) ); $my_query = new WP_Query( $args ); ?> <?php while ( $my_query->have_posts() ) : $my_query->the_post(); ?> <li> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </li> <?php endwhile; ?> <?php wp_reset_postdata(); ?> References: < <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development, categories, functions, query posts" }
how can i hide category? Please help me I am new baby in wordpress, how can i hide that 'course or call' category from the page.. i have var dump the variable which is passing as parameter to query_post $args = jr_filter_form(); var_dump($args); query_posts($args); !enter image description here this category is having tag_ID="65" in its url , which i have seen in wordpress dashboard, job category page please help me a little thanks
Thanks u guys , your views help me to analyse i have added this lines and it works thanks u all, $args = array_merge( array( 'job_type' => 'Jobs' ), $args ); query_posts($args);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, query posts" }
Deleting a custom field field Is there a way to delete a custom field (in the sense of complete removal from WP database) without using a plugin?
If you have access to phpMyAdmin, these steps should do the trick: > Step 1: Login to your hosting account and launch myPHPadmin from the cPanel, or equivalent, to access the WordPress database engine. > > Step 2: Enter a select SQL command to list all the meta keys you want to remove. In this example, I want to find and eventually remove the meta key dcssb_short_url. > > > SELECT * FROM 'wp_postmeta' where 'meta_key' = 'dcssb_short_url' > > > Step 3: Once you are satisfied you’ve narrowed down the selection, issue a delete SQL command to remove the rogue data > > > DELETE * FROM 'wp-postmeta' WHERE 'meta_key' = 'dcssb_short_url' > > > Step 4: Issue the same select SQL command again, to verify all the offending records have been deleted. > > > SELECT * FROM 'wp_postmeta' where 'meta_key' = 'dcssb_short_url' > > > If you get no results returned, it means that you successfully deleted the records. Source
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "custom field" }
Avoiding using a loop to access a single post Sometimes I want to access one particular CPT to extract something from it, for example a custom field value: $group = new WP_Query( array( 'post_type' => 'group', 'p' => $group_id ) ); while ( $group->have_posts() ) : $group->the_post(); $group_type = get_post_meta($post->ID, "group_type", $single = true); endwhile; However the purpose of a loop is to access more than one element so I dislike using a loop for a single post. Is there a way to do exactly the same thing (accessing this custom field value) without using a loop?
how about get_post? $post = get_post( $p ); $group_type = get_post_meta( $post->ID, 'group_type', true );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 4, "tags": "loop" }
Shortcode of a function I got this function and i want to make the contents divs of "foreach" as return. How can i do that? <?php $args = array( 'numberposts' => 6, 'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date"); $postslist = get_posts( $args ); foreach ($postslist as $post) : setup_postdata($post); ?> <div class="events"> <p><strong><?php the_date(); ?></strong></p> <p><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></p> </div> <?php endforeach; ?> /// Top Section Block add_shortcode('top_section_block', 'shortcode_top_section_block'); function shortcode_top_section_block($atts) { extract(shortcode_atts( array( 'content' => '', ), $atts)); return ' '; }
Build a string instead of directly outputting the contents. $str = ''; foreach ($postslist as $post) : setup_postdata($post); $str .= '<div class="events">'; $str .= '<p><strong>'.get_the_date().'</strong></p>'; $str .= '<p><a href="'.get_permalink().'" title="'.esc_attr(get_the_title()).'">'.get_the_title().'</a></p>'; $str .= '</div>'; endforeach;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, shortcode, html" }
Post type specific upload folder in 3.5 In 3.4 I used the following function to change image upload folder by post type. Different upload directory based on post type in a theme Now it doesn't work anymore in 3.5. Do you have any idea how to replace this function in 3.5 version? thanks
Yes, it does. I had to do something similar just yesterday and worked out this solution. About the same as the linked solution, but with a bit more error checking. <?php add_filter('upload_dir', 'cgg_upload_dir'); function cgg_upload_dir($dir) { // xxx Lots of $_REQUEST usage in here, not a great idea. // Are we where we want to be? if (!isset($_REQUEST['action']) || 'upload-attachment' !== $_REQUEST['action']) { return $dir; } // make sure we have a post ID if (!isset($_REQUEST['post_id'])) { return $dir; } // modify the path and url. $type = get_post_type($_REQUEST['post_id']); $uploads = apply_filters("{$type}_upload_directory", $type); $dir['path'] = path_join($dir['basedir'], $uploads); $dir['url'] = path_join($dir['baseurl'], $uploads); return $dir; }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "uploads, media settings" }
How to display the names of users from a specific group with a shortcode? I have in the database a table with the `user_id` and corresponding `group_id` values, so each row contain the ID of the user that is a member of a group and the related group ID. **The question is** : How to display the names of users from a specific group, plus some metadata, with a shortcode, for example `[group_members group_id=1]`? With the bellow function, that I try to adapt for this without success, I can to display only the user ID or the group ID. add_shortcode( 'group_members', 'group_members_shortcode_handler' ); function group_members_shortcode_handler ( $atts, $content = null ) { global $wpdb; $querystr = "SELECT * FROM wp_groups_user_group"; $users = $wpdb->get_results($querystr, OBJECT); foreach ($users as $user) { $output .= $user->group_id; } return $output; }
Below is my own answer to the question. I will appreciate any constructive comment. add_shortcode( 'group_members', 'group_members_shortcode_handler' ); function group_members_shortcode_handler ( $atts, $content = null ) { global $wpdb; $querystr = "SELECT * FROM wp_groups_user_group"; $users = $wpdb->get_results($querystr, OBJECT); $output=''; foreach ($users as $user) { if($user->group_id == $atts['group_id']){ $firstName = esc_html(get_user_meta($user->user_id, 'first_name', true)); $lastName = esc_html(get_user_meta($user->user_id, 'last_name', true)); $output .= '<li>' . $firstName . ' ' . $lastName . ' - ' . esc_html(get_user_meta($user->user_id, 'teaching_position', true)) . '</li>' . PHP_EOL; } } return $output; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "shortcode, users" }
How to add custom text editor in add post section? How can I add custom text editor in wordpress? Is there any way to do that? If not, How can I add or remove certain features from it? Thanks in advance.
You can use TinyMCE,CKeditor plugin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, text" }
Buddypress Language Files Question I have one question. I use latest Wordpress and Budypress. I have language files for buddypress - .po and .mo. My question is where I need to put the files, how I need to rename them and is there any function that I need to add somewhere (for example functions.php) to load them. I checked this page and try to follow the instructions, but my site is still in english. Thank you in advance :)
The naming convention for plugins translation files (`.mo` and `.po` files) is `pluginname-language_COUNTRY.mo`. So, for example, a French translation files of Buddypress will be: `buddypress-fr_FR.mo` and `buddypress-fr_FR.po`. After renaming these files, put them in `wp-content/languages` directory and your translation should work. Note that `WP_LANG` must be defined with the same language (`fr_FR` for example) for the translation files to load.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "buddypress, language" }
Updating client websites on a regular basis I hope the following question is acceptable here, as it's half WordPress-related and half-business related. Updating WP regularly is important for security purposes, but it can be time consuming if there are many websites to update and even more if some updates require plugin updates (and in some cases, a plugin ceases to work after WP update which potentially requires a time-consuming solution). What is the best solution to address this ongoing problem? Should WP regular updates be charged for example? Should it be mentioned in the initial contract?
I don't think there's a best solution, but whatever you decide to do, speak to the client about the issues, reach an agreement and put it in writing. I think it's important to discuss why we are using WordPress/theme frameworks/3rd party plugins, and what that means. The advantages: vastly reduced development time, a great community, etc., and the potential disadvantages (plugins that break). One option is to offer six months of free support, then charge by the hour after that. As long as the client is comfortable backing up their WP installation, then I see no reason why they can't update the site themselves. If something goes wrong, they at least have a backup.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "updates" }
Accessing multiple sites via FTP I've installed wordpress MU, and established a different site in my domain/dev/sitename -- but I want to then install a theme on that site, and edit it directly. However, my FTP only shows the main Wordpress installation. How do I get at the /sitename subdirectory?
You don't need to get to the `/sitename` sub-directory. You install the theme in the `themes` sub-directory, and enable it for all sites. WPMU doesn't have an out-of-the-box capability to enable a theme for one site only, but I there might be plugins that give that functionality.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "multisite" }
Inbuilt style for jquery-ui-datepicker I want to use the datepicker that gets bundled with WordPress on the front end of a website. I enqueued `jquery-ui-datepicker` but the datepicker isn't styled(no js error in console). Is there a corresponding `wp_enqueue_style` for that? I used this code in `functions.php` function rr_scripts() { wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'jquery-ui-datepicker', array( 'jquery' ) ); wp_register_style( 'bootstrap_css', get_template_directory_uri() . '/assets/css/bootstrap.min.css' ); wp_enqueue_style( 'bootstrap_css' ); # I'm using Twitter Bootstrap as CSS(if it matters) } add_action( 'wp_enqueue_scripts', 'rr_scripts' );
As far as I know, there is not style for datepicker. You have to register your own. The code then will be: function rr_scripts() { wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'jquery-ui-datepicker', array( 'jquery' ) ); wp_register_style( 'bootstrap_css', get_template_directory_uri() . '/assets/css/bootstrap.min.css' ); wp_enqueue_style( 'bootstrap_css' ); // I'm using Twitter Bootstrap as CSS(if it matters) wp_register_style('jquery-ui', ' wp_enqueue_style( 'jquery-ui' ); } add_action( 'wp_enqueue_scripts', 'rr_scripts' );
stackexchange-wordpress
{ "answer_score": 22, "question_score": 11, "tags": "css, wp enqueue style, jquery ui, datepicker" }
WooCommerce: How to edit the get_price_html I am trying to edit the price value for a single product. In `single-product/price.php` there is a template call to `$product->get_price_html`. How can I edit that function/method to change the way the HTML is presented? At the moment even if I delete all the contents of the function located in `class-wc-product` it still miraculously displays? Anyone know why?
Core and plugin files should never be edited directly, as any updates could overwrite your changes. If you look in WooCommerce source at the `get_price_html` method, there are a number of filters available to modify the output of the function. See `add_filter` in Codex for more info on adding filters to `apply_filters` calls. From `get_price_html` in `class-wc-product`: return apply_filters('woocommerce_get_price_html', $price, $this); So to add your own filter: add_filter( 'woocommerce_get_price_html', 'wpa83367_price_html', 100, 2 ); function wpa83367_price_html( $price, $product ){ return 'Was:' . str_replace( '<ins>', ' Now:<ins>', $price ); }
stackexchange-wordpress
{ "answer_score": 26, "question_score": 18, "tags": "woocommerce offtopic" }
Does WordPress Development Mode Exist (with not minified JS)? A lot of WP JS is minified and therefore it's hard to be analyzed in the Console. Is there any way to have all scripts uncompressed?
Yes there is, from Debugging in WordPress codex, you need to define `SCRIPT_DEBUG` in `wp-config.php` to force WP to load the `dev` versions of the scripts: define('SCRIPT_DEBUG', true);
stackexchange-wordpress
{ "answer_score": 10, "question_score": 4, "tags": "functions, javascript" }
Hide meta box based on post format I'm currently using a version of this function - post formats - how to switch meta boxes when changing format? which hides all meta boxes until a corresponding post format is selected (Ie; If someone selects "Video" then my custom Video meta box shows up) But when the post is saved all the meta boxes become hidden again unless I reselect the post format. Is there a way to show the appropriate meta box even when the post has been saved? This is the main function; jQuery( document ).ready( function($) { // Starts by hiding the "Video Options" meta box $( "#video-options" ).addClass( "hidden" ); // If "Video" post format is selected, show the "Video Options" meta box $( "input#post-format-video" ).change( function() { $( "#video-options" ).removeClass( "hidden" ); } ); } );
Try this one: jQuery( document ).ready( function($) { // Starts by hiding the "Video Options" meta box $( "#video-options" ).addClass( "hidden" ); if( $( "input#post-format-video" ).is(':checked') ){ $( "#video-options" ).removeClass( "hidden" ); } // If "Video" post format is selected, show the "Video Options" meta box $( "input#post-format-video" ).change( function() { if( $(this).is(':checked') ){ $( "#video-options" ).removeClass( "hidden" ); } } ); } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "metabox, post formats" }
Put Microsoft Excel xlsx document I want display Microsoft Excel xlsx sheet in wordpress. How i can do that? Also it will be looking like excel sheet. Thanks.
Your best bet will be using the Google Document Embedder plugin. It has sketchy support for the new X MS Office files, but will sometimes work. If not, you'll need to re-save the file as the old XLS filetype.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -3, "tags": "microsoft" }
Using wp_get_image_editor in a standalone script With WP 3.5, they updated the image resizing scripts with `wp_get_image_editor`. Currently, in this standalone script that is accessed with Ajax, I have included `wp-load.php` so I can access all of the WP functions. Particularly, `$wpdb;`. In order to use the `$wpdb` functions, I had to declare `global $wpdb;` first. I assumed I had to do the same for `wp_get_image_editor`, but there is no global variable to declare. When using: $image = wp_get_image_editor($current); //if (!is_wp_error($image)) { $image->resize(100, 100, false); } nothing happens, and if I remove the `if` statement, I get the error > PHP Fatal error: Call to undefined method WP_Error::resize() Does anyone know how I can do this? Would it be smarter to install my own image-resizing scripts?
Turns out I'm just silly. WP_Error was the undefined method, not resize. I was sending a bad image location through the resize function. How silly of me! It was working all along. I've included this on top $parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] ); require_once( $parse_uri[0] . 'wp-load.php' ); and this is my image resize function $image = wp_get_image_editor($current); if (!is_wp_error($image)) { $image->resize(100, 100, false); $image->save($target); return "succ"; } else return "error";
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "php, plugin development, functions, images" }
Metabox date month number to word I use custom metabox with date (day, month and year). The problem is when I try to transform date number to date word - for example 10 to be October. I use this code: function eventposttype_get_the_month_abbr($month) { global $wp_locale; for ( $i = 1; $i < 13; $i = $i +1 ) { if ( $i == $month ) $monthabbr = $wp_locale->get_month_abbrev( $wp_locale->get_month( $i ) ); } return $monthabbr; } But now the month is displayed only with three symbols - Oct. I like to be full month name. Is there any way to define it? Thank you in advance!
The code you are using is specifically for the month abbreviation, (Oct). You should be using this: function eventposttype_get_the_month($month) { global $wp_locale; for ( $i = 1; $i < 13; $i = $i +1 ) { if ( $i == $month ) $month =$wp_locale->get_month( $i ) ; } return $monthabbr; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "metabox, date" }
Remove / Rename Uncategorized Category In Wordpress I have installed wordpress Muilit Site (NETWORK) I need to Remove / Rename **`Uncategorized`** Category In Wordpress. How is this possible?
To change the default "Uncategorized" using code you can do the following: // Uncategorized ID is always 1 wp_update_term(1, 'category', array( 'name' => 'hello', 'slug' => 'hello', 'description' => 'hi' )); Read this: <
stackexchange-wordpress
{ "answer_score": 8, "question_score": 5, "tags": "categories" }
Why is a category/ tag name prefixed to title of every page? Recently, I've noticed there is a category/ tag name "Contests" added to the title of all of my pages. I've checked the "Tagline" under "Settings" >> "General" of course, it hasn't changed. This is what's in `header.php` and I have never touched it at all: <title><?php wp_title(''); ?><?php if(wp_title('', false)) { echo ' :'; } ?> <?php bloginfo('name'); ?> </title>
I've found the cause. All in one SEO Pack plugin 1.6.14.5 is guilty (perhaps it's not guilty by itself but also due to the multisite setup of my site and other plugins I've just installed conflicting it). Disabling the plugin resolve the problem immediately. I'm upgrading it and will use an alternative if it doesn't work out. Thanks @LeaCohen for pointing me to the right redirection. **Updates** Instead of deactivating the plugin, disabling the auto-rewrite title in settings of the plugin is sufficient. At the same time, just FYI, All-in-one SEO Pack plugin version 1.6.13.8 works just fine for WordPress multisite 3.4.2. I can no claims about the possible conflicts between this and any other WordPress plugins
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "title, wp title" }
How to sync with plugins update after I have done manual optimizations? I have several WordPress running plugins on my site and as per suggestions of wordpress performance optimizations I am planning to do the optimizations on plugins myself. However, that will mean that I will have to modify existing plugins codes. Now, as WordPress plugins release frequent updates, the updates will wipe out my manual changes. How can I keep sync between these? That means, how can I get updated plugin and keep my manual changes as well?
Create a local repository in Git (or SVN) for the plugin, and each time an update happens: * merge the changes into your adjusted version, * test it in your local copy of the production site, * then push your updated code to your site. But much better would it be to send your improvements to the plugin author, so she can use that in the main code. Keeping improvements secret is not the spirit of Open Source.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "plugin development, updates, performance" }
Dynamic price product I started a wordpress project for a client which has an e-commerce part. So I decided to try Woocommerce. Nevertheless I'm not yet familiar with this "big" plugin. The client has several specific needs and I'm not able to say if the plugin would cover those needs. This is an airsoft website. The users will be able to reserve a match. One of client's needs is: Depending your stuff, the price changes (49$ for non-equiped and 10$ for those who have their stuff). If Woocommerce can do it, I would like to know how to implement those features ? I mean a "product" will be a "match", but then how to customize it like I would like. Any help would be apreciated, regards,
I believe you are asking for product variations.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
Redirect wp-login I have a custom page called owner-login that has a `wp_login_form()` How can I disable wp-login.php so that: * when a user writes `wp-admin/` it will redirect him to the owner-login (if not logged) * when a user writes `wp-login.php` it will redirect him to the owner-login (logged/not logged) Generally, I don't want to show wp-login, but to have the functionality for the scripts that require
Try something similar to this: function is_login() { return in_array( $GLOBALS['pagenow'], array( 'wp-login.php', 'wp-register.php' ) ); } function redirect_login() { if ( is_login() ) { wp_redirect(' } } add_action( 'init', 'redirect_login' ); You'll need to modify the URL it redirects to, and test thoroughly.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "login, wp redirect, wp login form" }
Contact Form 7 "non-selectable" options in a drop down I'm using CF7 and I need to have a dropdown with a non selectable category "header" such as **US States** AL AK AR...etc. **Countries** Afganistan Albania etc.... With "US States" and "Countries" not an option to submit. Thanks EDIT: I solved the problem myself if anyone has the same issue I used JQuery and gave the options I wanted to make non-selectable an empty value. $("option:nth-child(1), option:nth-child(1)").val(""); $("option:nth-child(1), option:nth-child(53)").val(""); });`
I can see how your solution works, but there is a semantic element created for exactly what you want: `<optgroup>`. Whatever your solution, I'd encourage you to use that instead. Searching for "contact form 7 optgroup" you'll discover that other people are looking for the same thing you are and trying to implement `<optgroup>` to do it. Here's one answer that includes both a javascript solution and a plugin hack (probably not a good idea). Probably the better solution I've found is this one. It's a javascript to replace Contact Form 7 select options with the optgroup element using a specified syntax. That final solution should probably remain stable even if CF7 adds optgroup support down the road.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, forms, dropdown, plugin contact form 7, contact" }
Need to return shortcode text instead of the output Is there a way I can return the shortcode text instead of the output. My code function is hooked into 'the_content' and I know if my function contain shortcode it will automatically generate the output. I just want to output shortcode text e.g [gallery] add_filter( 'the_content', 'show_on_front', 10 ); function show_on_front( $content ) { $content .= 'this is example of shortcode : [gallery]'; return $content; } Regards,
Another way is to use a shortcode to display shortcodes :) add_shortcode('SH','shortcode_display_handler'); function shortcode_display_handler($atts = array(),$content=null){ $content = str_replace("[","&#91;",$content); $content = str_replace("]","&#93;",$content); return $content; } Usage: [SH] [gallery] [/SH]
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters, shortcode, hooks" }
Need custom picture field for pages I want to have a picture or multiple pictures on each page in wordpress. AFAIK there are two standart ways of doing this 1. in WYSIWYG editor, attach file etc 2. widgets. Problem is, those wont do for my clients. So how can I make a custom field on each page, where the user selects a pic if he wants. I know there is a plugin, "sidebar per page" but i would like to do it without plugin, and if possible all the page editing happens on admin>pages>page x without the need to go to widgets are and so on. Pls share if there is a way to do this, or what it would take. TY
It sounds like "Featured" or "Thumbnail" images would work. These are enabled by default for 'posts'. For 'pages' they need to be enabled, but that is as simple as adding `add_post_type_support( 'page', 'thumbnail' );` to your theme's `functions.php` hooked on `init`, and, of course, modifying the theme template files to display the featured image. function add_featured_to_post_wpse_83508() { add_post_type_support( 'page', 'thumbnail' ); } add_action('init','add_featured_to_post_wpse_83508'); The theme itself has to register its support with `add_theme_support( 'post-thumbnails' );` In the Loop, `the_post_thumbnail()` will display the image
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, customization" }
Change permalinks for posts but not for custom post types Currently my permalink structure for posts is domain.com/post-title I'm using a static front page and a "blog" page for posts. I'd like to to change the permalink structure for posts, tags and categories to domain.com/blog/post-title I can easily add /blog/ in the permalink structure but the catch is that my custom post types also get this modified permalink structure and that is not the desired result. Thanks in advance!
When you register your post type, the `with_front` argument of `rewrite` should be `false`, so the permastruct is not appended to the front of your custom post type permalink. $args = array( // snip... 'rewrite' => array( 'with_front' => false ), // snip... ); register_post_type( 'your-post-type', $args );
stackexchange-wordpress
{ "answer_score": 16, "question_score": 12, "tags": "custom post types, posts, theme development, permalinks, mod rewrite" }
WP Super Cache compression not working I have WP Super Cache installed, and compression is turned on. However, both GIDZipTest and Google Page Speed Insights Chrome extension say that compression is not enabled. I added the following to my .htaccess file, and they still say compression is not enabled: AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript **UPDATE** : I have since disabled WP Super Cache, and I'm testing W3 Total Cache.
W3 Total Cache is working; compression is being performed correctly.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin wp supercache" }
Weird lightbox phenomenon I have one weird thing happening with lightbox on my website. If I add a lightbox image or gallery and then click on the image, the first time it will navigate directly to the image file. If you then click the back button and click the image again, lightbox loads up normally. Any thoughts on why reloading the page after the first click makes lightbox work properly? Thanks example page
Its just you. I tried from fast internet computer and it loads fine the first time. Then I tried from a low speed computer before the page completely loaded, and it acts the way you described. So its all about loading and fast internet connection
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins" }
Why Does get_posts() Return an Empty Set? I'm writing a custom plugin that is initialized at `init`. This plugin is trying to query for some custom post types already stored in the DB. Here's my code: $args = array() $myposts = get_posts( $args ); print_r($myposts); No matter what arguments I pass into the $args array I don't get anything. For example: $args = array( 'post_type' => 'page' ); Now, to my confusion if I use the exact same arguments with `get_pages()` I get a result. Maybe this has something to do with when WP Query is initialized?
It seems that is was a simple problem. get_posts() has various default settings, one of which is that the `post_status` is set to `public` and my custom post type which doesn't use `post_status` used the default value, `draft`. To fix this you can either query by post status (see the code below) or change the data in the DB. $args = array( 'post_status' => 'draft', 'post_type' => 'your_custom_post_type' );
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "plugin development, wp query, get posts" }
How to gain access to each menu item in wordpress? I have some menu items in a menu at location "main-menu". By using `wp_nav_menu( array( 'theme_location' => 'main-menu' ) );` , i get all the 13 items in a div. Now i just need to show 10 menu items in present div and the remanining in other div (say id="new") just adjacent to it. Again if the div with id "new" has 10 menu-items in it, again a new div will be created and the remaining items are shown in it. So is there a way to access the array that contains these menu-items? Please help.
Besides a custom walker, you could also use a filter, such as `wp_nav_menu_args` or `wp_nav_menu_objects` as described in the codex
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "menus" }
External WordPress API I'd like to manipulate a WordPress website from another program/website. IS there an API already written that provides access, and authentication, to do this? Ideally, I'll be using a multi-site wordpress instance and I want an outside program to add new sites, send config options to plugins, etc.
As of Wordpress 4.7 (released December 2016), a REST API is provided out of the box on Wordpress. As you're probably aware, REST APIs are interfaced with by standard HTTP GET and POST requests, so if you have a Wordpress 4.7 installation, you can access it at this URL, by plugging this into your browser: < Further reading: * WP REST API, User Guide * WP REST API, Developer's Guide * * * **Important side note:** Because this is turned on be default, because this exposes endpoints that can changes your data (via POST/PATCH/DELETE requests), and because Wordpress prefers you not to disable it, you really really ought to turn on some form of authentication. Thankfully, turning on basic WP logged-in authentication isn't particularly hard, and there are plugins that will enable OAuth.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 4, "tags": "api" }
how can I add an icon/image for a child theme? I have set up a child theme of the twentyten theme. In the themes section that under the appearance, I can only see the child theme's title, author name, and a grey box above it. How can I add an icon/image to be displayed in the grey box?
Leave a file with the name `screenshot.png` inside the root of your child theme folder and it works. > The recommended image size is 600x450. The screenshot will only be shown as 300x225, but the double-sized image allows for high-resolution viewing on HiDPI displays. * see on Codex
stackexchange-wordpress
{ "answer_score": 12, "question_score": 14, "tags": "theme development, child theme" }
Wordpress plugin archive I need to find an archive of some Wordpress plugins. Previous webmaster of the site installed some plugins and then made modifications to some of them. He did not document these modifications in any way, so I have no idea what was changed and where. There's also no contact with him. And now I need to upgrade Wordpress and its plugins - there's a security update released. I could compare installed plugins to originals but I can't find an archive of old versions of these plugins anywhere. Is there any?
If the plugins were hosted in the official WordPress SVN repository, you can download old versions directly if they're available by clicking the 'developer' tab on the relevant plugin page. e.g. < (scroll down to 'other versions'). If the plugins weren't hosted at WordPress.org, you'll need to contact the plugin developer directly.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 7, "tags": "plugins" }
javascript is not working on Event Submission? I am using Events Manager Plugin Javascript is not working on **Submit Events** Page . I found the reason behind this , that was, I have written a line of code in functions.php to call jquery file. `wp_enqueue_script('jquery-1.7.2',get_template_directory_uri().'/js/jquery-1.7.2.min.js');` When I remove this line of code then javascripts start working fine on Event Submission Page but this file is important for me because I am using this file at many places too so I can not remove this. For Example I have a line of code which generates error.Line is : `var p_option = $('input[@name="p_option"]:checked').val();` . This line is written in **'wordpress_1/wp-content/themes/my-theme/sidebar.php'** I also asked this question on plugin support but no reply from there. Thanks in advance!!!
You're enqueuing a specific version of jQuery. It's better to enqueue the version that comes with WP, like this: `wp_enqueue_script('jquery');` in a function run by the hook `wp_enqueue_scripts`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "jquery, javascript, events" }
How to copy an existing (custom themed) site to a new domain I'm trying to find a way of duplicating an existing Wordpress site that uses a custom theme to a new domain. Once it's there I'll do a redesign of the site and redirect the old url to the new one. Just briefly... I tried following the instructions @ < but when it told me to "3.Go back to your OLD blog and go to options and change the url (both of them) to that of your new site." It logged me out and caused about 3 hours of trying to get it fixed again !! So, my question is - how do I copy an existing, custom WP site & theme (including posts etc.) onto a new domain ? I'm a complete noob at Wordpress and would very much appreciate any help given... Thanks !
If it's a new domain, it's pretty simple: 1. Install WordPress on the NEW domain 2. Copy `wp-content/themes` and `wp-content/plugin` from the OLD domain to the NEW domain (using FTP) 3. Activate the Theme on the NEW domain 4. Activate Plugins on the NEW domain 5. Delete generic content (hello world post, about page, etc.) from the NEW domain 6. Export _all content_ from the OLD domain, via `Dashboard -> Tools -> Export` 7. Import the just-exported file in the NEW domain, via `Dashboard -> Tools -> Import`. **Important** : be sure to check/enable the option to download/install attachments That should pretty much be it.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "domain, codex, clone site" }
Testing if current page is the static page set as home page I set my 'About' page as home page, its permalink (my_site/about/) became my_site/ as a result. Is_page('about') returns TRUE on my local server but FALSE on online server. Why is that ?
You can use the function is_front_page(). Put this where you want to check if is frontpage if( is_front_page() ) { echo 'I am the frontpage'; } It returns **TRUE** when the main blog page is being displayed and the Settings->Reading->Front page displays is set to "Your latest posts", **or when is set to "A static page"**
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "homepage" }
Optimizing site speed by localizing paths I read an article (which I didn't save) that argued you can improve the performance of your site by changing all file paths to full paths, so for instance, instead of `<img src="<?php bloginfo('template_directory'); ?>/images/headers/image.jpg" />` we go with `<img src=" />`. My platform has its own theme, meaning that it will only be updated if we update it. So changing paths should not be an issue. Also, the article suggested that you do the same type of changes everywhere, e.g. script files, `functions.php`, plugins (if you can be bothered to redo it every time they update...). So the question is, how much performance will this improve? Surely sending less requests on a page load should make some very minor, but noticeable, improvement?
This is nonsense. Almost all URL getters are a result of `get_option()`, eg. `get_option('stylesheet_root')`, `get_option('template')` and so on. These options are loaded very early during the request, they are cached and not fetched again. Since the options are fetched anyway, all you can improve is processing time. Nanoseconds. This isn’t worth the trouble. Just compare to the time you need when you have t change something in all those files (switching to HTTPS, to a sub-domain, changing permalinks). Install a good caching plugin. That will improve load time much, much more.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "performance, optimization" }
Adding admin-ajax.php to the frontend. Good or bad idea? I love admin-ajax.php. But I hate having to localize in order to point frontend scripts to it, and I wish there was an equivalent, easy-to-find file for themes. (It also just bothers me to see frontend requests go through "/wp-admin/". No practical reason, just looks ugly IMO.) So I've simply copied admin-ajax.php to the root dir at "/ajax.php", adjusted the include paths and removed the WP_ADMIN constant definition. Seems to work like gangbusters (I can now just direct all my frontend AJAX requests to /ajax.php! And I can still use the normal wp_ajax hooks in my plugins!). But is this safe? What might go wrong? Since this isn't built into core, I assume there's a good reason as to why not. But looking through the code, I can't see any immediate problems. You're smart--tell me if this approach is crazy. Or if there's a simpler method that I'm overlooking.
You could just use a RewriteRule to your .htaccess above the regular permalink rewrite rules: RewriteRule ^ajax$ /wp-admin/admin-ajax.php [L] Now send your AJAX requests to `example.com/ajax`, and never miss core changes to that file after upgrades.
stackexchange-wordpress
{ "answer_score": 20, "question_score": 17, "tags": "themes, ajax" }
Wordpress tries to load "next page" after done loading current page I have a fresh 3.5.1 installation - default theme, no plugins. Running HTTPFox on Firefox shows that after a GET-request of any given page in Wordpress has finished loading, a GET-request is sent for the `rel='next'` page: <link rel='next' title='Next Page Title' href=' /> and fails: 00:10:04.992 0.556 698 245 GET (Aborted) text/html (NS_BINDING_ABORTED) My question - is this on purpose? Is wordpress doing some kind of preloading? I'd like to understand why it is doing this.
This isn’t WordPress, it is Firefox’ Link prefetching. You can turn it off. Serve those requests nothing: # Serve Firefox' prefetch requests an empty page RewriteCond %{HTTP_X_MOZ} ^prefetch$ RewriteRule ^ - [L,R=204]
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "performance" }
How to Add a Custom Size for Thumbnails for WP - Gallery I am using "Lightbox Plus" plugin to create lightbox image overlay on the top of thumbnail galley. Now my question is how I can set a size for Thumbnails without affecting on the lightbox image overlays. I mean when I try to set a scale for Thumbnails through wp-Gallery edit option it apply the size even to the overlays (I would like to keep the overlay size as big as possible but this function makes them small like Thumbnails size) I also see this line of code in codex: `get_the_post_thumbnail($id, array(100,100) ); // Other resolutions` but I don't know how and where to use it. Thanks
Use **`add_image_size()`**: add_image_size( 'custom-name', 123, 456, true ); ...will create image size `custom-name`, with dimensions of 123x456px, hard-cropped. ## Edit Re this comment: > Thanks for comment but honestly I got more confused!can you please let me know what is the 'custom-name'? How I can associate this name with Gallery thumbnails? The `custom-name` is arbitrary. It's whatever you want it to be. You could call it `gallery-thumb`, if you want to: add_image_size( 'gallery-thumb', 123, 456, true ); Then, you would output that image size by passing `gallery-thumb` to `the_post_thumbnail()`: the_post_thumbnail( 'gallery-thumb' ); In your case, I assume you're using the [core WordPress `[gallery]` shortcode]( If so, you can pass the `size` attribute: [gallery size="gallery-thumb"]
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, gallery" }
Using get_template_part to retrieve a template file based on current post type I'm trying to use get_template_part to retrieve a template file based on the current post type (slug) the user is in. The template file just includes an image that is used specific to specific post types. <?php get_template_part('parts/get_post_type( $post )') ?><p id="t3-splash-title"><?php $post_type = get_post_type_object( get_post_type($post) ); echo $post_type->labels->singular_name ; ?></p> The above doesn't blow up the page, but nothing seems to get output. Not sure what I'm doing wrong here.
There is built in support for that, kind of. While I don't see anything wrong with your code, try naming your files on the form `archive-mytype.php`, `content-mytype.php` etc. and then call `get_template_part` like this: <!-- This will result in including parts/content-mytype.php --> <?php get_template_part('parts/content', get_post_type( $post )); ?> <p id="t3-splash-title"><?php $post_type = get_post_type_object( get_post_type($post) ); echo $post_type->labels->singular_name ; ?></p>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "get template part" }
allow only lowercase user registrations I'm trying to get allow only lowercase usernames are valid usernames in my wordpress blog. I managed to write a function but it does not seem to work. add_filter('validate_username' , 'simple_user', 1, 2); function simple_user($valid, $username ) { if (preg_match("/[a-z0-9]+/", $username)) { // there are spaces return $valid=false; } return $valid; } Any ideas with getting this to work ? i tried this but it never worked. I will be very appreciative if someone could help me with this one. Thank you
The filter `validate_username` sends and expects a _boolean_ value, not a string. Hook into `sanitize_user` and use `mb_strtolower()`. Sample code, not tested: add_filter( 'sanitize_user', 'wpse_83689_lower_case_user_name' ); function wpse_83689_lower_case_user_name( $name ) { // might be turned off if ( function_exists( 'mb_strtolower' ) ) return mb_strtolower( $name ); return strtolower( $name ); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "user registration, validation, username" }
How to add a menu that belongs to parent blog to all child-blogs? I want to add a menu that belongs to parent multisite blog to all child-blogs. I need the menu displayed in all child-blogs, I mean the same menu on all multisites blogs. How I can do that?
Well, thanks to **@toscho** ... For your help I found a way to achieve show the primary nav that belongs to parent blog to all child blogs: /** * Plugin Name: Network Primary Nav * Network: true */ add_filter( 'wp_nav_menu_objects', 'network_primary_nav', 100, 2 ); function network_primary_nav( $menu_items, $args ) { global $blog_id; $menu_name = 'primary'; if ( ( $blog_id > 1 ) && $menu_name == $args->theme_location ) { // to parent blog switch_to_blog(1); $locations = get_nav_menu_locations(); // get primary nav of parent blog if ( isset( $locations[ $menu_name ] ) ) { $menu = wp_get_nav_menu_object( $locations[ $menu_name ] ); $menu_items = wp_get_nav_menu_items( $menu->term_id); } // to child blog restore_current_blog(); } return $menu_items; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, multisite, navigation" }
Is it possible to remove next-post / previous-post with out creating a custom template? I'm creating a plugin that uses a custom post type. I do not want to make a custom template for viewing the posts and discovered I can add a filter for the_content to include my custom fields, this works great. However, I don't want visitors to navigate the custom post types with the previous next navigation. It there a way to remove these without creating a custom template? Thank you for taking the time to look at my issue.
Try this: function remove_link( $format, $link ) { return false; } add_filter( 'previous_post_link', 'remove_link' ); add_filter( 'next_post_link', 'remove_link' ); It should work if the theme uses `next_post_link()` and `previous_post_link()`. Cheers
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "plugin development, filters, the content, previous post link" }
Custom fields issue I installed the plugin Advanced Custom Fields and created few custom fields , but I'm not able to add any content in it. How is this done?
Within Admin under 'Screen Options' tab, make sure 'Custom Fields' is ticked. Then below your Post you should find your Custom Fields area. From here, select the custom field from the dropdown and add content in the value field on the right. Hope this helps.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field, advanced custom fields" }
How do I do this with WordPress? Taxonomies? I was hoping to get some help with how I organise posts in WordPress. I have 2 Custom Post Types called 'Places' and 'Events'. In the Admin, I'd like to be able to create a 'Place' post and associate multiple 'Events' posts to this. So perhaps inside an 'Event' post, I can select a 'Place' post from a list to associate that 'Event' with that 'Place'. Can someone explain how I would achieve this? Would I have to look at Taxonomies? Many thanks for any advice.
Three methods: 1. Don't use taxonomies at all, just store the ID of the associated posts as post meta 2. Create a taxonomy, and remove the ability to edit/delete/create terms. Then use automation to catch the hooks for the creation, editing, and deletion of Place posts, and create/edit/delete the associated terms in the taxonomy. 3. Use the Posts2posts plugin by Scribu, though this would require learning a new API and adding an additional plugin dependency If your relational mapping is a 1 place can have many events, but one event can only have one place, then a fourth option becomes available: * Set the parent post of an event to its place
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, posts, taxonomy" }
Hook to edit an column on comments screen? At the moment I'm doing add_filter("manage_edit-comments_columns", function($columns) { unset($columns["author"]); $columns_one = array_slice($columns,0,1); $columns_two = array_slice($columns,1); $columns_one["user"] = "User"; $columns = $columns_one + $columns_two; return $columns; }); add_filter( 'manage_comments_custom_column', function($column, $column_id) { echo "Test"; },10, 2 ); Is there a way to just edit the author column instead of removing and creating my own?
There is no filter for this column. So answer is 'No'. WP_List_Table search for method column_{something} inside class of Lister. Comments List class has column_author. So kill this column, and create filter as you do now.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "comments, filters, hooks, columns" }
Remove read more I'm using 3.5.1 and WP UI plugin. When i create a post, add automatically Read More button. Like this: <p class="wpui-readmore"><a title="Read more from NEWS" href=" class="ui-button ui-widget ui-corner-all">Read More...</a></p> But i cannot use Read More options anyway on my site. Whats best way remove this option?
It sounds like your theme is using the_excerpt() instead of the_content() when displaying the post. If you want to display the full post you'll need to edit your index.php file to use the_content() instead.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, php, read more" }
wp_get_archives breakes Html5 validation I have a issue with **wp_get_archives** because it breaks my **Html5** validation. Inside validator I get this message: **Bad value archives for attribute rel on element link: Not an absolute IRI. The string archives is not a registered keyword or absolute URL.** My archive links looks like this: /> /> I am guessing that those errors are happening because spaces inside my links, now if I change my **Doctype** into **Strict** my page validates **fine**. Can someone please tell me how can I validate my page as **HTML5**? Thank you!! My wp_get_archives looks like this:`wp_get_archives('type=monthly&format=link');` Validator link
I would just remove the `wp_get_archives()` call from the document head altogether. Why even have it there? Otherwise, this isn't really **WordPress** -specific. `rel="archives"` is valid for `<link>` tags in HTML5.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 3, "tags": "wp get archives" }
remove auto generated pages from the menu? I have a simple function that adds a couple of pages to the users website when they activate my plugin. Actually there are many plugins out there that generate custom pages for the user, plugins like woocommerce do this. Question: If the user does not have a menu assigned to their theme, many times the theme reverts back to simply showing a list of pages, I think by using the wp_list_pages() function. Is there a way of automatically excluding my dynamically created pages from wp_list_pages()?
If you don't want them to ever be listed (using wp_list_pages at least) then you could hide them using a filter add_filter('wp_list_pages_excludes', 'my_page_excludes'); function my_page_excludes() { // the array should contain the page ids you want to exclude return array(1,6,7,12); } This will stop them from displaying in anything that lists pages using WordPress template functions - including widgets etc. If the user may ever want them to be visible then they'd have to use a custom menu - or you'd have to provide an option to display them.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp list pages" }
How to save the same post in multiple blogs? I would like to write my post in one of the my 3 blogs and the same post will be published in the other two blogs. How can I do that?
You can hook on `save_post` or `publish_post` hook in each post and publish in other blogs. You must use the function `switch_to_blog()` to switch in other blog and then use `[wp_insert_post()][2]` to save a post inside this blog; do this for each blog. Alternative is you search for a plugin, there doing this; like Multi Post. I don't know if is the right and a good plugin. I had use the search on www.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "posts, blog, post duplication" }
Handling URLs in WordPress application We have a web application that we run inside of WordPress in order take advantage of WordPress's authentication. To make this work, we created a template type for our application that simply includes our application's start page. While a little bit of hack, this works great, except for once aspect - all the relative URLs now use the WordPress's page as its base, instead of the actual path to the resource. For example, if my application's page is at ` a relative link to a stylesheet would result in ` as expected. Unfortunately, this is not the actual location of the stylesheet. The actual location of the stylesheet is something like this: ` How should I go about linking to this resource in my web application if the base URL won't accurately reflect the location of the resource? Note: I am not able to use absolute links as we develop locally, which obviously does not have the same directory structure as the WordPress site.
`../directory1/directory2/directory3/css/stylesheet.css` should get you there if I am reading your description accurately. However, I would be very cautious using relative links in WordPress. They do not always work the way you'd expect because a lot of 'directories' don't actually exist. They are fabricated by WordPress and `mod_rewrite`. The two conspire to lie about filesystem structure. For example, there is no ` A relative link on that page would be broken. You are better off using `bloginfo` or `site_url` and constructing absolute URLs. `site_url` would the function to prefer. $url = siteurl('/directory1/directory2/directory3/css/stylesheet.css');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "css, javascript, urls, links" }
How to enqueue script based on post category? I have scripts for various little tools I have made using some js and html. I want the js to load only on specific single posts in side a specific category. I have tried the following code and it does not work. I removed the "if" statement and the script does run and work so it's a matter of fixing the if statement. Here's what I've got so far, if ( is_single() && in_category( 'mouse' ) ) { wp_enqueue_script( 'mousescript'); } Thank you very much for any and all help, it's greatly appreciated!
Inside your theme's `functions.php` add something like this: function my_conditional_enqueue_script() { global $post; if (is_single($post->ID) && in_category('mouse', $post->ID)) { wp_enqueue_script('mousescript'); } } add_action('wp_enqueue_scripts', 'my_conditional_enqueue_script'); Also, make sure you use `wp_register_script` before you attempt to enqueue.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "shortcode, javascript, wp enqueue script" }
Subpage Conditional I am looking for a way to write a condition for a subpage...in other words `if` we're on the subpage "duck" then do something...`if` not do something else. I found some code I thought would work, but it shows up on all of the pages under a given parent page, not just on its individual page...I'm only trying to target the individual page. This goes in functions: // Subpage Shortcode function is_child($page_id_or_slug) { global $post; if(!is_int($page_id_or_slug)) { $page = get_page_by_path($page_id_or_slug); $page_id_or_slug = $page->ID; } if(is_page() && $post->post_parent == $page_id_or_slug ) { return true; } else { return false; } } This is my `if`: if (is_child("Youth")) { echo "duck"; } else { echo "something else"; } Thanks, Josh
I don't know what I was thinking earlier...I guess somehow I was thinking that `is_page` wouldn't work for my child page, but I was over-thinking...this is my final code: <?php if (is_page("duck")) { echo "do something"; } else { echo "something else"; } ?> I know, I know it's so simple, but it works - guess I was just having a brain fart. Thanks, Josh
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages, conditional content" }
How to load javascript on custom page template? I have a custom page template where I would like to load some javascript. I suppose I could always include the javascript in the actual file, but that seems ugly. Is there any way to identify if WordPress is loading my custom-page.php file so I can enqueue the script only on that page? It should work dynamically, so checking page id is not an option.
You can use **`is_page_template`** to check if you template is being used and load your scripts based on that ex: Add this code to your functions.php: add_action('wp_enqueue_scripts','Load_Template_Scripts_wpa83855'); function Load_Template_Scripts_wpa83855(){ if ( is_page_template('custom-page.php') ) { wp_enqueue_script('my-script', 'path/to/script.js'); } }
stackexchange-wordpress
{ "answer_score": 28, "question_score": 12, "tags": "pages" }
Can I hook into user registration *before* a user is created? I want to limit registration based on the domain associated with their email address. I was looking at the `user_register` action hook, but it fires _after_ the user is already inserted, which, although it could be hacked into working, is less than ideal. I want to preempt rather than retroactively remove invalid users. I've looked through the source in `wp-includes/user.php`, but nothing in there looks to be helpful. I did notice the `pre_user_email` filter, but that doesn't seem to offer any options for doing anything useful since I can't see a way to do anything with that.
You're looking in the wrong place. When a user first attempts to register, their username and email is processed and sanitized inside the `register_new_user()` function in `wp-login.php`. This is where you want to do your filtering. Before the user is created, WordPress will pass the sanitized user login, email address, and an array or errors through the 'register_post' action. If there are any errors after that, then the user is not added and they will see the errors in the UI. So the following _untested_ function might help: function prevent_email_domain( $user_login, $user_email, $errors ) { if ( strpos( $user_email, '@baddomain.com' ) != -1 ) { $errors->add( 'bad_email_domain', '<strong>ERROR</strong>: This email domain is not allowed.' ); } } add_action( 'register_post', 'prevent_email_domain', 10, 3 );
stackexchange-wordpress
{ "answer_score": 14, "question_score": 7, "tags": "user registration, limit" }
W3 Total Cache "Preview mode could not be disabled" I receive the message: > Preview mode could not be disabled. Please run chmod 777 /wp-content/w3-total-cache-config-preview.php to make the configuration file write-able, then try again. I have chmodded the file to 777 and the error message remains.
W3 Total Cache plugin basically removes `w3-total-cache-config-preview.php`, when disabling the preview mode. In `/wp-content/` folder, please check if you have a file named `w3-total-cache-config.php`. * If it exists, please compare it with `w3-total-cache-config-preview.php` file. * If both have the same content, rename it to `w3-total-cache-config-preview-backup.php` and reload your site's `/wp-admin/admin.php?page=w3tc_general`. * If both have different content, please copy all the content from `w3-total-cache-config-preview.php` to `w3-total-cache-config.php` and then rename the `preview` file. * If it doesn't exist, please rename `w3-total-cache-config-preview.php` to `w3-total-cache-config.php` and then reload your site's `/wp-admin/admin.php?page=w3tc_general`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "errors, plugin w3 total cache" }
How to remove a settings section from the Theme Customization API preview pane? I am currently working on a theme that uses the Wordpress Customization API and I need to remove some pre-existing sections from the customization preview pane. Is there somewhere like a global variable holding an array of the sections perhaps (in true Wordpress style) I can unset the navigation section in particular? Please see attached image for what I am talking about. I've circled it in red. !enter image description here
Just call `remove_section` method of the `$wp_customize` object: add_action( 'customize_register', 'wpse8170_customize_register' ); function wpse8170_customize_register( WP_Customize_Manager $wp_customize ) { $wp_customize->remove_section( 'section-id-to-remove' ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, settings api, core" }
Deep customization of the comment form? I've been handed over a design to translate into WordPress plugin & theme. My question is regarding building a custom comment form. The design used some custom scripts on the comment submit button. It handles 'submitting...' button state, animations, and checks. And it uses an anchor tag `<a>` with jQuery's `.bind` to submit the form. I noticed that the `comment_form` function of WordPress did not offer a solution to change the submit button. I only needed to remove it as I'm handling it myself. What made it worse is that WordPress has hard coded `<input name="submit">` into the button, which made it impossible for jQuery to call `.submit` (more details on this issue here: < So just hiding this button with CSS won't work. If I prefer not to use the `<input type="submit">` button of WordPress comment form, do I have any options to build my own button? Thanks.
This is hard. Output buffering could solve that: add_action( 'comment_form_field_comment', 'ob_start' ); add_action( 'comment_form', 'wpse_83898_replace_submit' ); function wpse_83898_replace_submit() { $html = ob_get_clean(); # do some magic echo $html; } Just an idea, not tested.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "comments, comment form" }
How can I add the custom taxonomy categories to the posts and pages? I'm trying to build new wordpress plugin. Additional to the default wordpress categories box in the publishing screen of posts and pages, I want to add another box for custom taxonomy categories , How can I do that ?
All what you need to do is just pass required post types as array in the second parameter for `register_taxonomy` function call: add_action( 'init', 'wpse8170_init' ); function wpse8170_init() { register_taxonomy( 'my-taxonomy', array( 'post' ), array( ... ) ); // or call this function if your taxonomy is already registered register_taxonomy_for_object_type( 'my-taxonomy', 'page' ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, categories, custom taxonomy" }
different levels of nested comments per page I am working on a wordpress site that usually allows three levels of nested comments. But I would like for (at least) one specific page to allow only one level of comments => no nesting. How can I do that? edit: requested clarification: I can identify this page by the used page-template.
Please reference the Codex entry for **`wp_list_comments()`**. This function includes a `'max_depth'` parameter in its args array. On the specific page in question, simply call: <?php wp_list_comments( array( 'max_depth' => '1' ) ); ?> If you need more specific help, please clarify your question to indicate how you would _identify_ the specific page in question. By title/slug/id? By Page Template? Some other way?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "comments, threading" }
Generate aggregated feed from member blogs I currently manage a multisite installation with 7 member blogs. We need to produce a combined RSS feed of news from all 7. Currently we use Feedwordpress to syndicate 6 blogs into blog number 7. This isn't working out because we're duplicating content in the db. Ideally I need a cached feed to reduce server load (the feed is subscribed to via high-traffic portals). What's the best way of doing this? I've considered Yahoo Pipes, but how about using Wordpress transients to cache a query across all member blogs, and somehow publishing this as RSS? JSON could be an option, but RSS is probably preferred.
Here's one option we use for a high volume global RSS feed. It's worked out really well for us and has lower load times than trying to do some runtime combination. < <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, rss, feed, json, cache" }
similar of my posts in all over the internet sites and blogs i asked here in WordPress first and next asked there in webmasters Stack but i think here is very useful for WordPress users but close my question. I'm using the similar posts plugin < but I want the similar posts in all over the internet. is there any tools that when someone copy and paste my article in their own site alert to me? some of the bloggers don't link to my articles and i want to
You won't find a Wordpress plugin to do that - you need to use < or something similar; Good luck getting people to remove your content though, most of them will be automatically generated heaps of junk.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -6, "tags": "plugins, customization, tooltip" }
How do I get the Social Media Plugin to show up in my Twenty Eleven child theme's header? Being totally new to WordPress and (extremely) rusty with PHP, I'm having a difficult time figuring out how to add the Social Media Widget to my site's header. I'm using the Twenty Eleven theme, as I need the site to have no sidebars. Ideally, I'd like the social media icons to show up either above or below the site search box (image redacted for client's privacy): !Widget position I've tried tutorials and have looked all over the web, but haven't been able to find anything that applies to my rather specific situation. Is this just too hard to do with this theme, and should I just go ahead and use icons instead of a widget? I'm pretty sure I can do this in `functions.php` and `header.php`, but how?
You can throw a widget anywhere into your template (if you do not want to use sidebar drag + drop) by calling `the_widget`. In your case you would need to put this in the appropriate spot (maybe header.php or menu.php), you will have to figure out where you want it. the_widget('Social_Widget ', $instance, $args); Please view the ref page on what can be used for `$instance` and `$args` (for example this is where you put the widget title, parameters, etc): < You should just use a register a new sidebar though , on account of this plugin have _tons_ of options.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "headers, theme twenty eleven" }
Better in the long run to use post date or custom taxonomy to sort/separate posts by year? I have custom type posts that I need to separate by year as the posts are entries in an annual contest. Would it be better in the long run for efficiency of queries, speed, etc to simply use the built in post date or set up a custom taxonomy to group these posts into years? I notice that post_date is stored in the wp_posts table, so it seems to me that this would make for speedier queries than having to reference the separate taxonomy table. Thank you!
I can't see any practical reason to use a custom taxonomy here. You can already query posts by year using OOB query and archive stuff (see this Codex article about the "year" WP_Query parameter, and this one about the "yearly" mode for wp_get_archives()). If you're asking purely about performance, I'd consider this kind of thing (a single table query vs. a simple join) a "micro-optimization". For 95% of WordPress sites, it won't make any visible difference. And if your site is at the point where you need serious tuning, there are probably better places to focus energy (like identifying _really_ slow queries, and having a good caching strategy). Hope that helps?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom taxonomy" }
Accessing + retrieving custom database in WordPress I am looking for something really simple(?). I am using WordPress as a CMS. I created a new page in which I added a form (questionnaire). Inside WordPress' database (the same database in which all WordPress data are), I created a new table called "ExampleTable". Now I have 2 questions: 1) How can I insert data from the form into that custom table? 2) Is is "okay" to add a custom table (which has nothing to do with WP inside WordPress' database, or should I create a new database?) Thanks :)
It is OK. And you can access this table with standard way, throught wpdb To insert data to your table use this code: global $wpdb; $wpdb->insert( 'exampleTable', array( 'column1' => 'value1', 'column2' => 123 ), array( '%s', '%d' ) ); To breafly explain what this code mean. WordPress sanitizes values before inserting them into database (to prevent database being compromited by SQL injection.). First line defines table to inser value. Secon array contains col names and value being inserted. The third array contains type of value to insers. %s stands for string, %d stands for int (digit). You can read more about $wpdb->prepare in the codex. It is well explained in there.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, database" }
How to update avatar in buddypress programmatically? How to update avatar in buddypress programmatically? I have a script, which gets the image url and I want to update the url in the database, so that that image will will be avatar of the user.
WordPress does not save the value of the avatar image in any database. It looks in the file system for avatar image and displays it on the website. So, I am planning to download the image to the server, which is running the WordPress (BuddyPress). I need to create a directory with the name same as user ID, in the directory /wp-content/uploads/avatars/ and put two images, one as -bpfull.jpg (full image) and -bpthumb.jpg (thumbnail image). And these images will be displayed for that user, automatically.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "buddypress, avatar" }
Auto log in hook is requiring a page refresh I have a simple auto log in hook that looks like the following: function auto_login() { if (!is_user_logged_in()) { //Removed some code for brevity. $user = get_userdatabylogin($domainName); if ($user != null) { //Set the auth cookie. wp_set_auth_cookie($user->ID, false, null); //Set the current user (this will also set WP objects at the global level) wp_set_current_user($user->ID); } } } add_action('init', 'auto_login'); This code does work, but, in order to get the admin bar at the top of the page it requires a page refresh. This makes me think that I'm not getting some global objects populated early enough in the Wordpress page life cycle. Should I be calling this method somewhere else besides `init`?
Maybe it is too late to hook on init. Try set_current_user or some earlier hook. List is here: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, hooks, security, user access, authentication" }
How to show animal lineage/pedigree in WordPress? I need to show the pedigree or lineage of an animal in my wordpress site. Currently I have the animals set up as custom post types, with data inserted using the amazing Advanced Custom Fields plugin. I can't really find any good plugins for this that do it well, especially those that can output standards compliant HTML and usable CSS without tables. Even if it's a list item, that's cool, I can work out the CSS. But what would be the best way of inputting an animal's lineage / pedigree, up to 4 levels deep (eg: 1)Parents 2)Grand parents 3)Great Grand Parents 4) Great Great Grand parents Really appreciate your help on this one! Rick
From Wikipedia > **Animalia** is the _taxonomic_ kingdom comprising all animals (including human beings). From the Codex > **Taxonomy** is one of those words that most people never hear or use. Basically, a taxonomy is a way to group things together. > > For example, I might have a bunch of different types of animals. I can group them together according to various characteristics and then assign those groups names. This is something most people encounter in biology classes, and it is known as the Linnaean Taxonomy. > > In WordPress, a "taxonomy" is a grouping mechanism for some posts (or links or custom post types). Just use Categories -a type of taxonomy- to group and categorize them.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom field, advanced custom fields" }
create functions based on array values I am working on a function set that will add a piece to each custom post type on a site. Since I won't know what CPTs are registered, I wrote a function to get them all (simple). However, I now need to create a function for each value in an array (a small settings page) to properly finish this off. here's my array example: $types = array ('type_a', 'type_b', 'type_c'); so I basically want to generate a function called `type_a_page`, `type_b_page`, etc within the same overall class. **UPDATE** I realized this code is only a small part and doesn't explain why I'm trying to achieve this. Here is the code base in it's entirety <
Can you use the __call PHP class functionality? < You could use __call in your class and call your function for grabbing the page types and check them against the $name (first) argument and running custom code against it. For instance: __call ($name, $args) { $types = array ('type_a', 'type_b', 'type_c'); if (in_array($name, $types) { // custom code } } UPDATE: Response to gist. So using __call as a method on your class, on line 90 of your gist, you would use: $this->$slug();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, array" }
Changing MySQL password via WHM - does this affect WordPress? For security, I changed the CPanel password for an account via WHM. There's a checkbox option that says "Sync MySQL password with account password." If I go ahead and change the password, does that create a problem for WordPress that's installed on that domain?
Actually, just found out that it doesn't. Here's the doc from Cpanel directly < Sorry, now that I know the answer, this definitely isn't WordPress related.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "mysql" }
PHP Warning: preg_match() expects & PHP Warning: strip_tags() I got this error log, do you know what is this and how can i fix this? [31-Jan-2013 22:01:25 UTC] PHP Warning: preg_match() expects parameter 2 to be string, array given in /home/xxx/public_html/wp-includes/formatting.php on line 608 [31-Jan-2013 22:01:25 UTC] PHP Warning: strip_tags() expects parameter 1 to be string, array given in /home/xxx/public_html/wp-includes/formatting.php on line 968
You are calling `remove_accents()` and `sanitize_title_with_dashes()` with an array as first argument somewhere. This is wrong, use a string instead. Install the Debug Bar plugin and look at the backtrace to see where the broken code starts.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
Minimum Template Files for Theme Development WordPress has minimum theme template files as * style.css * index.php and also some other files as listed here. If the theme developer wants to build theme with less bells and whistles, what are some of the template files which should be included at minimum? There isn't any guidelines in the WordPress codex. Only thing that you can find is what files and when to include them. For making use of most of the WordPress functions without any conflict, there doesn't seem to be specific number mentioned for number of template files. So how many files should be there when you build a theme from say raw html template?
To have the theme listed: * `style.css` With at minimum this: /* Theme Name: Minimum Theme Description: Test Author: Test Version: 1.0 */ For the theme to be functional: * `index.php` `index.php` must have a post loop, so this would be the bare minimum functional `index.php` <html> <head><?php wp_head(); ?></head> <body> <?php if ( have_posts() ) { while ( have_posts() ) { the_post(); the_title( '<h3>', '</h3>' ); the_content(); } } wp_footer(); ?> </body> </html> index.php is the defacto fallback for all template files WordPress might look for. All the rest are entirely optional, though I advise that you use them. For more information on which templates are possible, see here: <
stackexchange-wordpress
{ "answer_score": 24, "question_score": 16, "tags": "theme development" }
Roll my own theme or customize an existing one I just want to know whether I should roll my own theme from scratch or I should customize an existing one like twenty twelve. Reason I ask is I wanted to know whether there are any best practises I may be missing if may be missing from these themes ir I roll my own. Also I find that there is a lot of bloat even for a theme as simple as twenty twelve and hence ind myself removing a lot of it as I'm building my theme. The site I am currently building is www.laminsanneh.com Thanks in nadvance
You might look into the concept of using **child themes** to roll your own theme. A **framework** like **Genesis** comes out with regular updates and has a starter theme that can be quickly built upon. I would take the time to **roll your own** so that you can know the ins and outs of your own website. If you tweak an existing theme that has bloat you may have things break later and find that fixing issues is more of a headache. There are different **frameworks** and starter themes out there that will be better to start with than Twenty-Twelve. Here is one example: < There are also responsive ones available like this: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "theme development, themes, theme twenty twelve" }