INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to add an attribute data-slug = "$specfic_page_slug" in WordPress menu item? I want to add custom attribute in WordPress menu item which has specific page slug. like this - <li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-101" id="menu-item-101"><a href="javascript:;">Meet The Therapist</a></li> Change to <li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-101" id="menu-item-101" data-slug="$specific_page_slug"><a href="javascript:;">Meet The Therapist</a></li> Thanks in advance.
It would be easier to add this on a menu _link_. The attributes for each link pass through the `nav_menu_link_attributes` filter. You should be able to use it to add a custom one, along the lines of (not tested): add_filter( 'nav_menu_link_attributes', function( $atts, $item ) { // check if $item is what you need $atts['data-slug'] = 'something'; return $atts' }, 10, 2); To change the whole list items you would have to use more general `walker_nav_menu_start_el` filter, which only passes string you would have to cut up more messily.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "menus, slug" }
How to delete wordpress menu I'm designing my product pages, but at every page at the bottom, I find this: ![enter image description here]( Does anyone know how to delete this?
Take a look in your widgets. Appearance > Widgets, and remove the ones you don't want.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "sidebar" }
Gather posts into a cart/lightbox and share with another user Ok I've almost completed a Wordpress site that is a multi-user Image Library. This is a **private** site, where users **must** be logged-in to view it. The average user **cannot** get to the backend (wp-admin) **at all**. They are kept at the front end. So my question is this: What is a clever way to enable a user to be able to 'add' a post (each post is an image - featured image) to a kind of 'cart' or 'lightbox' that is attached to themselves as a user (eg. the cart/lightbox is still there when they log back in - think iStockphoto) and **then** be able to share this 'cart' or 'lightbox' **via email** with someone else? ^See note below. Tricky points bonus: I'm hoping that users can have more than one lightbox ('cart'), although this may not be a game-killer. ^ Note - sharing this link via email will **not** make anything publicly available. **The sharing link will only work for other users who are able to login**.
I think you might have to modify the plugin, fork it, if you like the rest of it's functionality. Then add functionality that when you "favourite" a post/image, instead of adding it to your favourites you get a list which collection you want to add it to. All of these collections could have their own url like www.mysite.com/user/collections/collection-name .
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, images, users, user meta" }
Why Wordpress CMS uses an array in wp_options instead of a field for Sticky posts? In WordPress we can pin (sticky) a post. Wordpress uses an option in `wp_options` table named 'sticky_posts' with an array list of sticky posts! As a normal condition WordPress should add a field named 'sticky' in `wp_posts` table. My question is why does WordPress use this way and what are Pros and Cons of this method?
Sticky posts are a feature of the home page, not of the post. The post has no reason to "know" it is sticky. The home page OTOH do not have any formal form of storage and therefor traditionally options related to it are stored in the options table
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "sticky post" }
Custom admin logo not showing after wordpress 4.5 upgrade I have just upgraded to wordpress 4.5 and now my custom logo for the admin doesn't work, the theme which I built uses the following in the theme functions.php: /* change admin logo */ function my_login_logo() { ?> <style type="text/css"> .login h1 a { background-image: url(<?php echo get_field('logo','options'); ?>); background-position: center center; background-repeat: no-repeat; background-size: cover; width: 320px !important; height: 99px !important; margin-bottom: 20px !important; } .login form { margin-top: 0px; } </style> <?php } add_action( 'login_enqueue_scripts', 'my_login_logo' ); I cannot find a work around for this, can anyone help?
I think you have the logo called from the Theme Options try updating your Theme Options alternatively you have many plugins that can help you achieve that. Like: < You can always refer to the Wordpress Codes <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, wp admin" }
Category next page link not working When I go to a category page and it lists the posts that are in that category, it lists 10 per page. At the bottom of the page it has the link for next page, but that link returns a 404 error. The first page of the category which works fine is < But when I click next, or directly on a page number, the url is < I can't figure out how the page 2 link should be formatted or where to change the incorrect format that it is using. Any help greatly appreciated. Brendan
**I may be jumping to a conclusion without seeing your code first.** But I believe this may simply be because the way have your permalinks setup. If you go to your `dashboard` then `settings->permalinks` and change the option to anything other than `Plain`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
Archive for a Taxonomy of a Custom Post type I have a situation like this: /disrupt-founders/disrupt-categories/help-me-be-healthier/ What I am wanting to do it create an archive page that is unique for the Taxonomy based on the Custom Post type it's part of. This is what I tried but it didn't work: taxonomy-disrupt-founder-disrupt-categories.php I know this will effect all the Taxonomies taxonomy-disrupt-categories.php Any ideas on how I could do this?
If I am understanding you have a taxonomy that is shared across multiple post types? And you want to make a custom template for each post type using the Wordpress's templating system. Which isn't possible. What you could do is add conditionals to your `taxonomy-disrupt-categories.php` to check what the current post type is and load different template parts depending on which post type it is. eg: if('disrupt-founders' == get_post_type()) { // disrupt-founders unique template get_template_part('content', 'founders'); } elseif('another-post-type' == get_post_type()) { // another unique template get_template_part('content', 'another'); } else { // default template get_template_part('default', 'default'); } < <
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "custom post types, custom taxonomy, templates, archives" }
ACF scheduled repeater fields 1. Is there a way to schedule repeater fields to appear on the front end at start date & time and be taken down at end date & time? 2. Is there a way to have those repeater fields deleted from the admin at end date & time?
1. Yes. You could keep other fields to specify the timestamp of the start and end dates. You then compare the timestamp on the front-end. If the current timestamp is larger than the start date and smaller than the end date, display the fields. 2. Yes, kinda. I don't know if there's a straightforward way to do it, but you can probably write a function to check the repeater fields from the `postmeta` table and delete them using delete_post_meta.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "advanced custom fields" }
Using depth=n in wp_list_pages I'm wondering what is the proper way to use depth n in wp_list_pages. I currently have a menu in my sidebar that goes 4 levels deep but I'd like to prevent levels 3 & 4 from displaying. The codex says: > **'depth'** > > (int) Number of levels in the hierarchy of pages to include in the generated list. Accepts -1 (any depth), 0 (all pages), 1 (top-level pages only), _**and n (pages to the given n depth)**_. Default 0. I've tried: wp_list_pages('child_of=124&title_li&depth=n(2)') wp_list_pages('child_of=124&title_li&depth=n2') I can't seem to find any examples on how to use depth in this instance.
`depth=n2` should be `depth=2`. `n` is just a "placeholder" and should be replaced by the actual integer value of your choice
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, wp list pages" }
How do I retrieve a users' last 5 posts? How do I retrieve a particular users last 5 blog posts? Currently, I am trying the following approach, but it seems that it is retrieving the actual post titles and permalinks: <?php $allUsers = get_users('orderby=post_count&order=DESC'); ?> When I do a `var_dump` on `$allUsers` I see a lot of information (including username and password info). I am looking specifically for the titles of the posts they have written along with the permalinks for those posts.
Basically, when you want get posts, you should think about `WP_Query`. It's already in the docs for your question. You can get posts by an author like this $query = new WP_Query( array( 'author' => AUTHOR_ID, 'posts_per_page' => 5 ) ); You can even get posts by more than one author, like this $query = new WP_Query( array( 'author__in' => array( AUTHOR_ID, ANOTHER_AUTHOR_ID ), 'posts_per_page' => 5 ) ); Because WP_Query is sort by date and order descending by default so you don't need specify that information.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "posts, author, users" }
How do I require a file in a shortcode? I have a shortcode that is working and displaying the problem is that it jumps to the top of the page. If I have any text or other shortcodes above it in the page editor they will be displayed below this one on the front end. add_shortcode('shortcode_exsample', 'shortcode_name'); function shortcode_name(){ return require_once ( plugin_dir_path(__FILE__) . '/shortcode_file.php');; }; There is about 259 lines of HTML in the `shortcode_file.php` file that is why I am doing it this way rather that just having it inside the function. Any idea on why this is happening would be great. Thank you.
Shortcodes are expected to return content, not echo it out. So if your `shortcode_file.php` file is straight html, it's considered being echoed. If that's the case, you could do something like : function shortcode_name(){ ob_start(); require_once ( plugin_dir_path(__FILE__) . '/shortcode_file.php'); $content = ob_get_clean(); return $content; };
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "shortcode" }
Foreach implode issue I have this piece of code that gets the values of meta boxes in WordPress. $guiones = rwmb_meta( 'mb_guionistas', array( 'multiple' => true) ); $pieces = array(); foreach ($guiones as $item) { $pieces[] = '<a href="' . bloginfo('url') . '/?p=' . $item . '" title="">' . get_the_title( $item ) . '</a>'; } echo implode(', ', $pieces); The problem is that the result it doesn't just show a comma separated values but adds the blog URL at the beginning. I'm pretty sure is something related to how `$pieces` is structured. Can you see any problem on the code? ![enter image description here]( Attached the results of adding 2 values.
Change it to: <?php $guiones = rwmb_meta( 'mb_guionistas', array( 'multiple' => true) ); $pieces = array(); foreach ($guiones as $item) { $pieces [] = '<a href="' . get_bloginfo('url') . '/?p=' . $item . '" title="">' . get_the_title( $item ) . '</a>'; } echo implode(', ', $pieces); ?> `bloginfo()` echos values while `get_bloginfo()` returns values.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
How can I get .html URL suffixes in permalinks? I have never seen that the page ending up in wordpress with ".html ending", but some how i also feels that this page/blog is build upon wordpress - < My Questions: If indeed this is a wordpress system how come ".html" is coming in the URLS end.
Short: You don't need `.html` ending. `.html` ending can be easily archive by setting in Options > Permalink or using plugin like Custom Permalink. But that's just personal style. Having `html` or not is now just different in length of URL. For me, the shorter one is better. It's has no effect on SEO score. In the past, `.html` ending is some kind to distinguish between archive and single/page, but now the Search Engine is smart enough to now the page is archive or single. So why don't we use shorter URL.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, url rewriting" }
Change "Display Site Title and Tagline" checkbox text in theme customizer Am making a custom theme, and in the Theme Customizer, will it be possible to change that checkbox under Site Title to something like "Display Site Title instead of Logo"? (i have removed that tagline field and added an image upload field for Logo) or, remove that checkbox from there? which one is easier? thanks!
You will need to de-register that control. It will look like this: /** * Remove parts of the Options menu we don't use. * * @param WP_Customize_Manager $wp_customize Customizer manager. */ function de_register( $wp_customize ) { $wp_customize->remove_control('display_header_text'); } add_action( 'customize_register', 'de_register', 11 ); For more information, this Theme Customization is a good start.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "theme customizer" }
Where does WordPress register default scripts like jQuery? I'm figuring out the ins and outs of WordPress. I know that WordPress sets some default filters and actions in /wp-includes/default-filters.php, but where does it register its scripts like jQuery? We are all able to set jQuery as a dependency or just enqueue it in our themes, but where does WordPress register it? Any help would be much appreciated!
WordPress registers jQuery in the `wp_default_scripts()` function, which is found in `wp-includes/script-loader.php`. // jQuery $scripts->add( 'jquery', false, array( 'jquery-core', 'jquery-migrate' ), '1.11.3' ); $scripts->add( 'jquery-core', '/wp-includes/js/jquery/jquery.js', array(), '1.11.3' ); $scripts->add( 'jquery-migrate', "/wp-includes/js/jquery/jquery-migrate$suffix.js", array(), '1.2.1' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, plugin development, wp register script" }
Shortcode templates I don't know if this is the correct way to approach this, but here it goes. I'm working on Visual Composer (but could be vanilla WP), and I'm trying to implement a shortcode which generates another bunch of shortcodes. Somewhat a template shortcode. For example: [test title="some title"] Could be converted to: [another_shortcode] [title]some title[/title] [get_posts total="5"] [/another_shortcode] Which will be further processed until the HTML is generated. The thing that I'm trying to achieve is to tell the user to use some shortcodes which will generate a concrete Visual Composer shortcodes. This way I'm **abstracting away the layout** and if there are lot's of pages with a given layout they can be changed changing the shortcode. Does make any sense? Is it doable?
Using `do_shortcode` within a shortcode does the trick of parsing the inner shortcodes. More information here: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode, visual editor" }
Extra themes - ok or bad? I know I am a newbie here, but I'm just wondering, if you keep extra themes in your Wordpress setup, will it add bloat to your site? Can these other themes provide a security risk even if they aren't activated? I imagine it's best to delete any theme that aren't in use, but I'm noticing a lot of unused themes in other setups, so perhaps it doesn't really matter? Thankyou!
Any extra code on your server is a theoretical security risk. Instead of checking each plugin and theme if they are security risk even if they are not active, it is much easier to just delete them. This of course should not prevent you from backuping them first in case you will decide that you need them in the future ;)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "themes, security, server load" }
Set cookie with taxonomy name I know that a should set a cookie before any output. I want to set a cookie with the actual page's taxonomy name. To get the taxonomy name I am using `get_query_var('taxonomy)`. The problem is: If I hook the cookie creation into `init` the `get_query_var` returns empty. If I hook it too late I get a `headers already sent` error. How can I accomplish this?
Try hooking on the `get_header` action hook. That's the last action hook before headers are output.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "cookies" }
How to support multiple search terms query within one process? For **multiple** search terms; `?s=hello+world` Wordpress work find **"hello world"** like `the_title` , `the_content` posts! * _And, if our post title`Hello Anna` wordpress does not get one results!_ > I want to use all keys: > > **"hello world"** , **"hello"** , **"world"** **Maybe** `array('hello world','hello','world');` but it exceeds my exp.! Is it in a single loop may be able to divide the query and send multiple queries? Is there someone who can help on the subject? **e.g.** `?s=`, `$_GET` > Wanted something must have been like to call more results for multiple queries!
Fixed: Search and result the all keys; <?php $the_keys = preg_split('/\s+/', str_replace('-',' ',get_query_var('s')),-1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); $total_keys = count($the_keys); $the_query = new WP_Query(array('post_type'=>'nothing')); if($total_keys>1){ for($i = 0; $i<=$total_keys; $i++) { $the_query_mask = new WP_Query(array('s' => $the_keys[$i])); $the_query->post_count = count( $the_query->posts ); $the_query->posts = array_merge( $the_query->posts, $the_query_mask->posts ); } } else { $the_query= new WP_Query(array('s' => get_query_var('s'))); } if ($the_query->have_posts()) : ?> Note: **`'post_type'=>'nothing'`** just need array merge!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "wp query, filters, search" }
How can I override print_embed_sharing_dialog() in Wordpress 4.5 Is there a way to hook into print_embed_sharing_dialog() and modify its output without hacking the core? We -really- dislike the new HTML output and Wordpress output options and want to display just one simple share link.
You can't modify the core function's output, but you can replace it with your own function by unhooking it from `embed_footer` and adding your own function with custom output: remove_action( 'embed_footer', 'print_embed_sharing_dialog' ); add_action( 'embed_footer', 'my_custom_sharing_dialog', 9 ); function my_custom_sharing_dialog() { // write your own dialog html here } (I added it back with a priority of 9 to insure that it gets printed before the `print_embed_scripts`.)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "embed, sharing" }
Change to nofollow tag in wp-login.php In wp-login.php default is: <meta name="robots" content="noindex,follow"> I want to change it to: <meta name="robots" content="noindex,nofollow"> Is there an easy way or script to change this?
Extending @prosti answer, WordPress add it using action `login_head` in `wp-login.php` itself. add_action( 'login_head', 'wp_no_robots' ); You can remove this action in theme/plugin and add your own action with custom callback function. Example:- //Keep priority 9 so we can remove WordPress action that is on 10 add_action( 'login_head', 'custom_no_robots', 9); /** * Custom robot tags */ function custom_no_robots() { remove_action( 'login_head', 'wp_no_robots' ); echo "<meta name='robots' content='noindex, nofollow' />\n"; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "login, nofollow" }
Custom link for wp_insert_post Is there any way to add a custom URL to the `wp_insert_post` function? $my_post = array( 'post_title' => wp_strip_all_tags( $_POST['post_title'] ), 'post_content' => $_POST['post_content'], 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array( 8,39 ) ); wp_insert_post( $my_post );
You can use `post_name` parameter. $my_post = array( 'post_title' => wp_strip_all_tags( $_POST['post_title'] ), 'post_content' => $_POST['post_content'], 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array( 8,39 ), 'post_name' => 'your-url' ); wp_insert_post( $my_post );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "customization" }
How to reset WP page url with deleting the variables In my unsubscribe script there is this command: < after the unsubscribe I like to change the url into < But WordPress does not accept again header(). Also try echo esc_url( remove_query_arg( 'email' ) ); That works but does not rewrite the url. Question: How can I rewrite the url as written above
Why not create an if statement to check if the email arg was passed, if so, redirect to the URL without the email. Something like: if ($_GET['email']) { //do unsubscribe stuff wp_redirect(' exit; } Unsubscribed!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "url rewriting" }
Form not working as it should in WordPress, but in a normal HTML site it does I am in need of help. I have a website, which has a form to fill out (simple form, that calls a PHP function and some other JQuery libraries). It is made in an ordinary HTML file, and works well on my servers. Now I have a new site made in WordPress. The site works great and everything, but the form does not. I do not have so much experience with WordPress to tell what is wrong. It does show, but it does not function properly. Can somebody please check it out? The biggest problem is the button, where you choose how to »pay«. It does actually redirect you, but it should happen twice, but it does not… This is the site: < I just copied the code into the past of the site and of course I uploaded the required files to the server, so that it has all the files and functions that it needs. This is my code: <
So I finally found the solution to the problem. It was in the validate.js function. I corrected the error by calling the outside functions of validate.js and jquerry: script type="text/javascript" src=" script type="text/javascript" src="
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, jquery, forms" }
Include file from higher level I created a custom page template where I want to present some data specific for that page. The file is placed in > wp-content/themes/themename/page-templates In that file I want to include another php file from the parent directory. That file is placed in: > wp-content/themes/themename So in the file i write: <?php include('../Sorting.php');?> But I receive an error saying the file doesn't exists. > Warning: include(../Sorting.php) [function.include]: failed to open stream: No such file or directory I'm not that much into wordpress so I theorized that it was something to do with the include function but it works fine if I put the files in the same folder though.
You need to use `get_template_directory()`, this function will return local server path of you template and then you can use that path to access required file. So in your case it would be something like below: include get_template_directory() . "/Sorting.php"; PS: Mind the spelling of your file.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "directory, include" }
conditional based upon the count of current user's published custom posts I have this conditional snippet that does something is the current user has not published a normal post. But I'd like to change it so that it counts a custom post rather than a normal post. <?php if ( 0 == count_user_posts( get_current_user_id() ) && is_user_logged_in() ) { ?> do something <?php } else { ?> do something else <?php endif; ?> This is what I have tried... <?php if ( 0 == count_user_posts( get_current_user_id(), "CUSTOM_POST_TYPE" ) && is_user_logged_in() ) { ?> do something <?php } else { ?> do something else <?php } ?> But it doesn't seem to work
After further testing it seems my attempt (in my question) works! <?php if ( 0 == count_user_posts( get_current_user_id(), "CUSTOM_POST_TYPE" ) && is_user_logged_in() ) { ?> do something <?php } else { ?> do something else <?php } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, conditional tags, count" }
I can't enqueue Suggest.js in frontend - not added my suggest.js is not being added in front-end. All scripts are correctly loaded but this one. I want to load it only on frontpage so: add_action('wp_enqueue_scripts', 'homescripts'); function homescripts() { if (is_front_page()): wp_enqueue_script('suggest'); endif; } and in my home's html <script> jQuery("#my_input").suggest("<?php echo get_bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php?action=ajax-tag-search&tax=my_taxonomy", {multiple:true, multipleSep: ","}); </script> where `#my_input` is my input field I want with suggestions and `tax=my_taxonomy` is the source taxonomy. Is there something worng I'm doing? Thanks in advance.
Provided you've confirmed that WP's native 'suggest' script is actually being rendered on the page properly (ie. you're using the correct template for home vs front-page), sometimes to avoid script conflicts on the page, you need to wrap your script in an anonymous function. So something like: <script> (function($) { $("#my_input").suggest("<?php echo get_bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php?action=ajax-tag-search&tax=my_taxonomy", { multiple: true, multipleSep: "," }); })(jQuery) </script> Ideally, this should also be separated off into its own .js file and registered/enqueued properly on the `wp_enqueue_scripts` hook with 'suggest' declared as a dependency: wp_enqueue_script( 'my-suggest', 'path/to/my-suggest.js', array( 'suggest' ), false, true );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "jquery, actions, wp enqueue script, front end, frontpage" }
How to get the attribues (alt and title) of an image import with ACF I use the ACF plugin to build oone of my page. Inside this one, i load 4 images. How can I get attached image alt ? I tried with "$alt = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true);" and a lot of other things my nothing works. <img src="<?php the_field('image_1');?>" alt="$alt"> Someone can help me ?
It's already in the docs. Try this: <?php $image = get_field('image'); if( !empty($image) ): ?> <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" /> <?php endif; ?> For easier debugging, try this: `var_dump($image);` to print out the `$image` variable to know what is in `$image`. You can also put `var_dump($image)` inside `<pre>` tag for better reading.
stackexchange-wordpress
{ "answer_score": 3, "question_score": -3, "tags": "images, advanced custom fields" }
Problem with adding custom post type meta to header by plugin I'm trying to write a plugin by which a meta code will be added to specific post type header. I tried to use this code: function msc_header() { if ( is_singular( 'article' ) ) { echo '<meta name="site_title" content="'.'test test'.'">'."\n"; } } add_action('wp_head','msc_header', 0); But nothing happened. I got no error but no code was added. Am I missing something here?
It's should be `return` rather than `echo`. return '<meta name="site_title" content="'.'test test'.'">'."\n";
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, plugin development, post meta, headers" }
Get blog title with REST v2 I can't find the answer after searching, so... How do I get the title of a site using the REST API v2? All I can find in the API docs are the posts, pages, tags,...
You can get it easily by making a GET request to: < You will see your site name, description, url and home...
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "rest api" }
Image Sizes/Thumbnails not generating on local install Ampps I'm not sure what is going on. I can't get the thumbnails to generate. I tried the "force regenerate thumbnails" plugin, but that didn't work. I' don't have any plugins running and I've tried with a fresh functions.php file, but still nothing. I'm using genesis framework with a custom child theme (which is pretty bare bones currently) Is there some settings I can try in the php.ini or elsewhere? I'm thinking that has something to do with the server rather than wordpress. Just don't know where to start.
Sounds like you don't have an image library enabled with PHP (that probably should have generated some errors so maybe first look at your php error logs). Checkout if GD2 is enabled in your php.ini file.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "thumbnails, images, localhost, local installation" }
<meta name="generator" content="WordPress 4.4.2" /> neccessary? Hello fellow WordPressers Today, I realized that most WordPress sites have this small footprint saying: <meta name="generator" content="WordPress 4.4.2" /> where it indicates what "system" have made this current page. Now three questions popped into my mind: 1. If I remove this line, what is the disadvantages? 2. If I leave this line alone, what is the advantages? 3. By indicating the WordPress version, won't it be easier for (evil)robots to search for vulnerabilities, and try to exploit my websites? I hope someone here can clear my mind.
1. Nothing (you will ruin some web stats that look at it, but you probably son't care about that) 2. Nothing 3. No. Evil people don't care what is the value otherwise the easiest security measure would have been to change it instead of actually upgrading anything.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "security, customization" }
plugin settings - uploading multiple files with a single button My plugin settings' page has a <input type='file' name='adm_uploads' multiple /> button which allows my browser to select multiple files as expected. All goes well except that in my callback $_FILES only contains the array corresponding to the last file from the browser' selection. It looks like the other files are not sent. Any idea of what could cause the issue?
Try this: <input type='file' name='adm_uploads[]' multiple />
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development, input" }
Showing different pages depending on a cookie value I have a website that asks the visitors to choose a language on the first page, I store the option in a cookie and I am showing the content (starting with second page) depending on this option. I want to show the second page without showing the first one as long as the cookie is not expired. I try to do something like this in a plugin I made: function has_my_cookie(){ if ( isset($_COOKIE["myCookie"])) { if($_COOKIE["myCookie"] == "en"){ header("Location:path/to/my/en/file"); exit; } } } add_action('init', 'has_my_cookie'); The problem is that I get an infinite loop somewhere (ERR_TOO_MANY_REDIRECTS). What am I missing? Is there a better way to achieve this? I tried to do something similar in the header.php, with the same result...
You could hook into the template redirect function. function my_page_template_redirect() { if ( isset( $_COOKIE["myCookie"] ) ) { if( $_COOKIE["myCookie"] == "en" ) { wp_redirect( 'you path' ); exit; } } } add_action( 'template_redirect', 'my_page_template_redirect' ); And you could better use `wp_redirect()` function to redirect inside Wordpress.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, redirect, cookies" }
Woocommerce: Only one review per verified buyer By default, Woocommerce allows multiple reviews by a single user. What I want is to allow only one review from verified buyers.
Adjust the single-product-reviews.php template file and add a conditional check. How to limit users to one comment per post
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "filters, woocommerce offtopic" }
How To Display Date (/Time/Author) In pages? I'm trying to search for a way to display the published date of a page, but I can't seem to find one. Maybe because the "PAGE" word is very generic. But what I'm looking for is a way to display date in a page. Displaying the date (and author and time) is pretty easy with posts because they're automatically built within the theme. I would appreciate any help on this. SAMPLE POST (WITH DATE) \- date at the bottom of the post, below the sharing buttons. SAMPLE PAGE (NO DATE)
WordPress has some nifty functions which do this for you. You'll need some experiences with HTML, CSS, PHP to style the output and understand what these functions do but the functions you're looking for are: * `the_date()` which displays the post date. * `the_author()` which displays the author of the post. In your theme will most likely be a `page.php` template where you can add these on pages into The Loop like so: <?php if( have_posts() ) : ?> <?php while( have_posts() ) : the_post(); ?> <div class="date"><?php the_date(); ?></div> <div class="author"><?php the_author(); ?></div> <?php endwhile; ?> <?php endif; ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "pages" }
How to translate a string that contains a WordPress sitename currently I have this code: <?php _e( 'Follow ' . get_bloginfo( 'name' ) . ' on Facebook', 'yanse' ); ?> But I just get **Follow** to translate and it echoes " **Seguir** 'Site name' on Facebook"
You can use `sprintf`: echo sprintf( __('Follow %s on Facebook', 'yanse'), get_bloginfo('name') );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "themes, translation, localization" }
WordPress custom post - add dynamically meta boxes I want build an custom editor for my custom post type in WordPress. I'm able to add multiple tinymce editor to the post type, but I want this dynamically. I'd like admin users to be able to create and remove additional meta box fields as needed. The admin user should be able to click a button (or select from a drop-down menu) that will add additional new metabox with an tinymce editor. How would you arrange this? Thanks a lot for any help!
It works with Advanced Custom Fields (Pro). You can create dynamic repeat boxes with this plugin
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, visual editor" }
get_the_terms in descending alphabetical order I'm displaying a list of terms that a post is assigned to by using the following: <?php $terms = get_the_terms( $post->ID , 'winetype' ); $sep = ', '; foreach ( $terms as $term ) { echo $term->name; echo $sep; } ?> But we would like the output to be in descending alphabetical order (Z-A), I can't find a way to use order => DESC on this, any suggestions? Many thanks in advanced.
You could try this: // Get posts terms $terms = wp_get_post_terms( $post->ID, 'winetype', array( 'order' => 'DESC') ); $sep = ', '; foreach ( $terms as $term ) { echo $term->name; echo $sep; }
stackexchange-wordpress
{ "answer_score": 6, "question_score": 5, "tags": "order" }
wp_enqueue_script + wp_enqueue_style Since When `wp_enqueue_script` \+ `wp_enqueue_style`: these 2 are recent inventions in wordpress are they are from many years. I purchase a course from udemy his authors hasn't used these functions. His videos look like a freelance edition. he is saying 1 year back when he made this video it wasn't there. Please guide me how long since these things have been incorporated into WordPress.
When looking at either The Codex or Code Reference there's usually a little snippet at the bottom which says: > **Since:** WordPress x.x.x If we take a look at `wp_enqueue_script()` for example we see toward the bottom above the contributor notes that it has been around: > **Since:** WordPress 2.1.0 Now we can use the WordPress Release Chart to find out when 2.1.0 came out, which it did so **January 22, 2007**. So this function has been around for roughly ~9 years.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugin development, functions" }
Get images / media attached to a page by page ID I have a series of pages which have images included on them by means of the HTML editor in the admin area. I need to access these while NOT on the the actual page in question, i.e, I need to access these images by the page ID. I've tried using the following: `$all the images = get_attached_media( 'image', 31 );` This returns NULL however, does anyone have a solution here? Please bear in my mind, I am not looking to access the featured page image here, I am trying to access all images attatched / assigned to a page within the WYSIWYG editor.
`$all_the_images = get_attached_media( 'image', 31 );` _should_ return any image attachments for a page the ID of 31 **if** that page has child images. Meaning, there are images that were uploaded and actually attached to that page, not just upload and _inserted_ into that page. When you use the media uploader (to upload images), from within the Edit screen of the page you're editing, WP automatically makes those images children of that page. That's what `get_attched_media()` returns. If you just use the media uploader to browse the media library and insert images into the content body of the page you're editing `get_attched_media()` won't pull those.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, themes" }
wp_insert_user role not working I have be trying this all day but it is not working how do I set a role for the current user I am inserting with the `wp_insert_user()` function $userdata = array( 'user_login' => $username, 'user_email' => $email, 'user_pass' => $password, 'user_url' => $website, 'first_name' => $first_name, 'last_name' => $last_name, 'nickname' => $nickname, 'description' => $bio, 'role' => 'Editor' ); $user = wp_insert_user( $userdata );
$WP_array = array ( 'user_login' => $username, 'user_email' => $email, 'user_pass' => $password, 'user_url' => $website, 'first_name' => $first_name, 'last_name' => $last_name, 'nickname' => $nickname, 'description' => $bio, ) ; $id = wp_insert_user( $WP_array ) ; wp_update_user( array ('ID' => $id, 'role' => 'editor') ) ; Since you are looking for working solutions, this one should work, and it is only the helpful answer candidate. I am ware that this may not be the best solution, maybe not even close, but it should work.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 7, "tags": "php, user roles" }
How to get membership level id f a particular user How do I get membership level id of a particular user. I have tried $user = get_userdata($userid); $membership_id = $user->membership_level->ID; but it gives a notice of `Trying to get property of non-object....`. I am doing it through Ajax. I have googled it but does not found any solution. Anyone can help? <
You probably want `pmpro_getMembershipLevelsForUser` from functions.php: /* pmpro_getMembershipLevelsForUser() returns the membership levels for a user * * If $user_id is omitted, the value will be retrieved from $current_user. * By default it only includes active memberships. * * Return values: * Success returns an array of level objects. * Failure returns false. */ function pmpro_getMembershipLevelsForUser($user_id = NULL, $include_inactive = false) { Or there's `pmpro_getMembershipLevelForUser` if you only want the first level. Or if you actually want to test access then there's `pmpro_hasMembershipLevel` too. As far as I can see these are all stored in separate tables with date ranges and other restrictions so there's no simple way to access them through normal WP user functions. (And I expect there's documentation about all of these on their website here < but it looks like you'll have to sign up.)
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "membership" }
Declare global var from Template File and use it in Functions.php I am using the wpseo_title filter to rewrite the authors page titles from my site. I have the following code in author.php template: <?php global $author_page_titles; $author_page_titles = $curauth->nickname .', Preparador de Oposiciones a '. $term_especialidad->name .' en '. $term_region->name; ?> Which outputs **_Kevin, Preparador de Oposiciones a Forestales en Madrid_** in my author page (in other pages is the given author nickname and his/her selected terms). In my functions.php I have the following function: function my_custom_authorpage_title($author_page_titles) { if (is_author()) { global $author_page_titles; return $author_page_titles; } } add_filter('wpseo_title', 'my_custom_authorpage_title', 100); I'm pretty sure that the mistake must be in how and where I declare the var, but can't find the solution.
You can use the exact same filter in your template files. If you do need it in functions.php for any reason (maybe you have some additional processing) then you can use your own custom filter. functions.php: function my_custom_authorpage_title( $title ) { // process ... return apply_filters( 'my_title', $title ); } add_filter( 'wpseo_title', 'my_custom_authorpage_title' ); author.php (before `get_header()`): add_filter( 'my_title', function( $title ) use ( $curauth, $term_especialidad, $term_region ) { return $curauth->nickname . '...'; }); Hope that helps!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "author, globals, plugin wp seo yoast" }
Switch from https back to http I recently moved my site to https, by installing a SSL-certificate on the server and updating the site address and site home in the wp-admin to use https. Due to some errors my client is experiencing with https, I would like to switch back. I have edited the values in the wp-admin, to be without http **s**. I have also followed several options described in: < However, nothing seems to work. I am not sure what is going wrong. It seems that internally Wordpress is redirecting all url's to https, although the site_url is changed. I have also cleared my .htaccess file, but this also does not seem to be the problem. Any help much appreciated.
You can try these: **1\. make sure the values changed in database** If you can't login to wp-admin > settings to confirm that, you can go to database, wp_options table and look for `siteurl` and `home` values **2\. add code to wp-config.php** Add these lines to wp-config.php define('WP_HOME',' define('WP_SITEURL',' **3\. Clear your cache** Make sure that you clear the cache from any cache plugins you're using and also from your browser Also try adding this to `wp-config.php` (note "false") define( 'WP_CACHE', false ); **4\. check https / ssl related plugins** You might be using any plugin which is causing this, like ssl insecure content fixer, etc. **5\. Cloudflare or other dns side redirect** Make sure that the site isn't using any dns based redirect **6\. disable all plugins and confirm** **7\. change theme to default and check**
stackexchange-wordpress
{ "answer_score": 12, "question_score": 8, "tags": "https, site url, http" }
Add Media has stopped working in the front end since 4.5 update I've got a page that calls wp_editor in the front end. Since upgrading to 4.5, the Add Media button no longer does anything at all. It works fine if you call it in the admin section. There's no word from WordPress on this yet, but I've seen this complaint in a bunch of plugins all experiencing the same issue. Because it still works in the admin section, I'm assuming that a piece of JS that used to make it work throughout WP has been moved to only been called in the admin section, but I don't know where that would be. Has anyone else encountered and solved this?
I've fixed it by creating the following tiny plugin: <?php /* Plugin Name: Fix "Add Media" button in WordPress 4.5 Plugin URI: twitter.com/ojeffery Description: The 4.5 update of WordPress changed to the most recent version of JQuery, which broke the Add Media button when you call wp_editor via the front end. This tiny plugin fixes it by reverting to the previous version of JQuery. This should be considered a temporary measure until WordPress fixes it properly, as using an older version of JQuery may cause other issues. Version: 1.0 Author: Oli Jeffery Author URI: twitter.com/ojeffery */ function pre_4_5_jquery () { // Load jQuery wp_deregister_script('jquery'); wp_register_script('jquery', (" false); wp_enqueue_script('jquery'); } add_action('init', 'pre_4_5_jquery'); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 3, "tags": "front end, wp editor, upgrade, bug" }
echo esc_url( get_permalink($post->ID) + complete the ID's url I am in a deep trouble I try to only display the content of a post after clicking a bouton in order to not have the header and the footer again. Manually I have downloaded the plugin "Show Content Only" that allow me to do that: < content-only=1** My problem is that I would like to automatize the process. I have a php structure that is: `echo esc_url( get_permalink($post->ID)` So my question is can I add something after the `$post->ID` to display the whole url with `&content-only=1`? Or is there an other way more simple. Thank you very much. Cheers from France !
The best approach, from my point of view, is to use `add_query_arg()` function: $only_conent_url = add_query_arg( array( 'content-only' => 1 ), get_permalink( $post->ID ) ); And then you can escape it if you need: esc_url( $only_conent_url ); `add_query_arg()` takes the URL passed as second paramenter and append a properly formatted query string built from the key=>value pairs contained in the array passed as first argument.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, id" }
Adding an additional role to an Administrator User 19 is a WP Admin. $user = new WP_user( 19 ); $user->add_role( 'custom_role' ); The above code works and adds the `custom_role` role. However, when I run the same code on the `personal_options_update` and `edit_user_profile_update` hook it does not. I have added a checkbox to the user profile page. The function called from both the above hooks then... if( user_can( $user_id, 'administrator' ) ) { $user = get_user_by( 'id', $user_id ); if( ! empty( $_POST['my_checkbox'] ) ) { update_user_meta( $user_id, 'my_checkbox', true ); $user->add_cap( 'one_cap' ); $user->add_cap( 'two_cap' ); $user->add_role( 'custom_role' ); } } `one_cap` and `two_cap` are both set correctly for the user, but no sign of `custom_role` and nothing written to the debug log. What could be the cause of this?
use the profile_update hook and in the hooked function, run this check to make sure that it's adding the previous data to the users profile on update too. if ( $update ){ do_action('profile_update', $user_id, $old_user_data); }else{ do_action('user_register', $user_id); } return $user_id; This answer can help you understand it more: WordPress edit_user_profile_update update secondary role
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "user roles, capabilities" }
Partial refresh of menu in customizer not working? WordPress 4.5 supposedly enables live refresh of the menu in the customizer, though I cannot get it to work. If I reorder the menu (in customizer) I see no changes until I perform a manual refresh. However, if I click the Menu Locations checkbox to disable the menu, and again to re-enable, the screen does refresh. Though doing that saves the menu - which is not ideal. Or is that the intended functionality? Clicking save and publish does not trigger a refresh either. Since other changes in customizer are shown in real time, this seems inconsistent. Has anyone gotten this to work?
I found the problem - it was stupid but I hope this helps someone. I had set the menu using the "menu" arg like so: $args = array( 'menu' => "Primary", ); For selective refresh to work, you have to use the "theme_location" arg like so: $args = array( 'theme_location' => "primary", );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "menus, theme customizer" }
Override plugin template I've got Recent post by category widget on my plugin with the folder "recent-posts-by-category-widget" I've copied that folder and all of it's contents to the root location of my theme. But the override is not working, I've already done this on woocommerce and no issues happening there. Would love some ideas to fix this issue.
It doesn't work like that as native functionality, a plugin author has to build that themselves, and some have such as WooCommerce and Shortcodes Ultimate. If your plugin doesn't have this functionality and the hooks available (if any) aren't sufficient, you'll need to fork the plugin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
wpdb get posts by taxonomy SQL I need a list of posts of a specific post_type plus the name of a custom taxonomy term. This is what I got so far SELECT p.post_name,t.name as clientName FROM $wpdb->posts AS p, $wpdb->terms AS t LEFT JOIN $wpdb->term_relationships AS tr ON ('p.ID' = tr.object_id) LEFT JOIN $wpdb->term_taxonomy AS tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id) LEFT JOIN $wpdb->terms AS t2 ON (t2.term_id = tt.term_id) WHERE p.post_status = 'publish' AND p.post_type = 'portfolio' AND tt.taxonomy = 'clients' ORDER BY p.post_date DESC What´s the problem? I´m getting too many results, I get the right posts, but several times with every client. I guess thats because I use $wpdb->terms as t AND as t2? But when I try to use it as t both times I get the error Not unique table/alias: 't' Who can help?
Sorry guys, I just found the solution: SELECT p.post_name, t.name as clientName FROM $wpdb->posts AS p INNER JOIN $wpdb->term_relationships AS tr ON ('p.ID' = tr.object_id) INNER JOIN $wpdb->term_taxonomy AS tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id) INNER JOIN $wpdb->terms AS t ON (t.term_id = tt.term_id) WHERE p.post_status = 'publish' AND p.post_type = 'portfolio' AND tt.taxonomy = 'clients' ORDER BY p.post_date DESC I just don't have to define an alias for `$wpdb->terms` in `FROM` clause.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 5, "tags": "query, wpdb, sql" }
polylang translation of a custom post created by wp_insert_post() I am in trouble. I have a travel site...I have created a page where users can write a form to insert their houses. The houses are of course a custom post type. This is a piece of my code: ... some validation here if ($idarticolo = wp_insert_post($post)) { //lingua global $polylang; $lang = pll_current_language(); $polylang->set_post_language($idarticolo, $lang); ... everything works fine, the house is inserted in my current language; but when I try to translate this post from admin panel, I get an error. The post is not translated, and no language is detected. Please help!!!...many thanks in advance! M.:)
Apparently Polylang has an undocumented pll_save_post API method. See here: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "plugin polylang" }
Remove All Query Arg Is there a way to remove all query arg parameter in the URL added via `add_query_arg();` without knowing the query key available for removal? I'm looking for this kind of function `remove_query_arg_all();` currently I'm removing the query_arg via preg_match REQUEST_URI, but not sure if it will cause any problem in the future.
You can explode URL by `?` and take the first part: $url = explode( '?', esc_url_raw( add_query_arg( array() ) ) ); $no_query_args = $url[0];
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "urls" }
related author post thumbnail shows post thumbnail using the code below to show 4 related posts from author <?php global $authordata, $post; ?> <?php $authors_posts = get_posts( array( 'author' => $authordata->ID, 'post__not_in' => array( $post->ID ), 'posts_per_page' => 4 ) ); ?> <?php foreach ( $authors_posts as $authors_post ) { ?> <div class="uk-width-medium-1-4"> <a href="<?php the_permalink($authors_post->ID) ?>"> <?php the_post_thumbnail($authors_post->ID); ?> </a> </div> <?php } ?> Problem is, permalinks work fine, but the thumbnail is on all 4 related links the same as the thumb on the post itself. Which is set as featured image on the post I want to set the related posts. Any suggestions? Thanks.
I think the problem may be that `the_post_thumbnail()` doesn't accept an ID as a parameter. Instead you should use `get_the_post_thumbnail()` which does accept an ID as a parameter: <?php echo get_the_post_thumbnail($authors_post->ID); ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, post thumbnails, thumbnails" }
Scheduling posts in database I have more than 100 posts to schedule. I have set the date and the status (future) with a SQL query. But when the time comes the post is not published and in desktop I can read message 'Schedule lost'. The system (cron) is working properly, because manual schedules are working normally. How does the scheduling system work? What am I missing? Thanks.
Scheduled Post Guardian solved it. I guess scheduling strictly from database is not possible.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "database, sql, wp cron, scheduled posts" }
Best Practice - Customise a WooCommerce+Wordpress Templates To integrate customise HTML/CSS to Wordpress without editing default ready theme template from Wordpress 1. Download HTML5Blank Boiler plate 2. modify/overide boilerplate css with our customise Css 3. Create custom Template / Post templates 4. Install ACF Modify header.php My question is, as a web developer, if I wanted to customise WooCommerce template / styling /layout ? Usually which best practices I should go for ? 1. Can we modify WooCommerce template as this link's presentation does? 2. Or I should download WooCommerce ready template and modify from the ready templates? Is my first time to build WooCommerce site,this site will includes of : * Wordpress CMS to update / modify content * Woocommerce to track order / add product May I know which development method / best practice is for web developer to develop WooCommerce + Wordpress site?
The best practice for editing a Woocommerce theme is similar to Wordpress as you should use `Hooks` and `Filters` when possible. < But if you do need to edit a template Woocommerce outlines this on their website as well: < You just need to make the template upgrade safe by copying the template to your theme in to a woocommerce folder.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "woocommerce offtopic, page template, customization" }
How to display the requested post only? I have created a custom theme and my front page is `index.php`. Moreover, I have couple of blog posts and I display them with a loop in this page, together with a link for each particular post. The problem is that whenever I click on this link, the browser loads the correct permalink, e.g. ` but the content remains the same. I use `is_front_page()` to determine whether I am loading the front page or a single post. When I click on a single post, how to display this post **only** and not all the others?
WordPress creates the default query on each page automatically based on the requested URL. Your template file should contain the standard loop to output whatever the default query contains. if( have_posts() ){ while( have_posts() ){ the_post(); the_title(); the_content(); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts" }
Make custom post available under main domain directly? i have a custom post type called project. The shortlinks are all www.myapp.com/project/project-slug i want to change that to www.myapp.com/project-slug someone knows what I have to change in, i reckon permalinks settings, to be able to do that?
I did this before 6 months ago. But I don't remember the way. But I bookmarked a few articles which I followed to do it.Just check it. Remove slug from custom post type post URLs Remove The Slugs from Custom Post Type URL Remove Custom Post Type Slug from Permalinks
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks, shortlink" }
How do I stop my blog from pinging back itself? I connect a lot of my posts to my new ones, and that is probably why I keep getting self pingbacks. Besides a plugin, is there a script I can use to get rid of this?
You could try this by putting code in functions.php in your theme. function no_self_ping( &$links ) { $home = get_option( 'home' ); foreach ( $links as $l => $link ) if ( 0 === strpos( $link, $home ) ) unset($links[$l]); } add_action( 'pre_ping', 'no_self_ping' ); Hope this helpful to you.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 5, "tags": "pingbacks" }
How to change 'with_front" key from an existing custom post type? I have a CPT called 'experts', that has been created in a theme I bought, and I can't find out where nor where to change it. I need to change a parameter to 'with_front' => false Because my general permaling structure goes with /blog and I do'nt want experts to be in /blog/experts. Is there a way I could do that adding something in the functions file? I have tried this (How to set "with_front'=>false" to a plugin-generated cpt?) and various things, but could not get it to work. Thanks :)
You could try the newly `register_post_type_args` filter to adjust it. Here's an untested example: /** * Set 'with_front' to false for the 'experts' post type. */ add_filter( 'register_post_type_args', function( $args, $post_type ) { if( 'teachers' === $post_type && is_array( $args ) ) $args['rewrite']['with_front'] = false; return $args; }, 99, 2 ); **Updated** with new info from @Agnes: the post type is `teachers` not `experts`.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 6, "tags": "permalinks" }
Wordpress add_rewrite_rule() cannot visit lower url levels I have a post type called "shop" and added query variables and a rewrite rule. // Adds query vars for shop post type function gtp_add_shop_query_vars( $vars ) { $vars[] = 'shop-category'; $vars[] = 'width'; $vars[] = 'height'; return $vars; } add_filter( 'query_vars', 'gtp_add_shop_query_vars' ); // Adds rewrite rules for shop post type function gtp_add_shop_rewrite_rules() { add_rewrite_rule( '^shop/([^/]*)/([^/]*)/([^/]*)$', 'index.php?shop-category=$matches[1]&width=$matches[2]&height=$matches[3]', 'top' ); } add_action('init', 'gtp_add_shop_rewrite_rules', 10, 0); With this rules I can visit now: < But if I want to visit: * < * < the regex does not match anymore and the page will not be found. What do I need to do to be able to enter all the levels of the url?
I fixed my problem as follows: // Adds rewrite rules for shop post type function gtp_add_shop_rewrite_rules() { add_rewrite_rule( '^shop/([^/]*)/([^/]*)/([^/]*)$', 'index.php?shop-category=$matches[1]&width=$matches[2]&height=$matches[3]', 'top' ); add_rewrite_rule( '^shop/([^/]*)/([^/]*)$', 'index.php?shop-category=$matches[1]&width=$matches[2]', 'top' ); add_rewrite_rule( '^shop/([^/]*)$', 'index.php?shop-category=$matches[1]', 'top' ); } add_action('init', 'gtp_add_shop_rewrite_rules', 10, 0);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp query, permalinks, url rewriting, rewrite rules" }
How to get the registered sidebar's name by its id? Let's say I have this code in my _"functions.php"_ : function mytheme_widgets_init() { register_sidebar( array( 'name' => esc_html__( 'Sidebar Name', 'mytheme' ), 'id' => 'sidebar-2', 'description' => '', 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', ) ); } add_action( 'widgets_init', 'mytheme_widgets_init' ); How can I get that sidebar name by its id, some kind of this code? get_dynamic_sidebar_name( 'sidebar-2' ); // -> Sidebar Name
Sidebars are stored in global variable `$wp_registered_sidebars`. You can get the sidebar properties using this variable. global $wp_registered_sidebars; if ( isset( $wp_registered_sidebars['sidebar-2'] ) ) { echo $wp_registered_sidebars['sidebar-2']['name']; } > Note that do not use it too early, either on/after `widgets_init` hook or in a template file.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "php, functions, theme development, themes, widgets" }
WP MultiSite API - Create new sites I'm building an app for iOS/Windows. I want to allow my users to register / create a new sub site on my domain via the app. How can I achieve this? Does the REST API allow this? Thanks.
There is nothing in the core or in the rest API for this requirement. You can try this plugin, < Sorry, but I see no other chance and no more to say in this answer. The core function to create a new site in the network of the installation is `wpmu_create_blog`. But there is no access from the REST API.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "multisite, rest api" }
Can I limit term selection to one plus parent? So i have a custom post type (listings) and a custom taxonomy (listing_terms). The taxonomy has parent/child terms. Eg: Restaurant -> Cafe (where Cafe is the child of Restaurant). I want to only let my users to be able to select one child term and then have the parent term automatically selected when they're creating posts in the backend. So essentially only two terms can be selected. Anyone ever try this? Alternatively, I've been thinking that we could have a two-level select field possibly, where they'd have to pick the parent first from a dropdown then another dropdown would appear with the child terms of that first term. I'm open to suggestions!! Kinda hit a wall here. Just fyi, I'm also using ACF for custom fields if that helps anyone.
I found an answer that works well. Using two dropdowns in a 'cascading' style, with the code in the gist below, users would pick from a list of parent terms first, then a second dropdown appears with the list of children. The key is that both the parent and the child terms are 'selected'. Just took a bit of tweaking to get it right, but it seems to work great. Thanks to some older code that still works from @hameedullah-khan <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom taxonomy, wp admin, terms, select" }
Password-protect a custom rss feed I've created a custom post type and would like to send those posts to FB Instant Articles and Apple News via a RSS feed. I've created a custom RSS feed and need to know what's the best way to make that feed password-protected. The CPT is called limitedrun. The feed URL is domain.com/?feed=ltdrun and the RSS template is called rss-ltdrun.php I know there are plugins that do this but it's not what I'm looking for. They password protect the entire site in order to make the RSS feed password-protected. I need the opposite: RSS password-protected and the website open. Thanks,
Well it turns out Apple News doesn't accept password-protected RSS feeds. Thanks for the help!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "custom post types, theme development, themes, rss" }
How to use 'phpmailer_init' SMTP settings only on certain 'wp_mail' actions? Is there a conditional check I can run for `phpmailer_init` or a `wp_mail` parameter that let's me apply my custom `phpmailer_init` SMTP settings only on specific `wp_mail` actions or does `phpmailer_init` always run sitewide?
`phpmailer_init` will always fire for every `wp_mail()` call - however, you can hook/unhook it conditionally like so: function wpse_224496_phpmailer_init( $phpmailer ) { // SMTP setup // Always remove self at the end remove_action( 'phpmailer_init', __function__ ); } function wpse_224496_wp_mail( $mail ) { // Example: only SMTP for emails addressed to [email protected] if ( $mail['to'] === '[email protected]' ) add_action( 'phpmailer_init', 'wpse_224496_phpmailer_init' ); // Example: only SMTP for subject "Foo" if ( $mail['subject'] === 'Foo' ) add_action( 'phpmailer_init', 'wpse_224496_phpmailer_init' ); // Other properties $mail['message']; $mail['headers']; // Could be string or array $mail['attachments']; // Could be string or array return $mail; } add_filter( 'wp_mail', 'wpse_224496_wp_mail' );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "wp mail, smtp" }
How to report JavaScript errors in the admin panel Real life scenario for a context: A two instances of a JS library, each from different version are being loaded. Since the library do not keep backward compatibility someone code will probably fail, either the code using the first instance or the code using the second. For graceful degradation I am going to wrap the problematic code in a `try { } catch {}` block to have only my code fail instead of the whole page. The question is really how do I report to the user that there is a problem. logging to console is fine once you need debuging data but it is not user friendly. Lets assume for the sake of this question that we are talking about traditional admin side only.
You could probably make use of WP built-in notices and create one using JavaScript. jQuery(function($){ $('.wrap > h1').after('<div class="error notice"><p>' + 'Your error message' + '</p></div>'); });
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "javascript" }
How to remove container box in Wordpress pages? I would like some help on removing the container box from all my pages (Theme: Zerif Lite). In the screenshot below, you will see it red-boxed. ![enter image description here]( Thanks in advance! Regards, Suraj Edit 1: I think I have resolved this. In the Content Section of the Editor, I found this snippet of code, and made a minor change to it. article.hentry { border: 1px solid #FFF; /* Changed the border color to white*/ padding: 1px; background-color: #FFF !important; } The border is not visible anymore.
Set border property to none instead of white. article.hentry { border: none; // set this to none for no border padding: 1px; background-color: #FFF !important; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -4, "tags": "pages" }
How To Remove Dashboard Menu Items for Multisite Users? I'm trying to remove some menu items in the Dashboard of Multisite users. For example my domain name is xyz.com, his site will be xyz.com/user. When he logs in to WP Dashboard under xyz.com/user/wp-admin, how can I (the admin of xyz.com) remove some options from xyz.com/user (left sidebar) menu? For example, I would like to remove user's ability to Add New Users? Any response will be appreciated. Thanks! ![enter image description here](
1) Install & network activate User Role Editor plugin from < 2) Then go to **Settings > User Role Editor** menu on network and make sure you have the settings as shown in following screenshot. ![enter image description here]( 3) Go to "User Role Editor" settings page on your main site < and select the "Administrator" role. Then remove the capabilities which you want to remove. For example, in below screenshot you can see that all User related capabilities have been removed. Do note that I have checked "Apply to All Sites" so that it applies to all the sites on the network. ![enter image description here]( 4) Now check backend of any of your subsite and you will notice that "Users" menu is no more there. Similarly you can hide other menu pages as intended. Let me know how it goes :-)
stackexchange-wordpress
{ "answer_score": 7, "question_score": 2, "tags": "multisite, user roles, dashboard" }
posts_per_page override by default settings I'm running some template files outside of the actual theme and I am displaying some posts on this templates. Everything worked absolutely fine but some days ago (maybe the update to 4.5) the default settings of WordPress started to override my `posts_per_page=-1` and I have no clue why this is starting. (No new plugins installed) <?php // Include WordPress define('WP_USE_THEMES', false); require('./../wp-blog-header.php'); query_posts('tag=tagname&posts_per_page=-1'); ?> <?php while (have_posts()): the_post(); ?> <section class="in_tab"> <figure class="tab_fig"> <?php the_post_thumbnail('thumbnail'); ?> </figure> <h2><?php the_title(); ?></h2> <a class="insidelink" target="_blank" href="<?php the_permalink(); ?>" >Weiter...</a> </section> <?php endwhile; ?>
I found the problem. Here is the solution in case someone stumbles upon a similar problem. I had a filter in my functions.php that limited the showed posts on several custom taxonomies and the default value was set in the else statement // Customizing posts per page on zitate archive function limit_posts_per_archive_page() { if ( is_post_type_archive( 'zitate-sprueche' ) || is_tax('zitate-kats') || is_post_type_archive('daten') || is_tax('daten-kats')) { $limit = 27; } else if (is_post_type_archive( 'videos' ) || is_tax('videos-kats') || is_post_type_archive( 'whitepaper' ) || is_tax('whitepaper-kats')) { $limit = 9; } else $limit = get_option('posts_per_page'); set_query_var('posts_per_archive_page', $limit); } add_filter('pre_get_posts', 'limit_posts_per_archive_page'); I changed the else to else { // do nothing :) } Now it works as usual
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "query posts" }
Meaning of "if ( is_home() && ! is_front_page() )" snippet? I see the following code a lot in index.php files. I understand that `is_front_page()` returns true when viewing the Site Front Page (whether displaying the blog posts index or a static page), while `is_home()` returns true when viewing the Blog Posts Index (whether displayed on the front page or on a static page). I am still somewhat stumped about the use of the following code - <?php if ( have_posts() ) : ?> <?php if ( is_home() && ! is_front_page() ) : ?> <header> <h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1> </header> <?php endif; ?> Any explanation of why this piece of code is so popular is greatly appreciated.
This will display the title of the **page** when a static page is set to show posts. **E.g.** I show posts on my homepage... It'll do nothing. If I, say, show posts on page titled **News**... It'll show **News** in H1. This is used so that the title of the page is shown, whenever posts are shown on a page, but nothing when blog posts are shown on the front page (home page). We do it because if it's on home page... it will show the title of the first post, making it appear twice (once at the top in H1 and again when posts are looped through).
stackexchange-wordpress
{ "answer_score": 19, "question_score": 36, "tags": "theme development, loop, themes, templates" }
Which hook is fired when inserting media into a post I want to add numbering to each image when I insert them into the post. For example if I insert 3 images into a post, there will be: 1. Image 1 2. Image 2 3. Image 3 I looked through the WordPress documentation, but I can't find which hook is triggered when inserting images into a post.
The `add_attachment` action is fired when the `wp_insert_attachment()` function is called to add an item to the media library. Images are added to posts after going into the media library first. Even when adding via the post editor, items are added to the library with `wp_insert_attachment()` then to the post. add_action( 'add_attachment', function( $post_ID ) { // Do Stuff }); This will not allow you to number items by post, only by instance in the media library. Whether that works for your purposes, I cannot answer. <
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "filters, hooks, media" }
Calling JavaScript file with Custom Plugin So, the goal is to use jQuery Validation for a custom form. Maybe I'm going about this the hard way. But, here's what I'm doing: 1. Uploaded the jQuery Validation file to my theme folder 2. Created plug-in folder in plug-in's file 3. Added php file with this code: function custom_validation() { wp_enqueue_script('jquery'); wp_register_script( 'jq-validation', get_template_directory_uri() . '/jquery.validation/jquery.validation.js', array('jquery'),'1',false ); wp_enqueue_script( 'jq-validation' ); } add_action( 'wp_enqueue_scripts', 'custom_validation' ); And, it's not working. I'm trying to avoid adding: <script src=" <script src=" To the header file. But, it works whenever I do that. Any help is appreciated.
WP loads jQuery in no conflict mode so shortcut **$** is not available for jQuery to use .You should not use the **$** variable for `jQuery` within WordPress. jQuery(function ($) { //code here }) or (function($){ //code here })(jQuery); There are so many Q&A which refers to the same conflict issue.Check this and this.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, jquery, wp enqueue script, validation" }
Featured image fallback link to permalink I use this to display the featured image for each post. If the post does not have a featured image, a generic image will be displayed: <?php if ( has_post_thumbnail() ) { echo '<a href="' . get_permalink($post->ID) . '" >'; the_post_thumbnail(); echo '</a>'; } else { echo '<img src="<?php bloginfo('template_directory'); ?>/img/fallback-featured-image.jpg" />'; } How can I get the fallback image to link to the permalink?
I have updated your code so that the fallback image has post permalink. I hope this helps: if ( has_post_thumbnail() ) { echo '<a href="' . get_permalink($post->ID) . '" >'; the_post_thumbnail(); echo '</a>'; } else { echo '<a href="' . get_permalink($post->ID) . '" ><img src="'. get_stylesheet_directory_uri() . '/img/fallback-featured-image.jpg" /></a>'; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "php, permalinks, post thumbnails" }
Original image not saving? When i'm uploading a picture, WordPress doesn't save the original image, just the thumbnails? That's why when i'm setting a featured image, the link is broken. Any help to to save the original image by uploading it via media library?
The default image sizes of WordPress are “thumbnail”, “medium”, “large” and “full” (the size of the image you uploaded). These image sizes can be configured in the WordPress Administration Media panel under Settings > Media. This is how you can use these default sizes with the_post_thumbnail(): the_post_thumbnail(); // without parameter -> 'post-thumbnail' the_post_thumbnail( 'thumbnail' ); // Thumbnail (default 150px x 150px max) the_post_thumbnail( 'medium' ); // Medium resolution (default 300px x 300px max) the_post_thumbnail( 'large' ); // Large resolution (default 640px x 640px max) the_post_thumbnail( 'full' ); // Full resolution (original size uploaded) the_post_thumbnail( array(100, 100) ); // Other resolutions for more information to see <
stackexchange-wordpress
{ "answer_score": -1, "question_score": 1, "tags": "uploads, post thumbnails, gallery, media library, images" }
How to get attachements URL from author meta and display them? I created a form for edit author with "WP User Frontend" and I use a custom meta field for multi upload images that can upload 6 images, with meta name `'management_certi'`. My problem is I can display first image uploaded, but can't display all of the images uploaded from its form for author. My code is: if ( get_the_author_meta( 'management_certi', $curauth->ID ) ) { $id = get_the_author_meta( 'management_certi', $curauth->ID ); $url = wp_get_attachment_url( $id ); ?><a href="<?php echo $url; ?>" data-lightbox="image-1" data-title=""><img src="<?php echo $url; ?>" class="thumbnail" width="36" height="36" /></a><?php } Any ideas?
I found it :D Yeeeeeeeeaaaahhhhhh :)))) This is final code that worked! I explained each level ;) /* for get author ID use these */ $curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author)); $author_id = get_the_author_meta('ID'); /* First condition */ if( get_the_author_meta('management_certi', $author_id, true)) { /* get file ID */ $id = get_user_meta( $author_id, 'management_certi'); if($id) { /* Array Loop! */ foreach($id as $attachments) { /* get file URL */ $url = wp_get_attachment_url( $attachments ); ?> <a href="<?php echo $url; ?>" data-lightbox="image-1" data-title=""><img src="<?php echo $url; ?>" class="thumbnail" width="36" height="36" /></a> <?php } } } else { echo '--'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, uploads, author" }
How to use prepare to query with variables Trying to write a prepare statement that works. This works: $countthem = $wpdb->get_var( "SELECT COUNT(*) FROM wp_cmapg WHERE lang = 'yes'" ); This does NOT work: $countthem = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM wp_cmapg WHERE lang= %s", $lang ), 0, 0 ); Also tried: $countthem = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM wp_cmapg WHERE lang LIKE %%%s%%", $lang ), 0, 0 ); The contents of `$lang` is yes.
Try adding the single quotes back around the `%s`: $countthem = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM wp_cmapg WHERE lang='%s'", $lang) );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "wpdb" }
Listing a post's categories and subcategories Is there a way to display the parent categories and subcategories for a particular post (ie. for use on `single.php`). I've tried using `get_the_category_list()`, but it displays a list like this: * Subcat1 * ParentCat1 * Subcat2 * Subcat3 * ParentCat2 Even if you try the 'single' or 'multiple' display argument, it doesn't give me what I want, which is this: * ParentCat1 * Subcat1 * Subcat2 * ParentCat2 * Subcat 3 Is it possible to get the categories to be displayed like this? Even using another method (like `get_terms()`)?
### Update 1: Thanks to @birgire for suggesting a better way: wp_list_categories( [ 'include' => wp_list_pluck( get_the_category(), 'term_id' ) ] ); * * * Try this in your `single.php` template: $current_cats = get_the_category(); $current_cats_ids = []; foreach ($current_cats as $cat) { $current_cats_ids[] = $cat->term_id; } wp_list_categories([ 'include' => $current_cats_ids, ]);
stackexchange-wordpress
{ "answer_score": 12, "question_score": 3, "tags": "single, categories" }
Bulk posts from DRAFT Section So, i did create a website with 110k posts and i need to test some SEO features, so i did clone the same database and i did post them on 5 other domains. The thing is i can't index them 110k posts at a single time by google cus it isn't gonna go up, so i need a code to posts like 5000 - 10000 posts per day onto a random time postbased. I've tried this plugin < But it only allows 999 posts per day to be scheduled, i did try to modify the number of allowed characters on the php code but it doesn't work. Thanks!
An way to do that is using SQL. You probably have access to the database, so you can run this daily. It's not automatic, but will solve your problem UPDATE wp_posts SET post_status='publish' WHERE post_status='draft' AND post_type='post' ORDER BY rand() LIMIT 5000 Just to explain what this line do: It will get 5000 items (LIMIT 5000) in a random order (ORDER BY rand()) and will transform the status to published (post_status='publish') on every record that is a post (post_type='post') and the status is draft (post_status='draft'). Hope it helps :)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, bulk" }
Push Shortcode parameter to template I'm trying to push a shortcode parameter value to a template file but for some reason I can't get the array value that I'm targeting into a single variable. Here is my code and the shortcode I'm using: function content_table($atts) { $atts = shortcode_atts(array( 'tablepageid' => '' ), $atts); include(locate_template('table-layout.php')); } add_shortcode('ContentTable', 'content_table'); **Edit** I removed the quotes from my shortcode and I'm now able to see the value: [ContentTable tablepageid=4799] I created a page to test the shortcode function: print_r(array_values($atts)); Array ( [0] => 4799 ) The value from the shortcode is available but I'm having some trouble getting the value into a variable for my template to use: $arr = $atts[0]; The $arrTable variable is empty...I can't figure out why it's not 4799.
You are probably confused by the output of `array_values()` which will always get you only array values without keys while `$atts` variable is actually an associative array. To extract your attribute use `$arr = $atts['tablepageid'];` Cheers
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "shortcode, page template, include" }
Admin menu disable new/delete page So I've been tinkering with the admin roles and I can't seem to be able to revoke create page rights for the admin. I can only find 'Edit page'. If I remove Edit page, the entire pages tab goes away(probably because of not enough rights).. Is there a way to disable creating/deleting pages and keep the pages tab? I have this so far. $role = get_role('administrator'); $role->remove_cap('delete_pages'); $role->remove_cap('delete_others_pages'); $role->remove_cap('delete_published_pages'); $role->remove_cap('publish_pages');
By removing the capability of deleting published pages and publishing pages, I have effectively stopped the admin from creating or deleting anything that is on the website. $role = get_role('administrator'); $role->remove_cap('delete_published_pages'); $role->remove_cap('publish_pages');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, pages, admin" }
Wordpress Hook that will run when media file deleted I am very new in wordpress and I am currently developing a wordpress plugin, I just want to know if there is a wordpress plugin hook that will run when one or more file of wordpress media is deleted. Thanks, Dan
The `delete_attachment` action is fired when `wp_delete_attachment()` function is called to delete an item in the media library.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "plugins, php, hooks" }
Widget won't work due to old JavaScript? Any ideas how to make it work? I was trying to add this widget to my blog <!--BEGIN PROFILE WIDGET--> <script src=" type="text/javascript"></script> <script src=" <div id="profile_widget_container_2303472"></div> <!--END PROFILE WIDGET--> But it messes with my design because the first JavaScript is too old. When I remove it, the widget won't load. They (Lookbook) don't have new widgets, only the ones with the old code. Is there any plugin I could install to my WordPress blog to make it work though? Any coding I could add? Any help is very apppreciated :)
![enter image description here]( From your site i can say that script is not being loaded because of wrong opening quote for script tag.Use **`"`** instead of **`”`** So <script src=” Should be this <script src=" **Update:** Add `<script> $LB = jQuery; </script>` before the other script tag. I mean before <script src="
stackexchange-wordpress
{ "answer_score": 2, "question_score": -3, "tags": "jquery, widgets, ajax, javascript" }
add_action wp_enqueue_script priority level only works for admins I have a function in my functions.php file that loads all of the scripts into the header for my website. The line to run the function was like this: add_action('wp_enqueue_scripts', 'init_loadjs_scripts', 100); I'm curious if setting the priority level to 100, would in some way restrict the scripts from loading for visitors or having the priority level set that high might be throwing something off. The problem I was facing was that a couple thumbnails on my site when they were clicked they would open a lightbox that had a video in them. I only saw this issue with Chrome and Safari. Seemed to work with Edge, Firefox, and IE. When i removed the priority number, it worked in Chrome and Safari. I want to understand why it didnt work in Chrome/Safari when i had the priority level to 100. Is 100 to high?
The priority is related to other actions for the same hook. For example, if another plugin would implement `add_action` for `wp_enqueue_scripts` with a lower priority, they would have their scripts loaded in front of yours. You should check what scripts are inserted above yours and see if there is a css conflict.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, wp enqueue script" }
How to load a different header based on post format? I have a difficult question. What's the best way to load a different header based on a post format? I guess I could load another loop around the header but I noticed the site does slow down. This is the code on my index.php: <?php get_header();?> <section id="block"> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php endwhile; endif; ?> </section> <?php get_footer();?> Thanks
Say if your have `header-video.php` used for video post format. Replace `get_header();` with `get_header(get_post_format());` in your regular `singular.php` or `index.php`. If WP can find `header-video.php` it will load it otherwise it will automatically will fallback to `header.php`.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "posts, theme development, headers, post formats" }
Problem with saving large amount of data in postmeta/usermeta I am facing issues saving large amount of data in post meta field e.g. I have created a field Bio/description and put a huge amount of text in it. Now when I save it, it saves some of the text and sometimes nothing saved in the meta field. I have searched through web but didn't get the clear answer. So I want to know what is the size/length restriction on postmeta fields to accept the text? Is there any way we can fix this issue or it will be better to save data in custom table where we can use Long text field which will definitely save it. Also want to know how saving huge amount of data in post meta field will effect the site performance? Thanks in advance!
The `meta_value` field is `longtext`, which a quick google reports is 4,294,967,295 characters - I doubt you're exceeding that. Chances are it's an issue with PHP, specifically `post_max_size` \- if this is less than the "huge amount of data" you are referring to, PHP will simply truncate `$_POST` and you end up with nothing.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field, metabox, post meta" }
Wordpress Smart Iframe Browser How to browse other website without leaving domain? for ex. my website is websites1.com and i want to someone to goto website2.com but doamin name in address bar must be website1.com only.
This should get you on track... <iframe src="javascript:void(0);" frameborder="0" style="display:none;width:100%;margin:0;padding:0;" id="fullsizeframe"></iframe> <a href=" onclick="loadfullsize(this.href);">Website 2</a> <script>function loadfullsize(url) { fullsizeframe = document.getElementById('fullsizeframe'); fullsizeframe.href = url; fullsizeframe.style.height = window.clientHeight; return false; } </script> Note the problem here is you have to insert the iframe HTML directly after the `<body>` tag (and have no CSS width rules on the body tag) for this to work or the iframe width may be limited to less that full width if inside other containing divs etc.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "plugins" }
change "missing attachment" text functions.php WordPress core file: `wp-includes/post-template.php` has this text "Missing Attachment" that i want to change with "-". The problem is that when WordPress upgrades, the file is changed back to the old "Missing Attachment" text. So, are there any filters I can use in my `functions.php` to do that?
You should never change a core file. This message is called by the function wp_get_attachment_link(). For this singular message this function does not apply a filter, but it return the string as value, which can help. You can simple identify where in your theme this function is called and change it return, like: $result = wp_get_attachment_link(); if ($result == 'Missing Attachment') echo '-'; else echo $result;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters" }
How to enable shortcodes in text retrieved from get_theme_mod Is there a way to enable shortcodes in text saved in the customizer and retrieved using get_theme_mod? I'm guessing there's a filter in a similar manner to enabling shortcodes in widgets.
To enable shortcodes in text widgets add a filter like that: add_filter( 'widget_text', 'do_shortcode' ); You can pass every string to `do_shortcode()` including `get_theme_mod()` calls. echo do_shortcode( get_theme_mod( 'theme_setting' ) );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "shortcode, theme customizer" }
previous_post_link inside of a function? I'm missing something on how to call previous_post_link() inside of a function. I also tried assigning the output to a string variable and using that. function prevnext( $content ) { $content .= '<div>' . previous_post_link() . '-' . next_post_link() . '</div>'; return $content; } add_action( 'the_content', 'prevnext', 4 ); I get the hyphen - but not the links. Substituting another string variable also prints to the screen. I can use previous_post_link() in the page template and it works fine. What am I not doing right?
`previous_post_link()` and `next_post_link()` should work inside the `the_content` filter. There is nothing wrong with your code except you must return the value inside the filter instead of print. Otherwise I believe post link should be there at the beginning of content. `previous_post_link()` and `next_post_link()` print the output so consider using `get_previous_post_link()` and `get_next_post_link()`. function prevnext( $content ) { $content .= '<div>' . get_previous_post_link() . '-' . get_next_post_link() . '</div>'; return $content; } add_action( 'the_content', 'prevnext', 4 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, filters, actions" }
Add code inside specific wordpress standard function Is it possible to add a piece of code snippets inside wordpress standard function ? In my case I am developing a plugin that will trace the exact location of the caller of wp_delete_attachment method in wordpress. I can acheive that by **debug_backtrace()** but this method must be called inside the method you wish to trace. How can I acheive this without touching/ editing the wordpress core functions ? function wp_delete_attachment( $post_id, $force_delete = false ) { <-- wordpress core function global $wpdb; //my custom code inside wordpress core function $bt = debug_backtrace(); $caller = array_shift($bt); die(json_encode($caller)); }
I solve the problem by hooking my function to `delete_attachment` hook, then putting the debug trace inside my function and filtering the `wp_delete_attachment`, by this I can retrieve what file and line number where the wp_delete_attachment is called. add_action( 'delete_attachment', 'your_function' ); function your_function($postid) { $trace = debug_backtrace(); if(is_array($trace) && !empty($trace)) { foreach ($trace as $trace_value) { if(array_key_exists("function", $trace_value)) { if($trace_value['function'] == "wp_delete_attachment") { echo $trace_value; } } } } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugin development, customization, filters" }
How to transfer one domain to another domain without losing theme options (customizer)? I have developed the one wordpress site with custom theme, Here I used the custom customizer options. Then site completed on my local machine I mean localhost `( Now the problem is I tried to transfer my site to live domain `( **_How I tried to transfer files?_** 1) exported the database from localhost/phpmyadmin and changed the oldurl to new url using `ctrl+f`. 2) then transfered files through ftp. After live site opens without logo, header menu, and custom customizer data. but `DB` having these values. **_What I expect from you guys?_** _How to avoid these losing theme options?_ I tried many times and checked all the old url was changed to new url in DB. But I didn't get theme options values in new url. please suggest me to _avoid these losing theme options?_ Thanks.
You can not replace the URL in the database using ctrl+f or any other "direct" method. You have to do a search & replace in the whole database in a way capable of **keeping the validity of serialized data**. There are several tools to do that serialized seach & replace. For example: 1. Plugins like Better Search Replace, Velvet Blues Update URLs or All-in-One WP Migration. 2. WP-CLI's search-replace 3. Search and Replace for WordPress Databases Script
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, customization, database, theme customizer, migration" }
How can I use a text and a function php I want to display a text and a function in same sentence: <?php echo 'Right sidebar'; ?> <?php echo the_content(); ?> Something like this: <?php echo 'Right sidebar' the_content(); ?> But it didin't, it's possible to make it work? Thanks
Try <?php echo "Right sidebar".get_the_content(); ?> Don't use echo for `the_content`, it's already echoed out, use `get_the_content` instead.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
Send media uploads to different directories I am making a website for my local primary school, and I have each class page as a separate page template. Rather than have all their uploads go into the general /uploads/ folder I'd like to direct uploads to certain folders based on their page template, so that page-class1.php media uploads will always go to /uploads/class1/ and page-class2.php will go to uploads/class2/ (or some specific folder). I can then control these uploads and sort them by size/date if one class is getting too many uploads I can ask them to limit/clear them. And setting this system in place may allow us to protect them differently depending on the class and content. I would have thought this was a fairly common issue but I can't seem to find this question asked on this site (specific to page templates or even post-type). So, what is the method to direct uploads to different folders, based on the page template?
Well I was privileged enough to get the tumbleweed badge for this question. But I found the answer. Easy enough. Custom Upload Dir Plugin. Perfect for the job. Well, almost. With a little tweaking.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "uploads, page template, media" }
Can I check who updated the static front page on WordPress and the time it was done I need to check who updated the static front page of a WordPress site and the time it was done. Is it possible? And if so how? I'm an administrator of the site and there are other administrators with access.
You can have some clue using the revision log. For more advanced logs, try using a plugin such Simple History
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, frontpage, revisions" }
Which function required? Which WordPress function allows you to include the `footer.php` file into `index.php` file?
Add <?php get_footer(); ?> into index.php or the template you are using Then create footer.php and add in something like this: <?php /* Always have wp_footer() just before the closing </body> * tag of your theme, or you will break many plugins, which * generally use this hook to reference JavaScript files. */ wp_footer(); ?> </body> </html>
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "functions, footer" }
Importing featured image to posts, duplicates the image I'm using wp cli to import the same featured image for around 2,000 posts. I did a couple tests to see if the image would be duplicated or if WordPress would notice that the image already exists in the media library and use it. Sadly it just duplicates the image. Command I'm using: `wp media import --post_id=x --title="Pluto Mosaic" --featured_image --url=mysite.example.com` Is there another way to do this without having to import the same image 2,000 times? Thanks, j03
You can use `wp media import` to import the image once. Once you have the ID for the attachment created, you can run: wp post list --post_type=post --format=ids | xargs -0 -d ' ' -I % wp post meta add % _thumbnail_id <thumbnail-id> Make sure to replace `<thumbnail-id>` with the actual attachment ID.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "post thumbnails, wp cli" }
With Wordpress + Visual Composer, how to restrict a user to change some content in a page? Sorry if it's not the right place to post that but I did not find better. I know in Wordpress, it's possible to restrict users to change pages or remove items from the menu. But is it possible to restrict them to change a content in a page? As I am using Visual Composer I think this feature may be related to this. I did find there is a role manager page with Visual Composer but the configuration isn't deep enough to have that level of restriction. Thanks,
There is no such granular control. The only possible way around it is to use shortcodes that insert content from other "posts" and restrict the access to those posts.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins" }
get_page_templates only return templates with "home" in the filename I have the following custom page template filenames: * template-about-1.php * template-about-2.php * template-home-1.php * template-home-2.php I have this function to get_page_templates: function get_page_templates_select() { $teh_cats = get_page_templates(); foreach ( $teh_cats as $template_name => $template_filename ) { $results[] = $template_name; } return $results; } How can I modify the function to ONLY return the templates that have "home" in their filename?
Figured it out after thinking it through.. if (stripos(strtolower($template_filename), 'home') !== false) { $results[] = $template_name; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, theme development" }
Login_form add to top of form rather then bottom I have added a 3rd field on the login page, but it shows at the bottom(underneath password) while I would like it to show above Username. How can I manipulate the order of fields? This is the code I have used to add the field. add_action('login_form', 'add_login_auth'); function add_login_auth() { $klantnr = (isset($_POST['klantnr'])) ? $_POST['klantnr'] : ''; ?> <p> <label for="klantnr">Klantnummer<br> <input type="text" tabindex="20" size="10" value="" class="input" id="klantnr" name="klantnr"></label> </p> <?php }
Unfortunately there is no hook for above the fields (perhaps you might want to submit a patch/feature request on trac?) You'll have to get by with JavaScript: <p id="klantnr-field"> <label for="klantnr">Klantnummer<br> <input type="text" tabindex="20" size="10" value="" class="input" id="klantnr" name="klantnr"></label> </p> <script> (function ( form ) { form.insertBefore( document.getElementById( "klantnr-field" ), form.childNodes[0] ) })( document.getElementById( "loginform" ) ); </script> And I hope you'll be sanitizing that `$klantnr` variable if you plan on using it ;)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, login, forms" }