qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
228,588 |
<p>My theme is a very small one page theme which really doesn't need all the scripts, so I've created a few options to remove <code>wp_head()</code> and <code>wp_footer()</code> so the user can choose if they want to enable or disable those.</p>
<p>However, my site does use the <code>custom_background()</code> feature which is placed in the <code>wp_head()</code> so when they disable <code>wp_head()</code>, they will also remove the background.</p>
<p>Is there a way to place the <code>custom_background()</code> code outside the <code>wp_head()</code>?</p>
|
[
{
"answer_id": 228592,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 3,
"selected": true,
"text": "<p><code>custom_background()</code> places the CSS to <code>wp_head()</code> as you mentioned so to get those CSS as if you don't have <code>wp_head()</code> in your header, these tweaks from the core files would help:</p>\n\n<pre><code>function wpse_228588_background_image_css() {\n $background_styles = '';\n if ( $bgcolor = get_background_color() )\n $background_styles .= 'background-color: #' . $bgcolor . ';';\n\n $background_image_thumb = get_background_image();\n if ( $background_image_thumb ) {\n $background_image_thumb = esc_url( set_url_scheme( get_theme_mod( 'background_image_thumb', str_replace( '%', '%%', $background_image_thumb ) ) ) );\n\n // Background-image URL must be single quote, see below.\n $background_styles .= ' background-image: url(\\'' . $background_image_thumb . '\\');'\n . ' background-repeat: ' . get_theme_mod( 'background_repeat', get_theme_support( 'custom-background', 'default-repeat' ) ) . ';'\n . ' background-position: top ' . get_theme_mod( 'background_position_x', get_theme_support( 'custom-background', 'default-position-x' ) );\n }\n return $background_styles; // CSS\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code><style type=\"text/css\" media=\"all\">body{<?php echo wpse_228588_background_image_css(); ?>}</style>\n</code></pre>\n"
},
{
"answer_id": 228593,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, this is possible. You can access the custom background image directly with <a href=\"https://codex.wordpress.org/Function_Reference/get_background_image\" rel=\"nofollow\"><code>get_background_image()</code></a>, like this:</p>\n\n<pre><code>echo '<style>body.custom-background {background-image: url(' . get_background_image() . ');} </style>';\n</code></pre>\n"
}
] |
2016/06/02
|
[
"https://wordpress.stackexchange.com/questions/228588",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94984/"
] |
My theme is a very small one page theme which really doesn't need all the scripts, so I've created a few options to remove `wp_head()` and `wp_footer()` so the user can choose if they want to enable or disable those.
However, my site does use the `custom_background()` feature which is placed in the `wp_head()` so when they disable `wp_head()`, they will also remove the background.
Is there a way to place the `custom_background()` code outside the `wp_head()`?
|
`custom_background()` places the CSS to `wp_head()` as you mentioned so to get those CSS as if you don't have `wp_head()` in your header, these tweaks from the core files would help:
```
function wpse_228588_background_image_css() {
$background_styles = '';
if ( $bgcolor = get_background_color() )
$background_styles .= 'background-color: #' . $bgcolor . ';';
$background_image_thumb = get_background_image();
if ( $background_image_thumb ) {
$background_image_thumb = esc_url( set_url_scheme( get_theme_mod( 'background_image_thumb', str_replace( '%', '%%', $background_image_thumb ) ) ) );
// Background-image URL must be single quote, see below.
$background_styles .= ' background-image: url(\'' . $background_image_thumb . '\');'
. ' background-repeat: ' . get_theme_mod( 'background_repeat', get_theme_support( 'custom-background', 'default-repeat' ) ) . ';'
. ' background-position: top ' . get_theme_mod( 'background_position_x', get_theme_support( 'custom-background', 'default-position-x' ) );
}
return $background_styles; // CSS
}
```
Usage:
```
<style type="text/css" media="all">body{<?php echo wpse_228588_background_image_css(); ?>}</style>
```
|
228,589 |
<p>I would like to link a user to a custom post type (college). Does anyone know a good way to do this?</p>
<p>The ultimate goal is to display links to view and edit their college</p>
<p>I've been using Advanced Custom Fields but none of the Relational fields seem to support linking users</p>
|
[
{
"answer_id": 228721,
"author": "kcbluewave890",
"author_id": 95196,
"author_profile": "https://wordpress.stackexchange.com/users/95196",
"pm_score": 2,
"selected": false,
"text": "<p>if you are trying to link up the post in the user profile area, the code below might be a good starting point. You could put this in your functions.php file. The first function displays a select tag with all the posts from your custom post type in the user profile section. The option value is the post id, and the title is the post name. The next function saves the user profile information, adds or updates a user meta field(in this case, I used 'userphotos' that will store the ID of the post. When you want to display the user's posts anywhere on the site, you can use WP_User_Query, and display the user's metadata. If you are looking to include multiple posts, a check box or use the multiple attribute in the select tag, and store the posts as an array in the metafield. The code below isn't tested, and wasn't quite sure how you wanted the user profile section to function, so apologies if this isn't what you are looking for. </p>\n\n<pre><code><?php\nfunction add_extra_user_fields( $user ) {\n $userid = get_user_meta($user->ID);\n $args = array(\n 'post_type' => 'your_post_type',\n 'posts_per_page' => -1,\n );\n $query = new WP_Query($args);\n ?>\n <select name=\"testprofile\">Select a Post</p>\n <?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>\n <option value=\"<?php the_ID(); ?>\" \n if (get_user_meta( $userid, userphotos, true) == $userid ){ \n echo 'selected'; \n }?>>\n <?php the_title(); ?>\n </option>\n <?php endwhile; endif; ?>\n </select>\n <?php\n}\n\nadd_action( 'show_user_profile', 'add_extra_user_fields' );\nadd_action( 'edit_user_profile', 'add_extra_user_fields' );\n\nfunction save_extra_user_fields( $user_id ) {\n update_user_meta( $user_id, 'userphotos', sanitize_text_field( $_POST['testprofile'] ) );\n}\n\nadd_action( 'personal_options_update', 'save_extra_user_fields' );\nadd_action( 'edit_user_profile_update', 'save_extra_user_fields' );\n</code></pre>\n"
},
{
"answer_id": 242847,
"author": "Milan Švehla",
"author_id": 105015,
"author_profile": "https://wordpress.stackexchange.com/users/105015",
"pm_score": 1,
"selected": false,
"text": "<p>Do not have enough reputation to comment, so:</p>\n\n<p>Thanks to kcbluewave890 I found a solution, but there were some things to fix. Here is my working code for functions.php file:</p>\n\n<pre><code>function add_extra_user_fields( $user ) {\n$args = array(\n 'post_type' => 'YOUR_POST_TYPE',\n 'posts_per_page' => -1,\n);\n$query = new WP_Query($args);\n?>\n<h3>Select Your College</h3>\n<select name=\"college\">\n <?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>\n <option value=\"<?php the_ID(); ?>\"\n <? if (get_user_meta( $user->ID, \"college\", true) == get_the_ID() ) echo 'selected'; ?>>\n <?php the_title(); ?>\n </option>\n<?php endwhile; endif; ?>\n</select>\n<?php\n}\n\nadd_action( 'show_user_profile', 'add_extra_user_fields' );\nadd_action( 'edit_user_profile', 'add_extra_user_fields' );\n\nfunction save_extra_user_fields( $user_id ) {\nupdate_user_meta( $user_id, 'college', sanitize_text_field( $_POST['college'] ) );\n}\n\nadd_action( 'personal_options_update', 'save_extra_user_fields' );\nadd_action( 'edit_user_profile_update', 'save_extra_user_fields' );\n</code></pre>\n"
}
] |
2016/06/02
|
[
"https://wordpress.stackexchange.com/questions/228589",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51830/"
] |
I would like to link a user to a custom post type (college). Does anyone know a good way to do this?
The ultimate goal is to display links to view and edit their college
I've been using Advanced Custom Fields but none of the Relational fields seem to support linking users
|
if you are trying to link up the post in the user profile area, the code below might be a good starting point. You could put this in your functions.php file. The first function displays a select tag with all the posts from your custom post type in the user profile section. The option value is the post id, and the title is the post name. The next function saves the user profile information, adds or updates a user meta field(in this case, I used 'userphotos' that will store the ID of the post. When you want to display the user's posts anywhere on the site, you can use WP\_User\_Query, and display the user's metadata. If you are looking to include multiple posts, a check box or use the multiple attribute in the select tag, and store the posts as an array in the metafield. The code below isn't tested, and wasn't quite sure how you wanted the user profile section to function, so apologies if this isn't what you are looking for.
```
<?php
function add_extra_user_fields( $user ) {
$userid = get_user_meta($user->ID);
$args = array(
'post_type' => 'your_post_type',
'posts_per_page' => -1,
);
$query = new WP_Query($args);
?>
<select name="testprofile">Select a Post</p>
<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<option value="<?php the_ID(); ?>"
if (get_user_meta( $userid, userphotos, true) == $userid ){
echo 'selected';
}?>>
<?php the_title(); ?>
</option>
<?php endwhile; endif; ?>
</select>
<?php
}
add_action( 'show_user_profile', 'add_extra_user_fields' );
add_action( 'edit_user_profile', 'add_extra_user_fields' );
function save_extra_user_fields( $user_id ) {
update_user_meta( $user_id, 'userphotos', sanitize_text_field( $_POST['testprofile'] ) );
}
add_action( 'personal_options_update', 'save_extra_user_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_fields' );
```
|
228,591 |
<p>I'm following <a href="http://codex.wordpress.org/Changing_File_Permissions#Permission_Scheme_for_WordPress" rel="noreferrer">Changing File Permissions « WordPress Codex</a>, yet when I'm try to update and/or install <code>plugin</code> and/or <code>theme</code> through <code>wp-admin</code>, I'm getting following:</p>
<blockquote>
<p>To perform the requested action, WordPress needs to access your web
server. Please enter your FTP credentials to proceed. If you do not
remember your credentials, you should contact your web host.</p>
</blockquote>
<p>from file system level:</p>
<pre><code># ls -ld wp-content/ wp-content/plugins/ wp-content/themes/
drwxrwxr-x. 6 root apache 4096 Jun 2 12:01 wp-content/
drwxrwxr-x. 28 root apache 4096 Jun 2 00:00 wp-content/plugins/
drwxrwxr-x. 11 root apache 4096 May 11 16:34 wp-content/themes/
#
</code></pre>
<p><code>httpd</code> runs as <code>apache</code>:</p>
<pre><code>$ ps auxw | grep httpd
root 20158 0.0 0.1 533080 26192 ? Ss 15:03 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20233 0.0 0.2 612608 34908 ? S 15:03 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20234 0.0 0.2 538772 46904 ? S 15:03 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20235 0.0 0.1 536832 24268 ? S 15:03 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20236 0.0 0.2 626272 35640 ? S 15:03 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20237 0.0 0.0 535296 9592 ? S 15:03 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20322 0.0 0.1 537088 26620 ? S 15:03 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20380 0.0 0.2 626060 33816 ? S 15:04 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20429 0.0 0.1 538216 29184 ? S 15:04 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20447 0.0 0.2 629380 43180 ? S 15:04 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20448 0.0 0.2 626172 35224 ? S 15:04 0:00 /usr/sbin/httpd -DFOREGROUND
alexus 24073 0.0 0.0 112652 972 pts/9 R+ 15:13 0:00 grep --color=auto httpd
$
</code></pre>
<p>I'd like to be able to perform requested action (<code>install</code> and/or <code>update</code>) through <code>/wp-admin</code> <em>without</em> FTP credentials.</p>
<p>How can I do that?</p>
|
[
{
"answer_id": 228643,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Not a direct answer, but probably has to be said - this is one problem you should avoid solving unless you are talking about a local development in which case you can just set permissions to 777.</p>\n\n<p>The reason is that if the webserver can overwrite your code, then any malicious code running on it will be able to do that as well. The risk is just so much bigger than the convenience of saving few seconds by not having to type the ftp credentials.</p>\n"
},
{
"answer_id": 235075,
"author": "Syamraj K",
"author_id": 100505,
"author_profile": "https://wordpress.stackexchange.com/users/100505",
"pm_score": 5,
"selected": false,
"text": "<p>This means that WordPress is having limited permission for making changes in the folder that it was installed.</p>\n<p>In-order to fix this, all that you need to do is provide necessary permissions for the same.</p>\n<p>Run the following Command in your Terminal / Putty / Commandline Prompt after connecting to your Server via SSH:</p>\n<pre><code>sudo chown -R apache:apache /var/www/html\n</code></pre>\n"
},
{
"answer_id": 271003,
"author": "Narendra Solanki",
"author_id": 117953,
"author_profile": "https://wordpress.stackexchange.com/users/117953",
"pm_score": 7,
"selected": false,
"text": "<p>Add the following to wp-config.php:</p>\n\n<pre><code>define( 'FS_METHOD', 'direct' );\n</code></pre>\n\n<p>Let me know how it works for you.</p>\n"
},
{
"answer_id": 277880,
"author": "w00t",
"author_id": 126439,
"author_profile": "https://wordpress.stackexchange.com/users/126439",
"pm_score": 3,
"selected": false,
"text": "<p>Even though it is totally correct to have the ownership as <code>root:apache</code> with permissions 775, and httpd to run as <code>apache</code>, Wordpress does not like this. It wants the owner to be <code>apache</code>, as per <code>wp-admin/includes/file.php</code>:</p>\n\n<pre><code> // Attempt to determine the file owner of the WordPress files, and that of newly created files\n $wp_file_owner = $temp_file_owner = false;\n if ( function_exists('fileowner') ) {\n $wp_file_owner = @fileowner( __FILE__ );\n $temp_file_owner = @fileowner( $temp_file_name );\n }\n</code></pre>\n\n<p>Yours would be:<br>\nwp_file_owner = root<br>\ntemp_file_owner = apache</p>\n\n<pre><code>if ( $wp_file_owner !== false && $wp_file_owner === $temp_file_owner ) {\n // WordPress is creating files as the same owner as the WordPress files,\n // this means it's safe to modify & create new files via PHP.\n $method = 'direct';\n $GLOBALS['_wp_filesystem_direct_method'] = 'file_owner';\n} elseif ( $allow_relaxed_file_ownership ) {\n // The $context directory is writable, and $allow_relaxed_file_ownership is set, this means we can modify files\n // safely in this directory. This mode doesn't create new files, only alter existing ones.\n $method = 'direct';\n $GLOBALS['_wp_filesystem_direct_method'] = 'relaxed_ownership';\n}\n</code></pre>\n\n<p>If $wp_file_owner is same as $temp_file_owner then proceed. Yours would be caught in the elseif, which according to the comment does not allow delete/create, but only updates (I verified this by updating the code of a plugin from within Wordpress, and it worked).</p>\n\n<p>Note I did not extensively look through the code, this is just my quick interpretation. I had the same problem and once I switched user:group so that the httpd user is also the file owner, it did not prompt for FTP credentials anymore.</p>\n"
},
{
"answer_id": 302455,
"author": "Charles",
"author_id": 15605,
"author_profile": "https://wordpress.stackexchange.com/users/15605",
"pm_score": 1,
"selected": false,
"text": "<p>Although the question is not that new anymore I want to add my two cents on this issue also.</p>\n\n<p>A lot of ppl have Centos(7) on their VPS server and following code lines could solve their problem.</p>\n\n<p>Imho has all to do with SELinux which withholds WordPress from doing it's job as wished. It goes to far to explain what <a href=\"https://wiki.centos.org/HowTos/SELinux\" rel=\"nofollow noreferrer\">SELinux</a> is and what it does. FYI the introduction starts with:<br /></p>\n\n<blockquote>\n <p>Security-Enhanced Linux (SELinux) is a mandatory access control (MAC) security mechanism implemented in the kernel.</p>\n</blockquote>\n\n<p><em>Only 3 steps to folow:</em><br /></p>\n\n<ul>\n<li>1 Open a terminal (or access the server through SSH)</li>\n<li>2 Add following code line\n<code>chcon -R -t httpd_sys_content_t /var/www/html/wordpress</code></li>\n<li>3 Add second code line\n<code>chcon -R -t httpd_sys_rw_content_t /var/www/html/wordpress</code></li>\n</ul>\n\n<blockquote>\n <p>No reboot from the server or restart from any daemon needed.</p>\n</blockquote>\n\n<p>I won't say it helps everybody but for those who didn't disable SELinux it should be a relieve. </p>\n\n<p>Cheers</p>\n\n<p><strong>Note: Please adjust to your own needs (meaning path to WordPress)</strong></p>\n\n<p><em>edit: be sure to remove the line <code>define(\"FS_METHOD\", \"direct\");</code> when it is/was used in <code>wp-config.php</code> because that's absolutely a no go when above code lines do as wanted.</em></p>\n"
},
{
"answer_id": 311642,
"author": "MarkPraschan",
"author_id": 129862,
"author_profile": "https://wordpress.stackexchange.com/users/129862",
"pm_score": 0,
"selected": false,
"text": "<p>In my case, I solved this by switching from GIT back to FTP mode.</p>\n\n<p>No more warning.</p>\n\n<p>Perhaps that'll help somebody else too.</p>\n"
},
{
"answer_id": 413840,
"author": "shimii",
"author_id": 186313,
"author_profile": "https://wordpress.stackexchange.com/users/186313",
"pm_score": 0,
"selected": false,
"text": "<p>add the following to your wp-config.php file in between the 2 comments</p>\n<pre><code>/* Add any custom values between this line and the "stop editing" line. */\n\ndefine( 'FS_METHOD', 'direct' );\n\n/* That's all, stop editing! Happy publishing. */\n</code></pre>\n"
}
] |
2016/06/02
|
[
"https://wordpress.stackexchange.com/questions/228591",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3255/"
] |
I'm following [Changing File Permissions « WordPress Codex](http://codex.wordpress.org/Changing_File_Permissions#Permission_Scheme_for_WordPress), yet when I'm try to update and/or install `plugin` and/or `theme` through `wp-admin`, I'm getting following:
>
> To perform the requested action, WordPress needs to access your web
> server. Please enter your FTP credentials to proceed. If you do not
> remember your credentials, you should contact your web host.
>
>
>
from file system level:
```
# ls -ld wp-content/ wp-content/plugins/ wp-content/themes/
drwxrwxr-x. 6 root apache 4096 Jun 2 12:01 wp-content/
drwxrwxr-x. 28 root apache 4096 Jun 2 00:00 wp-content/plugins/
drwxrwxr-x. 11 root apache 4096 May 11 16:34 wp-content/themes/
#
```
`httpd` runs as `apache`:
```
$ ps auxw | grep httpd
root 20158 0.0 0.1 533080 26192 ? Ss 15:03 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20233 0.0 0.2 612608 34908 ? S 15:03 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20234 0.0 0.2 538772 46904 ? S 15:03 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20235 0.0 0.1 536832 24268 ? S 15:03 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20236 0.0 0.2 626272 35640 ? S 15:03 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20237 0.0 0.0 535296 9592 ? S 15:03 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20322 0.0 0.1 537088 26620 ? S 15:03 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20380 0.0 0.2 626060 33816 ? S 15:04 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20429 0.0 0.1 538216 29184 ? S 15:04 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20447 0.0 0.2 629380 43180 ? S 15:04 0:00 /usr/sbin/httpd -DFOREGROUND
apache 20448 0.0 0.2 626172 35224 ? S 15:04 0:00 /usr/sbin/httpd -DFOREGROUND
alexus 24073 0.0 0.0 112652 972 pts/9 R+ 15:13 0:00 grep --color=auto httpd
$
```
I'd like to be able to perform requested action (`install` and/or `update`) through `/wp-admin` *without* FTP credentials.
How can I do that?
|
Add the following to wp-config.php:
```
define( 'FS_METHOD', 'direct' );
```
Let me know how it works for you.
|
228,595 |
<p>The scenario is that I need to add an HTML banner under a slideshow which is a shortcode in the homepage content. I personally hate adding a bunch of <code>div</code> tags to the TinyMCE editor so I'm trying to filter <code>the_content</code> and add my HTML after the specific shortcode. Below is a solution but I wasn't sure if there was a better way to go about this.</p>
<p>What's the best way to add content after specific shortcodes?</p>
|
[
{
"answer_id": 228596,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 2,
"selected": false,
"text": "<p>This is a solution I've come up with after refining it a bit. The below <em>should</em> only run if the shortcode exists in the content. It loops through all the shortcodes to find the specific one we need, replaces it with the shortcode plus the new HTML:</p>\n\n\n\n<pre class=\"lang-php prettyprint-override\"><code>function insert_after_shortcode( $content ) {\n if( ! has_shortcode( $content, 'shortcode_name' ) ) {\n return $content;\n }\n\n ob_start();\n ?>\n\n <div id=\"bannerHTML\"><!-- banner HTML goes here --></div>\n\n <?php\n\n $additional_html = ob_get_clean();\n preg_match_all( '/'. get_shortcode_regex() .'/s', $content, $matches, PREG_SET_ORDER );\n\n if( ! empty( $matches ) ) {\n\n foreach ( $matches as $shortcode ) {\n\n if ( 'shortcode_name' === $shortcode[2] ) {\n $new_content = $shortcode[0] . $additional_html;\n $content = str_replace( $shortcode[0], $new_content, $content );\n }\n }\n }\n\n return $content;\n}\nadd_filter( 'the_content', 'insert_after_shortcode' );\n</code></pre>\n"
},
{
"answer_id": 228597,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>I wonder if you could override the <code>[rev_slider]</code> with this kind of wrapper:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_shortcode( 'rev_slider', function( $atts = array(), $content = '' )\n{\n $html = '';\n\n // Your custom banner HTML\n $banner = '<div id=\"bannerHTML\"><!-- banner HTML goes here --></div>';\n\n // Append your banner HTML to the revslider's output\n if( function_exists( 'rev_slider_shortcode' ) )\n $html = rev_slider_shortcode( $atts, $content ) . $banner;\n\n return $html;\n\n} );\n</code></pre>\n\n<p>Where we assume that the original shortcode's callback is <code>rev_slider_shortcode()</code>. We have to run the after the original one.</p>\n\n<h2>Update</h2>\n\n<p>As suggested by @Sumit we could try to get the shortcode's callback from the <code>$shortcode_tags</code> array.</p>\n\n<p>Here's an example:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'after_setup_theme', function() use ( &$shortcode_tags )\n{\n // Shortcode to override. Edit to your needs\n $shortcode = 'rev_slider';\n\n // Nothing to do if it's not registered as shortcode\n if( ! shortcode_exists( $shortcode ) )\n return; \n\n // Get the shortcode's callback\n $callback = $shortcode_tags[$shortcode];\n\n // Override the shortcode\n add_shortcode( $shortcode, function( $atts = array(), $content = '' ) use ( $callback )\n {\n // Your custom banner HTML\n $banner = '<div id=\"bannerHTML\">123<!-- banner HTML goes here --></div>';\n\n // Append your banner HTML to the revslider's output\n return \n is_callable( $callback ) \n ? call_user_func( $callback, $atts, $content, $callback ) . $banner \n : '';\n } );\n\n}, PHP_INT_MAX );\n</code></pre>\n\n<p>Here we hook late into the <code>after_setup_theme</code> action and use <code>call_user_func()</code> to run the previous shortcode's callback, similar how it's done in <code>do_shortcode_tag()</code>.</p>\n"
}
] |
2016/06/02
|
[
"https://wordpress.stackexchange.com/questions/228595",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/7355/"
] |
The scenario is that I need to add an HTML banner under a slideshow which is a shortcode in the homepage content. I personally hate adding a bunch of `div` tags to the TinyMCE editor so I'm trying to filter `the_content` and add my HTML after the specific shortcode. Below is a solution but I wasn't sure if there was a better way to go about this.
What's the best way to add content after specific shortcodes?
|
I wonder if you could override the `[rev_slider]` with this kind of wrapper:
```php
add_shortcode( 'rev_slider', function( $atts = array(), $content = '' )
{
$html = '';
// Your custom banner HTML
$banner = '<div id="bannerHTML"><!-- banner HTML goes here --></div>';
// Append your banner HTML to the revslider's output
if( function_exists( 'rev_slider_shortcode' ) )
$html = rev_slider_shortcode( $atts, $content ) . $banner;
return $html;
} );
```
Where we assume that the original shortcode's callback is `rev_slider_shortcode()`. We have to run the after the original one.
Update
------
As suggested by @Sumit we could try to get the shortcode's callback from the `$shortcode_tags` array.
Here's an example:
```php
add_action( 'after_setup_theme', function() use ( &$shortcode_tags )
{
// Shortcode to override. Edit to your needs
$shortcode = 'rev_slider';
// Nothing to do if it's not registered as shortcode
if( ! shortcode_exists( $shortcode ) )
return;
// Get the shortcode's callback
$callback = $shortcode_tags[$shortcode];
// Override the shortcode
add_shortcode( $shortcode, function( $atts = array(), $content = '' ) use ( $callback )
{
// Your custom banner HTML
$banner = '<div id="bannerHTML">123<!-- banner HTML goes here --></div>';
// Append your banner HTML to the revslider's output
return
is_callable( $callback )
? call_user_func( $callback, $atts, $content, $callback ) . $banner
: '';
} );
}, PHP_INT_MAX );
```
Here we hook late into the `after_setup_theme` action and use `call_user_func()` to run the previous shortcode's callback, similar how it's done in `do_shortcode_tag()`.
|
228,633 |
<p>I'm using a customized wordpress loop which allows me to style the post a certain way after a certain amount of post. For example, The first three post will be styled the same, the next 4 post will styled differently from the first three and so forth. It also allows me to add <code><div></code> sections between the post.</p>
<p>Here is the code php code I am using to accomplish this. </p>
<pre><code>if (have_posts()) :
$count = 0; $paged = ( get_query_var('paged') > 1 ) ? get_query_var('paged') : 1;
while (have_posts()) : the_post();
$count++;
if ($count <= 3 && $paged === 1) :
if ($count === 1) echo '<div class="break"><h2>Break div | first 3 posts</h2></div>'; ?>
<div class="first-three">
<?php the_title() ?>
</div>
<?php elseif (3 < $count && $count <= 7 && $paged === 1) :
if ($count === 4) echo '<div class="break"><h2>Break div | next 4 posts</h2></div>'; ?>
<div class="next-four">
<?php the_title() ?>
</div>
<?php elseif (7 < $count && $count <= 13 && $paged === 1) :
if ($count === 8) echo '<div class="break"><h2>Break div | next 6 posts</h2></div>'; ?>
<div class="next-six">
<?php the_title() ?>
</div>
<?php elseif (13 < $count && $count <= 20 && $paged === 1) :
if ($count === 14) echo '<div class="break"><h2>Break div | next other 6 posts</h2></div>'; ?>
<div class="next-other-six">
<?php the_title() ?>
</div>
<?php else :
if ($count === 21) echo '<div class="break"><h2>Break div | last 6 posts</h2></div>'; ?>
<div class="last-six">
<?php the_title() ?>
</div>
<?php endif;
endwhile; ?>
<div class="nav-previous alignleft"><?php next_posts_link('Older posts'); ?></div>
<div class="nav-next alignright"><?php previous_posts_link('Newer posts'); ?></div><?php
endif;
</code></pre>
<p>I'm not sure if you needed all of that, but I decided to place it there just in case. </p>
<p>Now here is the part I am having complications with.</p>
<pre><code> <?php elseif (3 < $count && $count <= 7 && $paged === 1) :
if ($count === 4) echo '<div style="clear:both;"></div> <div class="large-6 columns" style="max-width:566px; float:left;"> ', include 'thumbnail-break.php', '</div> '; ?>
</code></pre>
<p>For this part I added the <code>include</code> function to place a template path between the post. It returns the path but it also outputs the number 1 after the content. </p>
<p>How do I get rid of the number 1.</p>
|
[
{
"answer_id": 228596,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 2,
"selected": false,
"text": "<p>This is a solution I've come up with after refining it a bit. The below <em>should</em> only run if the shortcode exists in the content. It loops through all the shortcodes to find the specific one we need, replaces it with the shortcode plus the new HTML:</p>\n\n\n\n<pre class=\"lang-php prettyprint-override\"><code>function insert_after_shortcode( $content ) {\n if( ! has_shortcode( $content, 'shortcode_name' ) ) {\n return $content;\n }\n\n ob_start();\n ?>\n\n <div id=\"bannerHTML\"><!-- banner HTML goes here --></div>\n\n <?php\n\n $additional_html = ob_get_clean();\n preg_match_all( '/'. get_shortcode_regex() .'/s', $content, $matches, PREG_SET_ORDER );\n\n if( ! empty( $matches ) ) {\n\n foreach ( $matches as $shortcode ) {\n\n if ( 'shortcode_name' === $shortcode[2] ) {\n $new_content = $shortcode[0] . $additional_html;\n $content = str_replace( $shortcode[0], $new_content, $content );\n }\n }\n }\n\n return $content;\n}\nadd_filter( 'the_content', 'insert_after_shortcode' );\n</code></pre>\n"
},
{
"answer_id": 228597,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>I wonder if you could override the <code>[rev_slider]</code> with this kind of wrapper:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_shortcode( 'rev_slider', function( $atts = array(), $content = '' )\n{\n $html = '';\n\n // Your custom banner HTML\n $banner = '<div id=\"bannerHTML\"><!-- banner HTML goes here --></div>';\n\n // Append your banner HTML to the revslider's output\n if( function_exists( 'rev_slider_shortcode' ) )\n $html = rev_slider_shortcode( $atts, $content ) . $banner;\n\n return $html;\n\n} );\n</code></pre>\n\n<p>Where we assume that the original shortcode's callback is <code>rev_slider_shortcode()</code>. We have to run the after the original one.</p>\n\n<h2>Update</h2>\n\n<p>As suggested by @Sumit we could try to get the shortcode's callback from the <code>$shortcode_tags</code> array.</p>\n\n<p>Here's an example:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'after_setup_theme', function() use ( &$shortcode_tags )\n{\n // Shortcode to override. Edit to your needs\n $shortcode = 'rev_slider';\n\n // Nothing to do if it's not registered as shortcode\n if( ! shortcode_exists( $shortcode ) )\n return; \n\n // Get the shortcode's callback\n $callback = $shortcode_tags[$shortcode];\n\n // Override the shortcode\n add_shortcode( $shortcode, function( $atts = array(), $content = '' ) use ( $callback )\n {\n // Your custom banner HTML\n $banner = '<div id=\"bannerHTML\">123<!-- banner HTML goes here --></div>';\n\n // Append your banner HTML to the revslider's output\n return \n is_callable( $callback ) \n ? call_user_func( $callback, $atts, $content, $callback ) . $banner \n : '';\n } );\n\n}, PHP_INT_MAX );\n</code></pre>\n\n<p>Here we hook late into the <code>after_setup_theme</code> action and use <code>call_user_func()</code> to run the previous shortcode's callback, similar how it's done in <code>do_shortcode_tag()</code>.</p>\n"
}
] |
2016/06/03
|
[
"https://wordpress.stackexchange.com/questions/228633",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/95154/"
] |
I'm using a customized wordpress loop which allows me to style the post a certain way after a certain amount of post. For example, The first three post will be styled the same, the next 4 post will styled differently from the first three and so forth. It also allows me to add `<div>` sections between the post.
Here is the code php code I am using to accomplish this.
```
if (have_posts()) :
$count = 0; $paged = ( get_query_var('paged') > 1 ) ? get_query_var('paged') : 1;
while (have_posts()) : the_post();
$count++;
if ($count <= 3 && $paged === 1) :
if ($count === 1) echo '<div class="break"><h2>Break div | first 3 posts</h2></div>'; ?>
<div class="first-three">
<?php the_title() ?>
</div>
<?php elseif (3 < $count && $count <= 7 && $paged === 1) :
if ($count === 4) echo '<div class="break"><h2>Break div | next 4 posts</h2></div>'; ?>
<div class="next-four">
<?php the_title() ?>
</div>
<?php elseif (7 < $count && $count <= 13 && $paged === 1) :
if ($count === 8) echo '<div class="break"><h2>Break div | next 6 posts</h2></div>'; ?>
<div class="next-six">
<?php the_title() ?>
</div>
<?php elseif (13 < $count && $count <= 20 && $paged === 1) :
if ($count === 14) echo '<div class="break"><h2>Break div | next other 6 posts</h2></div>'; ?>
<div class="next-other-six">
<?php the_title() ?>
</div>
<?php else :
if ($count === 21) echo '<div class="break"><h2>Break div | last 6 posts</h2></div>'; ?>
<div class="last-six">
<?php the_title() ?>
</div>
<?php endif;
endwhile; ?>
<div class="nav-previous alignleft"><?php next_posts_link('Older posts'); ?></div>
<div class="nav-next alignright"><?php previous_posts_link('Newer posts'); ?></div><?php
endif;
```
I'm not sure if you needed all of that, but I decided to place it there just in case.
Now here is the part I am having complications with.
```
<?php elseif (3 < $count && $count <= 7 && $paged === 1) :
if ($count === 4) echo '<div style="clear:both;"></div> <div class="large-6 columns" style="max-width:566px; float:left;"> ', include 'thumbnail-break.php', '</div> '; ?>
```
For this part I added the `include` function to place a template path between the post. It returns the path but it also outputs the number 1 after the content.
How do I get rid of the number 1.
|
I wonder if you could override the `[rev_slider]` with this kind of wrapper:
```php
add_shortcode( 'rev_slider', function( $atts = array(), $content = '' )
{
$html = '';
// Your custom banner HTML
$banner = '<div id="bannerHTML"><!-- banner HTML goes here --></div>';
// Append your banner HTML to the revslider's output
if( function_exists( 'rev_slider_shortcode' ) )
$html = rev_slider_shortcode( $atts, $content ) . $banner;
return $html;
} );
```
Where we assume that the original shortcode's callback is `rev_slider_shortcode()`. We have to run the after the original one.
Update
------
As suggested by @Sumit we could try to get the shortcode's callback from the `$shortcode_tags` array.
Here's an example:
```php
add_action( 'after_setup_theme', function() use ( &$shortcode_tags )
{
// Shortcode to override. Edit to your needs
$shortcode = 'rev_slider';
// Nothing to do if it's not registered as shortcode
if( ! shortcode_exists( $shortcode ) )
return;
// Get the shortcode's callback
$callback = $shortcode_tags[$shortcode];
// Override the shortcode
add_shortcode( $shortcode, function( $atts = array(), $content = '' ) use ( $callback )
{
// Your custom banner HTML
$banner = '<div id="bannerHTML">123<!-- banner HTML goes here --></div>';
// Append your banner HTML to the revslider's output
return
is_callable( $callback )
? call_user_func( $callback, $atts, $content, $callback ) . $banner
: '';
} );
}, PHP_INT_MAX );
```
Here we hook late into the `after_setup_theme` action and use `call_user_func()` to run the previous shortcode's callback, similar how it's done in `do_shortcode_tag()`.
|
228,639 |
<p>I can't figure out the the code for - How to retain the values from dropdown category lists after wrong form submission? Any suggesstions, thanx in advance.</p>
<pre><code><select class="selectpicker btn-block" name="coupon_cat" id="category" >
<option selected value=""> Категори Сонгох</option>
<?php
$args['exclude'] = "12,20"; // omit these two categories
$categories = get_categories($args);
foreach($categories as $category) { ?>
<option value="<?php echo $category->term_id;?>"><?php echo $category->name;?>
</option>
<?php } ?</select>
</code></pre>
|
[
{
"answer_id": 228644,
"author": "Ashok Dhaduk",
"author_id": 81215,
"author_profile": "https://wordpress.stackexchange.com/users/81215",
"pm_score": 0,
"selected": false,
"text": "<p>You can check with $_REQUEST['coupon_cat'], Which gives value of selected category then compare it with your loop value so, you can make it selected.</p>\n\n<p>$_REQUEST['coupon_cat'] will help you. </p>\n"
},
{
"answer_id": 228646,
"author": "Paul",
"author_id": 74445,
"author_profile": "https://wordpress.stackexchange.com/users/74445",
"pm_score": 1,
"selected": false,
"text": "<p>Like Ash was saying, something like this using $_REQUEST or $_POST will do it.</p>\n\n<pre><code><?php\n $args['exclude'] = \"12,20\"; // omit these two categories\n $categories = get_categories($args);\n?>\n<select class=\"selectpicker btn-block\" name=\"coupon_cat\" id=\"category\">\n <option value=\"\">Категори Сонгох</option> <!-- if nothing else is selected, this will be selected automatically -->\n <?php foreach($categories as $category): ?>\n <?php $selected = (isset($_REQUEST['coupon_cat']) && $_REQUEST['coupon_cat'] == $category->term_id)?'selected=\"selected\"':''; ?>\n <option value=\"<?php echo $category->term_id;?>\" <?php echo $selected ?>><?php echo $category->name; ?></option>\n <?php endforeach; ?>\n</select>\n</code></pre>\n"
}
] |
2016/06/03
|
[
"https://wordpress.stackexchange.com/questions/228639",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93692/"
] |
I can't figure out the the code for - How to retain the values from dropdown category lists after wrong form submission? Any suggesstions, thanx in advance.
```
<select class="selectpicker btn-block" name="coupon_cat" id="category" >
<option selected value=""> Категори Сонгох</option>
<?php
$args['exclude'] = "12,20"; // omit these two categories
$categories = get_categories($args);
foreach($categories as $category) { ?>
<option value="<?php echo $category->term_id;?>"><?php echo $category->name;?>
</option>
<?php } ?</select>
```
|
Like Ash was saying, something like this using $\_REQUEST or $\_POST will do it.
```
<?php
$args['exclude'] = "12,20"; // omit these two categories
$categories = get_categories($args);
?>
<select class="selectpicker btn-block" name="coupon_cat" id="category">
<option value="">Категори Сонгох</option> <!-- if nothing else is selected, this will be selected automatically -->
<?php foreach($categories as $category): ?>
<?php $selected = (isset($_REQUEST['coupon_cat']) && $_REQUEST['coupon_cat'] == $category->term_id)?'selected="selected"':''; ?>
<option value="<?php echo $category->term_id;?>" <?php echo $selected ?>><?php echo $category->name; ?></option>
<?php endforeach; ?>
</select>
```
|
228,668 |
<p>I must disable a discount plugin for certain user role, I have wrote this and put in the child-theme <code>functions.php</code></p>
<pre><code>global $woocommerce;
get_currentuserinfo();
global $current_user;
if ($current_user->ID) {
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
if ($user_role == 'B2B') {
deactivate_plugins('/httpdocs/wp-content/plugins/woocommerce-payment-discounts/woocommerce-payment-discounts.php', false);
}
}
</code></pre>
<p>But this doesn't work, why? Is it correct? and the deactivation is only for the user session?</p>
|
[
{
"answer_id": 228684,
"author": "TomC",
"author_id": 36980,
"author_profile": "https://wordpress.stackexchange.com/users/36980",
"pm_score": 2,
"selected": true,
"text": "<p>You should use the <code>wc_payment_discounts_apply_discount filter</code>. </p>\n\n<p>Try something like the following:</p>\n\n<pre><code>function remove_privato_discounts() { \n global $woocommerce; \n get_currentuserinfo(); \n global $current_user; \n if ($current_user->ID) { \n $user_roles = $current_user->roles; \n $user_role = array_shift($user_roles); \n if ( $user_role !== 'b2b') { \n $discount = 0; \n $woocommerce->cart->discount_total = $discount; \n return true; // Do not apply discount to privato \n } \n } \n return false; \n } \nadd_filter( 'wc_payment_discounts_apply_discount', 'remove_privato_discounts'); \n</code></pre>\n"
},
{
"answer_id": 228900,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>You can not \"deactivate\" plugins based on any condition since your code will run only after the plugin have been already initialized, and you can't reverse the initialization.</p>\n\n<p>You should target disabling a specific functionality of the plugin, but unless it has a documentation which specifically suggests how to do it, I would stay away from doing such a thing as some functionality might depend on another, and disabling part of it might leave the whole system in a non stable state with unforeseen implications. At the very minimum you should make sure you understand how the whole plugin works before doing such a thing. In addition you should be prepared that future upgrades of the plugin will not work the same way and will cause your code to break.</p>\n"
}
] |
2016/06/03
|
[
"https://wordpress.stackexchange.com/questions/228668",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94422/"
] |
I must disable a discount plugin for certain user role, I have wrote this and put in the child-theme `functions.php`
```
global $woocommerce;
get_currentuserinfo();
global $current_user;
if ($current_user->ID) {
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
if ($user_role == 'B2B') {
deactivate_plugins('/httpdocs/wp-content/plugins/woocommerce-payment-discounts/woocommerce-payment-discounts.php', false);
}
}
```
But this doesn't work, why? Is it correct? and the deactivation is only for the user session?
|
You should use the `wc_payment_discounts_apply_discount filter`.
Try something like the following:
```
function remove_privato_discounts() {
global $woocommerce;
get_currentuserinfo();
global $current_user;
if ($current_user->ID) {
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
if ( $user_role !== 'b2b') {
$discount = 0;
$woocommerce->cart->discount_total = $discount;
return true; // Do not apply discount to privato
}
}
return false;
}
add_filter( 'wc_payment_discounts_apply_discount', 'remove_privato_discounts');
```
|
228,686 |
<p>I'm trying to show a text area in my customizer, only when a checkbox is selected.
I followed instruction at this post, but my textarea stays hidden.
Any help will be super appreciated!
Thank you</p>
<pre><code>function map_enabled(){
$tsum_options = get_theme_mod( 'tsum_options');
if( empty( $tsum_options['map_code'] ) ) {
return false;
}
return true;
}
function tsum_customize_register( $wp_customize ) {
$wp_customize->add_setting( 'tsum_options[show_map]', array(
'default' => false,
'capability' => 'edit_theme_options',
));
// FRONT BOX CHECK - CONTROL
$wp_customize->add_control( 'show_map', array(
'label' => 'Show Goole Map?',
'section' => 'tsum_contact_section',
'settings' => 'tsum_options[show_map]',
'type' => 'checkbox',
//'priority' => 20,
));
// FRONT BOX TEXT - SETTING
$wp_customize->add_setting('tsum_options[map_code]', array(
'default' => '<iframe src=... ',
'capability' => 'edit_theme_options',
));
// FRONT BOX TEXT - CONTROL
$wp_customize->add_control('map_code', array(
'label' => 'lll',
'description' => 'To embed a map, follow the steps below.<br>
1.) Open Google Maps. <a href="https://www.google.com/maps" target="_blank">Click here.</a><br>
2.) Search for your Location.<br>
3.) Zoom in - optional.<br>
4.) Change to Earth View - optional.<br>
5.) Click on Share<br>
6.) Click on Embed<br>
7.) Select Size => Custom Size.<br>
8.) Type in: 980 x 300<br>
9.) Copy the iframe code<br>
10.) Paste it below<br>
11.) Click on Save and Publish',
'section' => 'tsum_contact_section',
'type' => 'textarea',
'setting' => 'tsum_options[map_code]',
'active_callback' => 'map_enabled',
));
}
add_action( 'customize_register', 'tsum_customize_register' );
</code></pre>
|
[
{
"answer_id": 228684,
"author": "TomC",
"author_id": 36980,
"author_profile": "https://wordpress.stackexchange.com/users/36980",
"pm_score": 2,
"selected": true,
"text": "<p>You should use the <code>wc_payment_discounts_apply_discount filter</code>. </p>\n\n<p>Try something like the following:</p>\n\n<pre><code>function remove_privato_discounts() { \n global $woocommerce; \n get_currentuserinfo(); \n global $current_user; \n if ($current_user->ID) { \n $user_roles = $current_user->roles; \n $user_role = array_shift($user_roles); \n if ( $user_role !== 'b2b') { \n $discount = 0; \n $woocommerce->cart->discount_total = $discount; \n return true; // Do not apply discount to privato \n } \n } \n return false; \n } \nadd_filter( 'wc_payment_discounts_apply_discount', 'remove_privato_discounts'); \n</code></pre>\n"
},
{
"answer_id": 228900,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>You can not \"deactivate\" plugins based on any condition since your code will run only after the plugin have been already initialized, and you can't reverse the initialization.</p>\n\n<p>You should target disabling a specific functionality of the plugin, but unless it has a documentation which specifically suggests how to do it, I would stay away from doing such a thing as some functionality might depend on another, and disabling part of it might leave the whole system in a non stable state with unforeseen implications. At the very minimum you should make sure you understand how the whole plugin works before doing such a thing. In addition you should be prepared that future upgrades of the plugin will not work the same way and will cause your code to break.</p>\n"
}
] |
2016/06/03
|
[
"https://wordpress.stackexchange.com/questions/228686",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/95181/"
] |
I'm trying to show a text area in my customizer, only when a checkbox is selected.
I followed instruction at this post, but my textarea stays hidden.
Any help will be super appreciated!
Thank you
```
function map_enabled(){
$tsum_options = get_theme_mod( 'tsum_options');
if( empty( $tsum_options['map_code'] ) ) {
return false;
}
return true;
}
function tsum_customize_register( $wp_customize ) {
$wp_customize->add_setting( 'tsum_options[show_map]', array(
'default' => false,
'capability' => 'edit_theme_options',
));
// FRONT BOX CHECK - CONTROL
$wp_customize->add_control( 'show_map', array(
'label' => 'Show Goole Map?',
'section' => 'tsum_contact_section',
'settings' => 'tsum_options[show_map]',
'type' => 'checkbox',
//'priority' => 20,
));
// FRONT BOX TEXT - SETTING
$wp_customize->add_setting('tsum_options[map_code]', array(
'default' => '<iframe src=... ',
'capability' => 'edit_theme_options',
));
// FRONT BOX TEXT - CONTROL
$wp_customize->add_control('map_code', array(
'label' => 'lll',
'description' => 'To embed a map, follow the steps below.<br>
1.) Open Google Maps. <a href="https://www.google.com/maps" target="_blank">Click here.</a><br>
2.) Search for your Location.<br>
3.) Zoom in - optional.<br>
4.) Change to Earth View - optional.<br>
5.) Click on Share<br>
6.) Click on Embed<br>
7.) Select Size => Custom Size.<br>
8.) Type in: 980 x 300<br>
9.) Copy the iframe code<br>
10.) Paste it below<br>
11.) Click on Save and Publish',
'section' => 'tsum_contact_section',
'type' => 'textarea',
'setting' => 'tsum_options[map_code]',
'active_callback' => 'map_enabled',
));
}
add_action( 'customize_register', 'tsum_customize_register' );
```
|
You should use the `wc_payment_discounts_apply_discount filter`.
Try something like the following:
```
function remove_privato_discounts() {
global $woocommerce;
get_currentuserinfo();
global $current_user;
if ($current_user->ID) {
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
if ( $user_role !== 'b2b') {
$discount = 0;
$woocommerce->cart->discount_total = $discount;
return true; // Do not apply discount to privato
}
}
return false;
}
add_filter( 'wc_payment_discounts_apply_discount', 'remove_privato_discounts');
```
|
228,690 |
<p><strong>Intro</strong></p>
<p>I have a settings page which includes a setting with a more complicated callback function to save.</p>
<p><strong>Save data</strong></p>
<p>To save the data I use the <code>register_setting()</code> function with a custom sanitize callback. I implemented it exactly as the WordPress settings API explains so this works fine.</p>
<p><strong>Remove data from option</strong></p>
<p>To remove data from this option array I use jQuery in combination with an AJAX callback function.</p>
<p><strong>The problem</strong></p>
<p>The problem is that I cannot use <code>update_option()</code> (in my AJAX callback) when the <code>register_setting()</code> is also active. I know this because when I comment out the <code>register_setting()</code> function, the <code>update_option()</code> suddenly works well, where it with the register_setting() uncommented deletes the option.</p>
<p>Does anyone have experience with this problem and knows what I can do to use both functions to update the option?</p>
<p><strong>Setup and register setting</strong> </p>
<pre><code>function gtp_init_theme_options() {
$page = 'services-settings-page';
/**
* Services settings sections and fields
*/
$section = 'installing_settings_section';
// Add installation settings section
add_settings_section( $section, _x( 'Installing', 'Measure and installing', 'gtp_translate' ), 'gtp_display_installing_settings_section', $page );
// Add and register installation areas
$id = 'installing_data';
add_settings_field( $id, __( 'Installing data', 'gtp_translate' ), 'gtp_settings_installing_data_fields', $page, $section, array( 'id' => $id, 'label_for' => $id ) );
register_setting( 'services-theme-settings', $id, 'gtp_register_installing_data_setting' );
}
add_action( 'admin_init', 'gtp_init_theme_options' );
</code></pre>
<p><strong>The sanitize callback called by the register_setting()</strong></p>
<pre><code>/**
* Sanatizes callback for saving installation areas
*/
function gtp_register_installing_data_setting() {
// Initialize object
$installing = new Installing();
$error = false;
// Check if country isset
if ( ! empty( $_POST['existing_country'] ) ) {
$country = strtolower( $_POST['existing_country'] );
} elseif ( ! empty( $_POST['country'] ) ) {
$country = strtolower( $_POST['country'] );
} else {
$error = true;
}
// Check if zipcode isset
if ( ! empty( $_POST['existing_zipcode_area'] ) ) {
$range = $_POST['existing_zipcode_area'];
} elseif ( ! empty( $_POST['zipcode_from'] ) && ! empty( $_POST['zipcode_to'] ) ) {
$range = $_POST['zipcode_from'] . '-' . $_POST['zipcode_to'];
} else {
$error = true;
}
// Check if product isset
if ( ! empty( $_POST['existing_product'] ) ) {
$product = strtolower( $_POST['existing_product'] );
} elseif ( ! empty( $_POST['product'] ) ) {
$product = strtolower( $_POST['product'] );
} else {
$error = true;
}
// Check if price isset
if ( ! empty( $_POST['price'] ) ) {
$price = str_replace( ',', '.', $_POST['price'] );
} else {
$error = true;
}
// No errors
if ( ! $error ) {
// Add row to data array
$installing->addRow( $country, $range, $product, $price );
// Return data array
return $installing->getData();
}
}
</code></pre>
<p><strong>AJAX callback function</strong></p>
<pre><code>/**
* Remove installing data in admin AJAX handle
*/
function gtp_remove_installing_data() {
// Initialize object
$installing = new Installing();
// Remove product
if ( ! empty( $_POST['country'] ) && ! empty( $_POST['zipcode_area'] ) && ! empty( $_POST['product'] ) ) {
$installing->removeRow( $_POST['country'], $_POST['zipcode_area'], $_POST['product'] );
}
// Remove zipcode area
elseif ( ! empty( $_POST['country'] ) && ! empty( $_POST['zipcode_area'] ) ) {
$installing->removeRow( $_POST['country'], $_POST['zipcode_area'] );
}
// Remove country
elseif ( ! empty( $_POST['country'] ) ) {
$installing->removeRow( $_POST['country'] );
}
// Update
$installing->update();
die;
}
add_action( 'wp_ajax_remove_installing_data', 'gtp_remove_installing_data' );
add_action( 'wp_ajax_nopriv_remove_installing_data', 'gtp_remove_installing_data' );
</code></pre>
<p>I have attached an image of the settings screen for your imagination what kind of project I am working on.</p>
<p><a href="https://i.stack.imgur.com/uLPMO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uLPMO.png" alt="enter image description here"></a></p>
|
[
{
"answer_id": 228711,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>This is just a hunch, but it seems to me that this problem has something to do with the order in which the operations are called.</p>\n\n<p>If you have defined your hooks <code>wp_ajax_remove_installing_data</code> and <code>wp_ajax_nopriv_remove_installing_data</code> in your plugin and hooked that plugin in the usual way into WP with the <code>init</code> hook, it means this code is executed before <code>register_setting</code>, which you hook into <code>admin_init</code>, which is <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow\">later in the queue</a>.</p>\n\n<p>Now, you are updating the option directly, not through the Options API. As you can read at the bottom of the <a href=\"https://codex.wordpress.org/Function_Reference/update_option\" rel=\"nofollow\">codex page on <code>update_option</code></a>, this means the cache is not updated. So, you are deleting the option, but when <code>register_setting</code> is called further on, it gets the value from the cache and sets it again.</p>\n\n<p>The solution would be to <a href=\"http://codex.wordpress.org/Function_Reference/wp_cache_delete\" rel=\"nofollow\">clear the cache</a> after updating the option, or to hook <code>register_setting</code> in <code>init</code> as well and make sure it has a higher priority than your update function, so the latter is executed after the call to <code>register_setting</code>. Disclaimer: I haven't tried this.</p>\n"
},
{
"answer_id": 228712,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 2,
"selected": true,
"text": "<p>Note what happens when you provide sanitize callback in <code>register_setting()</code>. It register a filter to sanitize your options</p>\n\n<pre><code>add_filter( \"sanitize_option_{$option_name}\", $sanitize_callback );\n</code></pre>\n\n<p>Now when you do <code>update_option()</code> then trigger your own function to prevent saving :D</p>\n\n<p>Because <code>update_option()</code> calls <code>$value = sanitize_option( $option, $value );</code></p>\n\n<p><strong>Solution:</strong>\nRemove <code>register_settings()</code> callback before you call <code>update_option()</code>.</p>\n\n<pre><code>function gtp_remove_installing_data() {\n\n //Your code \n\n //Remove sanitizing for adding\n remove_filter( \"sanitize_option_installing_data\", 'gtp_register_installing_data_setting' );\n\n // Update \n $installing->update();\n\n die; \n}\n</code></pre>\n"
}
] |
2016/06/03
|
[
"https://wordpress.stackexchange.com/questions/228690",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25834/"
] |
**Intro**
I have a settings page which includes a setting with a more complicated callback function to save.
**Save data**
To save the data I use the `register_setting()` function with a custom sanitize callback. I implemented it exactly as the WordPress settings API explains so this works fine.
**Remove data from option**
To remove data from this option array I use jQuery in combination with an AJAX callback function.
**The problem**
The problem is that I cannot use `update_option()` (in my AJAX callback) when the `register_setting()` is also active. I know this because when I comment out the `register_setting()` function, the `update_option()` suddenly works well, where it with the register\_setting() uncommented deletes the option.
Does anyone have experience with this problem and knows what I can do to use both functions to update the option?
**Setup and register setting**
```
function gtp_init_theme_options() {
$page = 'services-settings-page';
/**
* Services settings sections and fields
*/
$section = 'installing_settings_section';
// Add installation settings section
add_settings_section( $section, _x( 'Installing', 'Measure and installing', 'gtp_translate' ), 'gtp_display_installing_settings_section', $page );
// Add and register installation areas
$id = 'installing_data';
add_settings_field( $id, __( 'Installing data', 'gtp_translate' ), 'gtp_settings_installing_data_fields', $page, $section, array( 'id' => $id, 'label_for' => $id ) );
register_setting( 'services-theme-settings', $id, 'gtp_register_installing_data_setting' );
}
add_action( 'admin_init', 'gtp_init_theme_options' );
```
**The sanitize callback called by the register\_setting()**
```
/**
* Sanatizes callback for saving installation areas
*/
function gtp_register_installing_data_setting() {
// Initialize object
$installing = new Installing();
$error = false;
// Check if country isset
if ( ! empty( $_POST['existing_country'] ) ) {
$country = strtolower( $_POST['existing_country'] );
} elseif ( ! empty( $_POST['country'] ) ) {
$country = strtolower( $_POST['country'] );
} else {
$error = true;
}
// Check if zipcode isset
if ( ! empty( $_POST['existing_zipcode_area'] ) ) {
$range = $_POST['existing_zipcode_area'];
} elseif ( ! empty( $_POST['zipcode_from'] ) && ! empty( $_POST['zipcode_to'] ) ) {
$range = $_POST['zipcode_from'] . '-' . $_POST['zipcode_to'];
} else {
$error = true;
}
// Check if product isset
if ( ! empty( $_POST['existing_product'] ) ) {
$product = strtolower( $_POST['existing_product'] );
} elseif ( ! empty( $_POST['product'] ) ) {
$product = strtolower( $_POST['product'] );
} else {
$error = true;
}
// Check if price isset
if ( ! empty( $_POST['price'] ) ) {
$price = str_replace( ',', '.', $_POST['price'] );
} else {
$error = true;
}
// No errors
if ( ! $error ) {
// Add row to data array
$installing->addRow( $country, $range, $product, $price );
// Return data array
return $installing->getData();
}
}
```
**AJAX callback function**
```
/**
* Remove installing data in admin AJAX handle
*/
function gtp_remove_installing_data() {
// Initialize object
$installing = new Installing();
// Remove product
if ( ! empty( $_POST['country'] ) && ! empty( $_POST['zipcode_area'] ) && ! empty( $_POST['product'] ) ) {
$installing->removeRow( $_POST['country'], $_POST['zipcode_area'], $_POST['product'] );
}
// Remove zipcode area
elseif ( ! empty( $_POST['country'] ) && ! empty( $_POST['zipcode_area'] ) ) {
$installing->removeRow( $_POST['country'], $_POST['zipcode_area'] );
}
// Remove country
elseif ( ! empty( $_POST['country'] ) ) {
$installing->removeRow( $_POST['country'] );
}
// Update
$installing->update();
die;
}
add_action( 'wp_ajax_remove_installing_data', 'gtp_remove_installing_data' );
add_action( 'wp_ajax_nopriv_remove_installing_data', 'gtp_remove_installing_data' );
```
I have attached an image of the settings screen for your imagination what kind of project I am working on.
[](https://i.stack.imgur.com/uLPMO.png)
|
Note what happens when you provide sanitize callback in `register_setting()`. It register a filter to sanitize your options
```
add_filter( "sanitize_option_{$option_name}", $sanitize_callback );
```
Now when you do `update_option()` then trigger your own function to prevent saving :D
Because `update_option()` calls `$value = sanitize_option( $option, $value );`
**Solution:**
Remove `register_settings()` callback before you call `update_option()`.
```
function gtp_remove_installing_data() {
//Your code
//Remove sanitizing for adding
remove_filter( "sanitize_option_installing_data", 'gtp_register_installing_data_setting' );
// Update
$installing->update();
die;
}
```
|
228,701 |
<p>I found code to show a notification bar on menu and customize it a little. It is working and shown on main menu (primary menu) and footer menu (secondary menu) but I want to show it only main menu. How to do that? Here's what I have:</p>
<pre><code>function my_counter_nav_menu( $menu ) {
$notif_url = bp_core_get_user_domain( bp_loggedin_user_id() ) . 'notifications/';
$friends_url = bp_core_get_user_domain( bp_loggedin_user_id() ) . 'friends/';
$msg_url = bp_core_get_user_domain( bp_loggedin_user_id() ) . 'messages/';
if ( ! is_user_logged_in() ) {
return $menu;
} else {
$notif = '<li><a href=" ' . $notif_url . ' "> <i class="fa fa-bell-o" aria-hidden="true"></i> Notifications [' . bp_notifications_get_unread_notification_count( bp_loggedin_user_id() ) . ']</a></li>';
}
$menu = $menu . $notif;
return $menu;
}
add_filter( 'wp_nav_menu_items', 'my_counter_nav_menu' );
</code></pre>
|
[
{
"answer_id": 228703,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/\" rel=\"nofollow\"><code>wp_nav_menu_items</code></a> filter has a secondary parameter that it passes: <code>$args</code>. What we need to do is set up our filter to accept second args by passing a priority <code>10</code> and the number of args <code>2</code>:</p>\n\n<pre><code>add_filter( 'wp_nav_menu_items', 'my_counter_nav_menu', 10, 2 );\n</code></pre>\n\n<p>Now that we're passing args - if we peek into what it holds we see the following object:</p>\n\n<pre><code>stdClass Object\n(\n [menu] => Menu Name\n [container] => nav\n [container_class] => \n [container_id] => mainNav\n [menu_class] => menu\n [menu_id] => \n [echo] => 1\n [fallback_cb] => wp_page_menu\n [before] => \n [after] => \n [link_before] => \n [link_after] => \n [items_wrap] => <ul id=\"%1$s\" class=\"%2$s\">%3$s</ul>\n [depth] => 0\n [walker] => \n [theme_location] => \n)\n</code></pre>\n\n<p>So if we wanted to in your function we can test against either <code>$args->menu</code> or <code>$args->theme_location</code>:</p>\n\n<pre><code>if( 'Menu Name' === $args->menu ) {\n /* .. Run Code Here .. */\n}\n</code></pre>\n\n<p>Or against the location:</p>\n\n<pre><code>if( 'primary-menu' === $args->theme_location ) {\n /* .. Run Code Here .. */\n}\n</code></pre>\n"
},
{
"answer_id": 228897,
"author": "işte bu",
"author_id": 95193,
"author_profile": "https://wordpress.stackexchange.com/users/95193",
"pm_score": 0,
"selected": false,
"text": "<p>Hi thx for your answering ,but i confused shall I define one of stdclass objects like [menu] => Menu Name or [theme_location] => \nİf so,Is it neccessary to change\nMenu Name which on you typed\n[menu] => Menu Name\nCould u send me hole ordered codes,pls?</p>\n"
}
] |
2016/06/03
|
[
"https://wordpress.stackexchange.com/questions/228701",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/95193/"
] |
I found code to show a notification bar on menu and customize it a little. It is working and shown on main menu (primary menu) and footer menu (secondary menu) but I want to show it only main menu. How to do that? Here's what I have:
```
function my_counter_nav_menu( $menu ) {
$notif_url = bp_core_get_user_domain( bp_loggedin_user_id() ) . 'notifications/';
$friends_url = bp_core_get_user_domain( bp_loggedin_user_id() ) . 'friends/';
$msg_url = bp_core_get_user_domain( bp_loggedin_user_id() ) . 'messages/';
if ( ! is_user_logged_in() ) {
return $menu;
} else {
$notif = '<li><a href=" ' . $notif_url . ' "> <i class="fa fa-bell-o" aria-hidden="true"></i> Notifications [' . bp_notifications_get_unread_notification_count( bp_loggedin_user_id() ) . ']</a></li>';
}
$menu = $menu . $notif;
return $menu;
}
add_filter( 'wp_nav_menu_items', 'my_counter_nav_menu' );
```
|
The [`wp_nav_menu_items`](https://developer.wordpress.org/reference/hooks/wp_nav_menu_items/) filter has a secondary parameter that it passes: `$args`. What we need to do is set up our filter to accept second args by passing a priority `10` and the number of args `2`:
```
add_filter( 'wp_nav_menu_items', 'my_counter_nav_menu', 10, 2 );
```
Now that we're passing args - if we peek into what it holds we see the following object:
```
stdClass Object
(
[menu] => Menu Name
[container] => nav
[container_class] =>
[container_id] => mainNav
[menu_class] => menu
[menu_id] =>
[echo] => 1
[fallback_cb] => wp_page_menu
[before] =>
[after] =>
[link_before] =>
[link_after] =>
[items_wrap] => <ul id="%1$s" class="%2$s">%3$s</ul>
[depth] => 0
[walker] =>
[theme_location] =>
)
```
So if we wanted to in your function we can test against either `$args->menu` or `$args->theme_location`:
```
if( 'Menu Name' === $args->menu ) {
/* .. Run Code Here .. */
}
```
Or against the location:
```
if( 'primary-menu' === $args->theme_location ) {
/* .. Run Code Here .. */
}
```
|
228,752 |
<p>I would like to sort posts by tags in category and archive pages. (Unfortunately there isn’t an <code>orderby</code> parameter for tags. That would make things so easy!)</p>
<p>So a category page would be like this:</p>
<blockquote>
<h1>Category name</h1>
<ul>
<li>Post 1 (Tag 1)</li>
<li>Post 2 (Tag 1)</li>
<li>Post 3 (Tag 1)</li>
<li>Post 4 (Tag 2)</li>
<li>Post 5 (Tag 2)</li>
<li>Post 6 (Tag 2)</li>
<li>Post 7 (Tag 3)</li>
<li>Post 8 (Tag 3)</li>
<li>Post 9 (Tag 3)
...</li>
</ul>
</blockquote>
<p>Or, even better:</p>
<blockquote>
<h1>Category name</h1>
<h3>Tag 1</h3>
<ul>
<li>Post 1</li>
<li>Post 2</li>
<li>Post 3</li>
</ul>
<h3>Tag 2</h3>
<ul>
<li>Post 4</li>
<li>Post 5</li>
<li>Post 6</li>
</ul>
<h3>Tag 3</h3>
<ul>
<li>Post 7</li>
<li>Post 8</li>
<li>Post 9
...</li>
</ul>
</blockquote>
<p>The tags would appear in alphabetical order. The posts below the tags would also appear in alphabetical order.</p>
<p>When a post has more than one tag, it needs to appear multiple times (one for each tag).</p>
<p>Is there any way to do that?</p>
<p>I thought about doing something <a href="https://wordpress.stackexchange.com/a/55386">like this</a>, but I couldn’t come up with a solution that would show only the posts and tags in the category. (The linked code shows all posts and tags.)</p>
<p>Or maybe there is a way to treat tags as a <code>meta_value</code>? Then I could simply use <code>pre_get_posts</code> like this:</p>
<pre><code>add_action( 'pre_get_posts', 'archive_post_order');
function archive_post_order($query){
if(is_archive()):
$query->set( 'orderby', 'meta_value' );
$query->set( 'metakey', 'tag' );
$query->set( 'order', 'ASC' );
endif;
}
</code></pre>
<p>Any ideas are welcome. Thanks in advance.</p>
|
[
{
"answer_id": 228887,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>There really is no sane way to accomplish this, specially if you have posts that are assigned to more than one tag (<em>which is almost always the case</em>). What is very sure, you have you work cut out for you.</p>\n\n<p>Here are some thought and ideas you can persue:</p>\n\n<h2>POSTS WITH MULTIPLE TERMS</h2>\n\n<p>If posts have more than one tag (<em>or any term for that matter</em>) assigned to them, it means that there are more than one relationship to another post or set of posts, and grouping those together will either: (a). Be impossible <strong><em>without</em></strong> duplication, or (b). Be possible, <strong><em>with</em></strong> duplication of posts.</p>\n\n<p>The terms (<em>tags in this case</em>) assigned to a post from a specific taxonomy (<em><code>post_tag</code> in this case</em>) is ordered in a specific way when more than one term exists. Simply grabbing the first term might not always be the term you would want to use. </p>\n\n<p>Sorting tags from <code>get_the_tags()</code> (<em>or the more generic <code>get_the_terms()</code></em>) would require additional PHP sorting to sort the returned array of tag object to suite your needs, or you would want to use a function like <code>wp_get_post_tags()</code> to do the sorting via SQL, but it would require an extra db call. </p>\n\n<p>If you want to sort by the first tag only, then it is quite easy if you sorted the tag array to suite or needs. I'll post example code later</p>\n\n<p><strong>WORKAROUND</strong></p>\n\n<p>If you have posts with multiple tags, you will need to find a specific unique relationship between posts, and according to that, either:</p>\n\n<ul>\n<li><p>assign a custom field with a sortable value to a set of posts and then use <code>pre_get_posts</code> to sort your category pages according to custom field value</p></li>\n<li><p>create a specific taxonomy for this, and then assign a special term to a set of posts and then use the <code>the_posts</code> filter, which I will post, to sort the returned array of posts</p></li>\n</ul>\n\n<p>If you do not mind post duplication, you have a look at <a href=\"https://wordpress.stackexchange.com/a/226250/31545\">this post</a>, this was however done for custom fields, so you would need to break it down and modify it to work with tags, but in essence, the principle by building a multidimentional array, flatten it later and then return a sorted array with duplicate posts remains the same</p>\n\n<h2>POSTS WITH SINGLE TAGS</h2>\n\n<p>If you have posts assigned to one tag only (<em>or you are happy to sort by first tag only</em>), it is quite easy to sort the posts accordingly by using the <code>the_posts</code> filter. You can try the following then (<strong><em>UNTESTED and very basic</em></strong>)</p>\n\n<pre><code>add_filter( 'the_posts', function ( $posts, \\WP_Query $q )\n{\n // Make sure we only target the main query on category pages\n if ( !is_admin()\n && $q->is_main_query()\n && $q->is_category()\n ) {\n // Use usort to sort the posts\n usort( $posts, function( $a, $b )\n {\n return strcasecmp( \n get_the_tags( $a->ID )[0]->name, \n get_the_tags( $b->ID )[0]->name \n );\n });\n }\n}, 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 228928,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": -1,
"selected": false,
"text": "<p>If you have a lot of tags this is going to be pretty inefficient, but still, it should get the job done...</p>\n\n<p>This first part is a little pointless but it will pare down to posts in the category that actually have tags.</p>\n\n<pre><code>add_action('pre_get_posts', 'get_category_tag_posts');\nfunction get_category_tag_posts($q) {\n if ( !is_admin() && $q->is_main_query() && $q->is_category() ) {\n global $categorytags;\n $terms = get_terms('post_tag');\n foreach ($terms as $term) {$categorytags[] = $term->term_id;}\n $q->set('tag__in',$categorytags);\n // inefficient but we cannot know how many posts are needed\n $q->set('posts_per_page',-1); // also makes offset ignored\n }\n}\n</code></pre>\n\n<p>Really just using this part to index some tags etc., in the hope of creating slightly better efficiency by not doubling up later...</p>\n\n<pre><code>add_filter('the_posts', 'get_category_post_tags', 10, 2);\nfunction get_category_post_tags($posts, $q) {\n if ( !is_admin() && $q->is_main_query() && $q->is_category() ) {\n global $categoryposttags, $categoryposts, $posttagnames;\n $categoryposts = $posts;\n if (count($posts) > 0) {\n foreach ($posts as $post) {\n $tagarray = array();\n $tags = get_the_tags($post->ID);\n if ($tags) {\n foreach ($tags as $tag) {\n if (!in_array($tag->term_id,$tagarray)) {$tagarray[] = $tag->term_id;}\n $posttagnames[$tag->term_id] = $tag->name;\n }\n $categoryposttags[$post->ID] = $tagarray;\n }\n }\n }\n }\n</code></pre>\n\n<p>And for the category template:</p>\n\n<pre><code>if (is_category()) {\n\nglobal $categoryposts, $categorytags, $categoryposttags, $posttagnames;\n$postsperpage = get_option('posts_per_page'); $postoffset = 0;\nif (isset($_GET['posts_per_page'])) {$postsperpage = absint($_GET['posts_per_page']);}\nif (isset($_GET['page'])) {$postoffset = (absint($_GET['page'])-1) * $postsperpage;}\n\n$postcount = 0; $displaycount = 0;\nforeach ($categorytags as $categorytag) {\n $theseposts = '';\n foreach ($categoryposts as $post) {\n if (in_array($categorytag,$categoryposttags[$post->ID])) {\n $postcount++;\n if ($postcount > $postoffset) {\n $theseposts .= '<li><h4><a href=\"'.get_permalink($post->ID).'\">'.$post->post_title.'</a></h4><br>';\n if (empty($post->post_excerpt)) {$theseposts .= wp_kses_post(wp_trim_words($post->post_content,50));}\n else {$theseposts .= $post->post_excerpt;}\n $theseposts .= '<br></li>';\n $displaycount++;\n }\n }\n if ($displaycount == $postsperpage) {break;}\n }\n if ($theseposts != '') {\n echo '<h3>'.$posttagnames[$categorytag].'</h3><br>';\n echo '<ul>'.$theseposts.'</ul><br>';\n }\n if ($displaycount == $postsperpage) {break;}\n}\nif ($displaycount == 0) {echo 'No posts were found.';}\n\n}\n</code></pre>\n\n<p>Note I have wrapped in <code>is_category</code> if this is for use not on the category template (eg. <code>archive.php</code>)</p>\n\n<p>May need to create the pagination links manually for this but it does work. :-)</p>\n"
}
] |
2016/06/04
|
[
"https://wordpress.stackexchange.com/questions/228752",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/95222/"
] |
I would like to sort posts by tags in category and archive pages. (Unfortunately there isn’t an `orderby` parameter for tags. That would make things so easy!)
So a category page would be like this:
>
> Category name
> =============
>
>
> * Post 1 (Tag 1)
> * Post 2 (Tag 1)
> * Post 3 (Tag 1)
> * Post 4 (Tag 2)
> * Post 5 (Tag 2)
> * Post 6 (Tag 2)
> * Post 7 (Tag 3)
> * Post 8 (Tag 3)
> * Post 9 (Tag 3)
> ...
>
>
>
Or, even better:
>
> Category name
> =============
>
>
> ### Tag 1
>
>
> * Post 1
> * Post 2
> * Post 3
>
>
> ### Tag 2
>
>
> * Post 4
> * Post 5
> * Post 6
>
>
> ### Tag 3
>
>
> * Post 7
> * Post 8
> * Post 9
> ...
>
>
>
The tags would appear in alphabetical order. The posts below the tags would also appear in alphabetical order.
When a post has more than one tag, it needs to appear multiple times (one for each tag).
Is there any way to do that?
I thought about doing something [like this](https://wordpress.stackexchange.com/a/55386), but I couldn’t come up with a solution that would show only the posts and tags in the category. (The linked code shows all posts and tags.)
Or maybe there is a way to treat tags as a `meta_value`? Then I could simply use `pre_get_posts` like this:
```
add_action( 'pre_get_posts', 'archive_post_order');
function archive_post_order($query){
if(is_archive()):
$query->set( 'orderby', 'meta_value' );
$query->set( 'metakey', 'tag' );
$query->set( 'order', 'ASC' );
endif;
}
```
Any ideas are welcome. Thanks in advance.
|
There really is no sane way to accomplish this, specially if you have posts that are assigned to more than one tag (*which is almost always the case*). What is very sure, you have you work cut out for you.
Here are some thought and ideas you can persue:
POSTS WITH MULTIPLE TERMS
-------------------------
If posts have more than one tag (*or any term for that matter*) assigned to them, it means that there are more than one relationship to another post or set of posts, and grouping those together will either: (a). Be impossible ***without*** duplication, or (b). Be possible, ***with*** duplication of posts.
The terms (*tags in this case*) assigned to a post from a specific taxonomy (*`post_tag` in this case*) is ordered in a specific way when more than one term exists. Simply grabbing the first term might not always be the term you would want to use.
Sorting tags from `get_the_tags()` (*or the more generic `get_the_terms()`*) would require additional PHP sorting to sort the returned array of tag object to suite your needs, or you would want to use a function like `wp_get_post_tags()` to do the sorting via SQL, but it would require an extra db call.
If you want to sort by the first tag only, then it is quite easy if you sorted the tag array to suite or needs. I'll post example code later
**WORKAROUND**
If you have posts with multiple tags, you will need to find a specific unique relationship between posts, and according to that, either:
* assign a custom field with a sortable value to a set of posts and then use `pre_get_posts` to sort your category pages according to custom field value
* create a specific taxonomy for this, and then assign a special term to a set of posts and then use the `the_posts` filter, which I will post, to sort the returned array of posts
If you do not mind post duplication, you have a look at [this post](https://wordpress.stackexchange.com/a/226250/31545), this was however done for custom fields, so you would need to break it down and modify it to work with tags, but in essence, the principle by building a multidimentional array, flatten it later and then return a sorted array with duplicate posts remains the same
POSTS WITH SINGLE TAGS
----------------------
If you have posts assigned to one tag only (*or you are happy to sort by first tag only*), it is quite easy to sort the posts accordingly by using the `the_posts` filter. You can try the following then (***UNTESTED and very basic***)
```
add_filter( 'the_posts', function ( $posts, \WP_Query $q )
{
// Make sure we only target the main query on category pages
if ( !is_admin()
&& $q->is_main_query()
&& $q->is_category()
) {
// Use usort to sort the posts
usort( $posts, function( $a, $b )
{
return strcasecmp(
get_the_tags( $a->ID )[0]->name,
get_the_tags( $b->ID )[0]->name
);
});
}
}, 10, 2 );
```
|
228,754 |
<p>I have <code>taxonomy.php</code> template file for post_type "posts" but I'd like to use another taxonomy.php but just use/apply it to a custom post type. Is this somehow possible to make another taxonomy.php file just for a specific custom post type?</p>
|
[
{
"answer_id": 228887,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>There really is no sane way to accomplish this, specially if you have posts that are assigned to more than one tag (<em>which is almost always the case</em>). What is very sure, you have you work cut out for you.</p>\n\n<p>Here are some thought and ideas you can persue:</p>\n\n<h2>POSTS WITH MULTIPLE TERMS</h2>\n\n<p>If posts have more than one tag (<em>or any term for that matter</em>) assigned to them, it means that there are more than one relationship to another post or set of posts, and grouping those together will either: (a). Be impossible <strong><em>without</em></strong> duplication, or (b). Be possible, <strong><em>with</em></strong> duplication of posts.</p>\n\n<p>The terms (<em>tags in this case</em>) assigned to a post from a specific taxonomy (<em><code>post_tag</code> in this case</em>) is ordered in a specific way when more than one term exists. Simply grabbing the first term might not always be the term you would want to use. </p>\n\n<p>Sorting tags from <code>get_the_tags()</code> (<em>or the more generic <code>get_the_terms()</code></em>) would require additional PHP sorting to sort the returned array of tag object to suite your needs, or you would want to use a function like <code>wp_get_post_tags()</code> to do the sorting via SQL, but it would require an extra db call. </p>\n\n<p>If you want to sort by the first tag only, then it is quite easy if you sorted the tag array to suite or needs. I'll post example code later</p>\n\n<p><strong>WORKAROUND</strong></p>\n\n<p>If you have posts with multiple tags, you will need to find a specific unique relationship between posts, and according to that, either:</p>\n\n<ul>\n<li><p>assign a custom field with a sortable value to a set of posts and then use <code>pre_get_posts</code> to sort your category pages according to custom field value</p></li>\n<li><p>create a specific taxonomy for this, and then assign a special term to a set of posts and then use the <code>the_posts</code> filter, which I will post, to sort the returned array of posts</p></li>\n</ul>\n\n<p>If you do not mind post duplication, you have a look at <a href=\"https://wordpress.stackexchange.com/a/226250/31545\">this post</a>, this was however done for custom fields, so you would need to break it down and modify it to work with tags, but in essence, the principle by building a multidimentional array, flatten it later and then return a sorted array with duplicate posts remains the same</p>\n\n<h2>POSTS WITH SINGLE TAGS</h2>\n\n<p>If you have posts assigned to one tag only (<em>or you are happy to sort by first tag only</em>), it is quite easy to sort the posts accordingly by using the <code>the_posts</code> filter. You can try the following then (<strong><em>UNTESTED and very basic</em></strong>)</p>\n\n<pre><code>add_filter( 'the_posts', function ( $posts, \\WP_Query $q )\n{\n // Make sure we only target the main query on category pages\n if ( !is_admin()\n && $q->is_main_query()\n && $q->is_category()\n ) {\n // Use usort to sort the posts\n usort( $posts, function( $a, $b )\n {\n return strcasecmp( \n get_the_tags( $a->ID )[0]->name, \n get_the_tags( $b->ID )[0]->name \n );\n });\n }\n}, 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 228928,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": -1,
"selected": false,
"text": "<p>If you have a lot of tags this is going to be pretty inefficient, but still, it should get the job done...</p>\n\n<p>This first part is a little pointless but it will pare down to posts in the category that actually have tags.</p>\n\n<pre><code>add_action('pre_get_posts', 'get_category_tag_posts');\nfunction get_category_tag_posts($q) {\n if ( !is_admin() && $q->is_main_query() && $q->is_category() ) {\n global $categorytags;\n $terms = get_terms('post_tag');\n foreach ($terms as $term) {$categorytags[] = $term->term_id;}\n $q->set('tag__in',$categorytags);\n // inefficient but we cannot know how many posts are needed\n $q->set('posts_per_page',-1); // also makes offset ignored\n }\n}\n</code></pre>\n\n<p>Really just using this part to index some tags etc., in the hope of creating slightly better efficiency by not doubling up later...</p>\n\n<pre><code>add_filter('the_posts', 'get_category_post_tags', 10, 2);\nfunction get_category_post_tags($posts, $q) {\n if ( !is_admin() && $q->is_main_query() && $q->is_category() ) {\n global $categoryposttags, $categoryposts, $posttagnames;\n $categoryposts = $posts;\n if (count($posts) > 0) {\n foreach ($posts as $post) {\n $tagarray = array();\n $tags = get_the_tags($post->ID);\n if ($tags) {\n foreach ($tags as $tag) {\n if (!in_array($tag->term_id,$tagarray)) {$tagarray[] = $tag->term_id;}\n $posttagnames[$tag->term_id] = $tag->name;\n }\n $categoryposttags[$post->ID] = $tagarray;\n }\n }\n }\n }\n</code></pre>\n\n<p>And for the category template:</p>\n\n<pre><code>if (is_category()) {\n\nglobal $categoryposts, $categorytags, $categoryposttags, $posttagnames;\n$postsperpage = get_option('posts_per_page'); $postoffset = 0;\nif (isset($_GET['posts_per_page'])) {$postsperpage = absint($_GET['posts_per_page']);}\nif (isset($_GET['page'])) {$postoffset = (absint($_GET['page'])-1) * $postsperpage;}\n\n$postcount = 0; $displaycount = 0;\nforeach ($categorytags as $categorytag) {\n $theseposts = '';\n foreach ($categoryposts as $post) {\n if (in_array($categorytag,$categoryposttags[$post->ID])) {\n $postcount++;\n if ($postcount > $postoffset) {\n $theseposts .= '<li><h4><a href=\"'.get_permalink($post->ID).'\">'.$post->post_title.'</a></h4><br>';\n if (empty($post->post_excerpt)) {$theseposts .= wp_kses_post(wp_trim_words($post->post_content,50));}\n else {$theseposts .= $post->post_excerpt;}\n $theseposts .= '<br></li>';\n $displaycount++;\n }\n }\n if ($displaycount == $postsperpage) {break;}\n }\n if ($theseposts != '') {\n echo '<h3>'.$posttagnames[$categorytag].'</h3><br>';\n echo '<ul>'.$theseposts.'</ul><br>';\n }\n if ($displaycount == $postsperpage) {break;}\n}\nif ($displaycount == 0) {echo 'No posts were found.';}\n\n}\n</code></pre>\n\n<p>Note I have wrapped in <code>is_category</code> if this is for use not on the category template (eg. <code>archive.php</code>)</p>\n\n<p>May need to create the pagination links manually for this but it does work. :-)</p>\n"
}
] |
2016/06/04
|
[
"https://wordpress.stackexchange.com/questions/228754",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
] |
I have `taxonomy.php` template file for post\_type "posts" but I'd like to use another taxonomy.php but just use/apply it to a custom post type. Is this somehow possible to make another taxonomy.php file just for a specific custom post type?
|
There really is no sane way to accomplish this, specially if you have posts that are assigned to more than one tag (*which is almost always the case*). What is very sure, you have you work cut out for you.
Here are some thought and ideas you can persue:
POSTS WITH MULTIPLE TERMS
-------------------------
If posts have more than one tag (*or any term for that matter*) assigned to them, it means that there are more than one relationship to another post or set of posts, and grouping those together will either: (a). Be impossible ***without*** duplication, or (b). Be possible, ***with*** duplication of posts.
The terms (*tags in this case*) assigned to a post from a specific taxonomy (*`post_tag` in this case*) is ordered in a specific way when more than one term exists. Simply grabbing the first term might not always be the term you would want to use.
Sorting tags from `get_the_tags()` (*or the more generic `get_the_terms()`*) would require additional PHP sorting to sort the returned array of tag object to suite your needs, or you would want to use a function like `wp_get_post_tags()` to do the sorting via SQL, but it would require an extra db call.
If you want to sort by the first tag only, then it is quite easy if you sorted the tag array to suite or needs. I'll post example code later
**WORKAROUND**
If you have posts with multiple tags, you will need to find a specific unique relationship between posts, and according to that, either:
* assign a custom field with a sortable value to a set of posts and then use `pre_get_posts` to sort your category pages according to custom field value
* create a specific taxonomy for this, and then assign a special term to a set of posts and then use the `the_posts` filter, which I will post, to sort the returned array of posts
If you do not mind post duplication, you have a look at [this post](https://wordpress.stackexchange.com/a/226250/31545), this was however done for custom fields, so you would need to break it down and modify it to work with tags, but in essence, the principle by building a multidimentional array, flatten it later and then return a sorted array with duplicate posts remains the same
POSTS WITH SINGLE TAGS
----------------------
If you have posts assigned to one tag only (*or you are happy to sort by first tag only*), it is quite easy to sort the posts accordingly by using the `the_posts` filter. You can try the following then (***UNTESTED and very basic***)
```
add_filter( 'the_posts', function ( $posts, \WP_Query $q )
{
// Make sure we only target the main query on category pages
if ( !is_admin()
&& $q->is_main_query()
&& $q->is_category()
) {
// Use usort to sort the posts
usort( $posts, function( $a, $b )
{
return strcasecmp(
get_the_tags( $a->ID )[0]->name,
get_the_tags( $b->ID )[0]->name
);
});
}
}, 10, 2 );
```
|
228,778 |
<p>I was wondering if there is any way to combine a custom field (in custom post type) with an embed shortcode? Long story short - a user type into a field called videox and an url for a video (youtube, vimeo) or audio (e.g. soundcloud). When I render this field, of course it displays as it was in the field. How do I convert such input into an embeded audio / video? </p>
<p>I've tried to echo that input between embed (as <code>do_shortcode('[embed]' . $adresgoeshere . '[/embed]');</code>) yet without success.</p>
|
[
{
"answer_id": 228781,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 3,
"selected": true,
"text": "<p>As you are using URLs from oEmbed provides (YouTube, Vimeo, Soundcloud, etc), I would use <a href=\"https://developer.wordpress.org/reference/functions/wp_oembed_get/\" rel=\"nofollow\"><code>wp_oembed_get()</code></a> function. This function uses oEmbed and tries to get the embed HTML of the provided URL.</p>\n\n<pre><code>$embed = wp_oembed_get( $some_url );\nif( $embed ) {\n echo $embed;\n} else {\n // The embed HTML couldn't be fetched\n}\n</code></pre>\n"
},
{
"answer_id": 228818,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 0,
"selected": false,
"text": "<p>Adding another way here. You can leave this to WordPress and just pass the URL from <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content\" rel=\"nofollow\"><code>the_content</code></a> filter.</p>\n\n<p>Example:-</p>\n\n<pre><code>$adresgoeshere = 'URL of oembed providers'\necho apply_filters('the_content', $adresgoeshere); \n</code></pre>\n"
},
{
"answer_id": 228997,
"author": "Jebble",
"author_id": 81939,
"author_profile": "https://wordpress.stackexchange.com/users/81939",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of do_shortcode you can use the run_shortcode function of $wp_embed</p>\n\n<pre><code>global $wp_embed;\n$embed = $wp_embed->run_shortcode( '[embed]' . $url . '[/embed]' );\n\necho $embed;\n</code></pre>\n"
}
] |
2016/06/04
|
[
"https://wordpress.stackexchange.com/questions/228778",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/95240/"
] |
I was wondering if there is any way to combine a custom field (in custom post type) with an embed shortcode? Long story short - a user type into a field called videox and an url for a video (youtube, vimeo) or audio (e.g. soundcloud). When I render this field, of course it displays as it was in the field. How do I convert such input into an embeded audio / video?
I've tried to echo that input between embed (as `do_shortcode('[embed]' . $adresgoeshere . '[/embed]');`) yet without success.
|
As you are using URLs from oEmbed provides (YouTube, Vimeo, Soundcloud, etc), I would use [`wp_oembed_get()`](https://developer.wordpress.org/reference/functions/wp_oembed_get/) function. This function uses oEmbed and tries to get the embed HTML of the provided URL.
```
$embed = wp_oembed_get( $some_url );
if( $embed ) {
echo $embed;
} else {
// The embed HTML couldn't be fetched
}
```
|
228,797 |
<p>So I am using the code below to retrieve the latest 5 posts from 5 different categories. </p>
<p>The problem is that it outputs the latest 5 posts from only the first category in the array, even if there are newer posts in the other 4 categories.</p>
<p>If I remove the first category from the array, then it simply outputs the latest 5 posts from the next category in the array. It never gets to the remaining categories.</p>
<p>What I wanted to do was to output the newest 5 posts from <em>all</em> the 5 categories <em>combined</em>. What can I do to fix that?</p>
<pre><code><?php
$args = array( 'posts_per_page' => 5, 'category' => 15,16,17,18,19);
$myposts = get_posts( $args ); ?>
<?php foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<?php the_title(); ?>
<?php the_content(); ?>
<?php endforeach; wp_reset_postdata();?>
</code></pre>
|
[
{
"answer_id": 228802,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 1,
"selected": false,
"text": "<p>You have a problem in the array construction.\nYou have that :</p>\n\n<pre><code>$args = array(\n 'posts_per_page' => 5,\n 'category' => 15, 16, 17, 18, 19\n);\n</code></pre>\n\n<p>And you probably need that : </p>\n\n<pre><code>$args = array(\n 'posts_per_page' => 5,\n 'category' => [15, 16, 17, 18, 19]\n);\n</code></pre>\n"
},
{
"answer_id": 228803,
"author": "Gareth Gillman",
"author_id": 33936,
"author_profile": "https://wordpress.stackexchange.com/users/33936",
"pm_score": 3,
"selected": true,
"text": "<p>2 choices here, you either need to set the category as an array e.g.</p>\n\n<pre><code>$args = array( \n 'posts_per_page' => 5,\n 'category' => array(15,16,17,18,19)\n);\n</code></pre>\n\n<p>You can't just add the numbers in a list but I can't find any documentation that the category element allows multiples (as the name is category)</p>\n\n<p>The other option is to use wp_query and category__in</p>\n\n<pre><code>$query = new WP_Query(\n array(\n 'category__in' => array(15,16,17,18,19),\n 'posts_per_page' => 5,\n 'post_type' => 'post',\n )\n );\nif ( $query->have_posts() ) {\n while ( $query->have_posts() ) {\n $query->the_post();\n // do something\n }\n}\nwp_reset_postdata();\n</code></pre>\n\n<p>These will get the 5 last posts from any of those categories, if you want to get a post from each of them then the query needs to be a lot different</p>\n"
}
] |
2016/06/04
|
[
"https://wordpress.stackexchange.com/questions/228797",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90205/"
] |
So I am using the code below to retrieve the latest 5 posts from 5 different categories.
The problem is that it outputs the latest 5 posts from only the first category in the array, even if there are newer posts in the other 4 categories.
If I remove the first category from the array, then it simply outputs the latest 5 posts from the next category in the array. It never gets to the remaining categories.
What I wanted to do was to output the newest 5 posts from *all* the 5 categories *combined*. What can I do to fix that?
```
<?php
$args = array( 'posts_per_page' => 5, 'category' => 15,16,17,18,19);
$myposts = get_posts( $args ); ?>
<?php foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<?php the_title(); ?>
<?php the_content(); ?>
<?php endforeach; wp_reset_postdata();?>
```
|
2 choices here, you either need to set the category as an array e.g.
```
$args = array(
'posts_per_page' => 5,
'category' => array(15,16,17,18,19)
);
```
You can't just add the numbers in a list but I can't find any documentation that the category element allows multiples (as the name is category)
The other option is to use wp\_query and category\_\_in
```
$query = new WP_Query(
array(
'category__in' => array(15,16,17,18,19),
'posts_per_page' => 5,
'post_type' => 'post',
)
);
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// do something
}
}
wp_reset_postdata();
```
These will get the 5 last posts from any of those categories, if you want to get a post from each of them then the query needs to be a lot different
|
228,821 |
<p>There is a new feature in wordpress introducing primary category.
When you select a category, primary category can be specified.</p>
<p>My question is how can I get that primary category name using Wordpress Core functions?</p>
<p>if there is no function, can you help me to get the first child of main category?</p>
<p>for example:<br />
- main category<br />
-- child cat 1<br />
-- child cat 2<br />
-- child cat 3<br /></p>
<p>I need to get -- child cat 1.</p>
<p>Thanks for you help.</p>
|
[
{
"answer_id": 228846,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>To answer your second question: <a href=\"https://developer.wordpress.org/reference/functions/get_categories/\" rel=\"nofollow\"><code>get_categories()</code></a> allows you to pass a whole bunch of arguments, one of which happens to be child categories.</p>\n\n<p>First get the parent category. I've used <code>get_category_by_slug</code> here, but you could use any other way to get it, for instance Yoasts function to retrieve the primary category.</p>\n\n<pre><code>$category = get_category_by_slug( 'category-name' );\n</code></pre>\n\n<p>Then get all child categories:</p>\n\n<pre><code>$args = array(\n'type' => 'post',\n'child_of' => $category->term_id,\n'orderby' => 'name',\n'order' => 'ASC', // or any order you like\n'hide_empty' => FALSE,\n'hierarchical' => 1,\n'taxonomy' => 'category',\n); \n$child_categories = get_categories($args );\n</code></pre>\n\n<p>Finally select the first element if there is any:</p>\n\n<pre><code>if !empty($child_categories) $first_child = $child_categories[0];\n</code></pre>\n"
},
{
"answer_id": 262015,
"author": "Serge Andreev",
"author_id": 116650,
"author_profile": "https://wordpress.stackexchange.com/users/116650",
"pm_score": -1,
"selected": false,
"text": "<p>I use sCategory Permalink plugin\n<a href=\"https://wordpress.org/plugins/scategory-permalink/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/scategory-permalink/</a></p>\n\n<pre><code>$category_primary_id = get_post_meta(get_the_ID(), '_category_permalink', true);\nif (!empty($category_primary_id)) {\n $category = get_category($category_primary_id);\n var_dump($category->name);\n}\n</code></pre>\n"
},
{
"answer_id": 304061,
"author": "MMTDesigner",
"author_id": 76334,
"author_profile": "https://wordpress.stackexchange.com/users/76334",
"pm_score": 3,
"selected": true,
"text": "<p>I see that this question is getting a lot of attentions since the past year, I thought to answer this question in the right way.</p>\n<p>There is not primary category in wordpress if you have installed <strong>Yoast SEO</strong> plugin then a new feature will be appear on <strong>Single Posts</strong> category selection in admin area in order to choose primary category .</p>\n<p>To get that primary category you can use the following function I came up with:</p>\n<pre><code>if ( ! function_exists( 'get_primary_taxonomy_id' ) ) {\nfunction get_primary_taxonomy_id( $post_id, $taxonomy ) {\n $prm_term = '';\n if (class_exists('WPSEO_Primary_Term')) {\n $wpseo_primary_term = new WPSEO_Primary_Term( $taxonomy, $post_id );\n $prm_term = $wpseo_primary_term->get_primary_term();\n }\n if ( !is_object($wpseo_primary_term) && empty( $prm_term ) ) {\n $term = wp_get_post_terms( $post_id, $taxonomy );\n if (isset( $term ) && !empty( $term ) ) {\n return wp_get_post_terms( $post_id, $taxonomy )[0]->term_id;\n }\n return '';\n\n }\n return $wpseo_primary_term->get_primary_term();\n}\n}\n</code></pre>\n<p>First it will check to see if Yoast SEO is being installed and activated then it will try to get primary category. if Yost is not installed then it will get all of the categories and returns the first one.</p>\n<p>Notice how this function also works for custom post types with custom taxonomies.</p>\n<p>At the end this function returns the category (term) ID if you want to get the category (term) object you can use <code>get_term($ID, $taxonomy)</code> and pass in the ID.</p>\n<p>New Edit:</p>\n<p>If you are using Rank Math and you want to get primary taxonomy set using this plugin then the following piece of code might help:</p>\n<pre><code> if (class_exists('RankMath')) {\n $primary_tax = get_post_meta( $post_id, 'rank_math_primary_category', true );\n if (!empty($primary_tax)) {\n return get_term( $primary_tax, $taxonomy );\n }\n }\n</code></pre>\n<p>I suggest to add this after Yoast <code>if</code> statement.</p>\n"
},
{
"answer_id": 311306,
"author": "Arash Rabiee",
"author_id": 129717,
"author_profile": "https://wordpress.stackexchange.com/users/129717",
"pm_score": 2,
"selected": false,
"text": "<p>this is not for wordpress but for seo plugin, you could use following function</p>\n\n<pre><code>function get_post_primary_category($post_id, $term='category', \n $return_all_categories=false){\n $return = array();\n\nif (class_exists('WPSEO_Primary_Term')){\n // Show Primary category by Yoast if it is enabled & set\n $wpseo_primary_term = new WPSEO_Primary_Term( $term, $post_id );\n $primary_term = get_term($wpseo_primary_term->get_primary_term());\n\n if (!is_wp_error($primary_term)){\n $return['primary_category'] = $primary_term;\n }\n}\n\nif (empty($return['primary_category']) || $return_all_categories){\n $categories_list = get_the_terms($post_id, $term);\n\n if (empty($return['primary_category']) && !empty($categories_list)){\n $return['primary_category'] = $categories_list[0]; //get the first \n\n }\n if ($return_all_categories){\n $return['all_categories'] = array();\n\n if (!empty($categories_list)){\n foreach($categories_list as &$category){\n $return['all_categories'][] = $category->term_id;\n }\n }\n }\n}\n\nreturn $return;\n}\n</code></pre>\n\n<p>this function is written by <a href=\"https://www.lab21.gr/blog/wordpress-get-primary-category-post\" rel=\"nofollow noreferrer\">lab21.gr</a></p>\n"
},
{
"answer_id": 315577,
"author": "Eqhes",
"author_id": 138418,
"author_profile": "https://wordpress.stackexchange.com/users/138418",
"pm_score": 3,
"selected": false,
"text": "<p>I have editted the <a href=\"https://wordpress.stackexchange.com/a/304061/138418\">MMT Designer function</a>. This works better for me:</p>\n\n<pre><code>if ( ! function_exists( 'get_primary_taxonomy_id' ) ) {\n function get_primary_taxonomy_id( $post_id, $taxonomy ) {\n $prm_term = '';\n if (class_exists('WPSEO_Primary_Term')) {\n $wpseo_primary_term = new WPSEO_Primary_Term( $taxonomy, $post_id );\n $prm_term = $wpseo_primary_term->get_primary_term();\n }\n if ( !is_object($wpseo_primary_term) || empty( $prm_term ) ) {\n $term = wp_get_post_terms( $post_id, $taxonomy );\n if (isset( $term ) && !empty( $term ) ) {\n return $term[0]->term_id;\n } else {\n return '';\n }\n }\n return $wpseo_primary_term->get_primary_term();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 348552,
"author": "Fellipe Sanches",
"author_id": 171011,
"author_profile": "https://wordpress.stackexchange.com/users/171011",
"pm_score": 2,
"selected": false,
"text": "<p>A native Wordpress solution to return the current parent category.</p>\n\n<pre><code>function primary_categories($arr_excluded_cats) {\n\nif($arr_excluded_cats == null) {\n $arr_excluded_cats = array();\n}\n\n$post_cats = get_the_category();\n\n$args = array(\n 'orderby' => 'name',\n 'order' => 'ASC',\n 'parent' => 0\n);\n\n $primary_categories = get_categories($args);\n\n foreach ($primary_categories as $primary_category) {\n\n foreach ($post_cats as $post_cat) {\n if(($primary_category->slug == $post_cat->slug) && (!in_array($primary_category->slug, $arr_excluded_cats))) {\n return $primary_category->slug;\n }\n }\n }\n}\n\n//if you have more than two parent categories associated with the post, you can delete the ones you don't want here\n$dont_return_these = array(\n 'receitas','enciclopedico'\n );\n\n//use the function like this:\necho primary_categories($dont_return_these);\n</code></pre>\n\n<p>Comments:</p>\n\n<ul>\n<li>if you only have one parent category by post, pass null instead of array</li>\n<li>if you want another output instead of slug change this to return $primary_category-> slug;</li>\n</ul>\n"
},
{
"answer_id": 402560,
"author": "msmosavar",
"author_id": 219088,
"author_profile": "https://wordpress.stackexchange.com/users/219088",
"pm_score": 1,
"selected": false,
"text": "<p>I've just refactored <a href=\"https://wordpress.stackexchange.com/users/138418/eqhes\">Eqhes</a> answer. A little cleaner code :)</p>\n<pre><code>if (!function_exists('get_primary_taxonomy_id')) {\n function get_primary_taxonomy_id($post_id, $taxonomy) {\n $prm_term = '';\n $wpseo_primary_term = '';\n\n if (class_exists('WPSEO_Primary_Term')) {\n $wpseo_primary_term = new WPSEO_Primary_Term($taxonomy, $post_id);\n $prm_term = $wpseo_primary_term->get_primary_term();\n }\n\n if (is_object($wpseo_primary_term) && !empty($prm_term)) {\n return $wpseo_primary_term->get_primary_term();\n }\n\n $term = wp_get_post_terms($post_id, $taxonomy);\n\n if (isset($term) && !empty($term)) {\n return $term[0]->term_id;\n }\n\n return '';\n }\n}\n</code></pre>\n"
}
] |
2016/06/05
|
[
"https://wordpress.stackexchange.com/questions/228821",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76334/"
] |
There is a new feature in wordpress introducing primary category.
When you select a category, primary category can be specified.
My question is how can I get that primary category name using Wordpress Core functions?
if there is no function, can you help me to get the first child of main category?
for example:
- main category
-- child cat 1
-- child cat 2
-- child cat 3
I need to get -- child cat 1.
Thanks for you help.
|
I see that this question is getting a lot of attentions since the past year, I thought to answer this question in the right way.
There is not primary category in wordpress if you have installed **Yoast SEO** plugin then a new feature will be appear on **Single Posts** category selection in admin area in order to choose primary category .
To get that primary category you can use the following function I came up with:
```
if ( ! function_exists( 'get_primary_taxonomy_id' ) ) {
function get_primary_taxonomy_id( $post_id, $taxonomy ) {
$prm_term = '';
if (class_exists('WPSEO_Primary_Term')) {
$wpseo_primary_term = new WPSEO_Primary_Term( $taxonomy, $post_id );
$prm_term = $wpseo_primary_term->get_primary_term();
}
if ( !is_object($wpseo_primary_term) && empty( $prm_term ) ) {
$term = wp_get_post_terms( $post_id, $taxonomy );
if (isset( $term ) && !empty( $term ) ) {
return wp_get_post_terms( $post_id, $taxonomy )[0]->term_id;
}
return '';
}
return $wpseo_primary_term->get_primary_term();
}
}
```
First it will check to see if Yoast SEO is being installed and activated then it will try to get primary category. if Yost is not installed then it will get all of the categories and returns the first one.
Notice how this function also works for custom post types with custom taxonomies.
At the end this function returns the category (term) ID if you want to get the category (term) object you can use `get_term($ID, $taxonomy)` and pass in the ID.
New Edit:
If you are using Rank Math and you want to get primary taxonomy set using this plugin then the following piece of code might help:
```
if (class_exists('RankMath')) {
$primary_tax = get_post_meta( $post_id, 'rank_math_primary_category', true );
if (!empty($primary_tax)) {
return get_term( $primary_tax, $taxonomy );
}
}
```
I suggest to add this after Yoast `if` statement.
|
228,833 |
<p>Is default functions like <code>update_post_meta()</code> safe to use user inputs?</p>
<p>e.g.</p>
<pre><code>update_post_meta(76, 'my_key', $_GET['value'])
</code></pre>
<p>Or should I use </p>
<pre><code>$_GET['value'] = sanitize_text_field($_GET['value']);
</code></pre>
<p>before using</p>
<pre><code>update_post_meta(76, 'my_key', $_GET['value'])
</code></pre>
|
[
{
"answer_id": 228835,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>Never leave anything to chance, always sanitize, escape and validate <strong>all</strong> data coming from forms and super globals like <code>$_GET</code> and <code>$_POST</code> according to your requirements and the data type you are expecting. </p>\n\n<p>It is always good to set your code up in a way so that should your validation fail, you do not unnecessarily run scripts and functions. Have some kind of fail safe which will properly handle failure</p>\n"
},
{
"answer_id": 228837,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>After upvoting @pieter's answer....</p>\n\n<p>In recent time I came to the realization that it is much better to handle \"bad\" data gracefully when it is used (usually it means escaping, but also validation) than at input time. Data corruption can happen not only because of some rouge process \"shitting\" over your data, but also when the enviroment has changed and the data is not as relevant any longer ( a plugin was disabled).</p>\n\n<p>Validation is worth doing if you are going to give some alert to the user, otherwise it might actually be a kind of intermediate state that is hard to protect against and give useful feedback (customizer live changes).</p>\n\n<p>For sanitation, I just use the wordpress APIs for DB access and let them handle that side, but otherwise I feel it is usually waste of time to do anything more then that.</p>\n\n<p>This all depends on context. In your case the question you should ask is whether you even want to sanitize the value, because sanitization means that the value a user request will not be displayed in the same way he wanted it to.</p>\n"
}
] |
2016/06/05
|
[
"https://wordpress.stackexchange.com/questions/228833",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96263/"
] |
Is default functions like `update_post_meta()` safe to use user inputs?
e.g.
```
update_post_meta(76, 'my_key', $_GET['value'])
```
Or should I use
```
$_GET['value'] = sanitize_text_field($_GET['value']);
```
before using
```
update_post_meta(76, 'my_key', $_GET['value'])
```
|
Never leave anything to chance, always sanitize, escape and validate **all** data coming from forms and super globals like `$_GET` and `$_POST` according to your requirements and the data type you are expecting.
It is always good to set your code up in a way so that should your validation fail, you do not unnecessarily run scripts and functions. Have some kind of fail safe which will properly handle failure
|
228,834 |
<p>Is there an <code>add_filter</code> where you can see/modify all the <code>$_POST</code> data submitted for a new user registration before the user is created?</p>
<p>Thanks</p>
|
[
{
"answer_id": 228840,
"author": "thebigtine",
"author_id": 76059,
"author_profile": "https://wordpress.stackexchange.com/users/76059",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/register_post\" rel=\"nofollow\"><code>register_post</code></a> hook. \nHere is the list of hooks and filters that fire during user reg (in order that they are fired):</p>\n\n<ol>\n<li><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/register_post\" rel=\"nofollow\"><code>register_post</code></a> - used to handle post data from a user registration before the <code>registration_errors</code> filter is called or errors are returned</li>\n<li><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/registration_errors\" rel=\"nofollow\"><code>registration_errors</code></a> - filters the errors encountered when a new user is being registered. </li>\n<li><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/user_register\" rel=\"nofollow\"><code>user_register</code></a> - allows you to access data for a new user immediately after they are added to the database</li>\n</ol>\n"
},
{
"answer_id": 228849,
"author": "jsherk",
"author_id": 95088,
"author_profile": "https://wordpress.stackexchange.com/users/95088",
"pm_score": 3,
"selected": true,
"text": "<p>Well once I looked into it, it is quite simple. <code>$_POST</code> is global variable and contains all the POSTed data that was sent from the form.</p>\n\n<p>For example, to email yourself all the posted data submitted in the form, you you could use something like this:</p>\n\n<pre><code> function email_me_post_data() {\n global $_POST;\n $msg = print_r($_POST, true);\n mail('[email protected]', 'Example POST data', $msg);\n }\n add_action( 'user_register', 'email_me_post_data' );\n</code></pre>\n\n<p>Note that user_register action occurs AFTER the new user is created. Not sure you can get to the post data before user is created, although you could still modify data and re-save the changes.</p>\n"
}
] |
2016/06/05
|
[
"https://wordpress.stackexchange.com/questions/228834",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/95088/"
] |
Is there an `add_filter` where you can see/modify all the `$_POST` data submitted for a new user registration before the user is created?
Thanks
|
Well once I looked into it, it is quite simple. `$_POST` is global variable and contains all the POSTed data that was sent from the form.
For example, to email yourself all the posted data submitted in the form, you you could use something like this:
```
function email_me_post_data() {
global $_POST;
$msg = print_r($_POST, true);
mail('[email protected]', 'Example POST data', $msg);
}
add_action( 'user_register', 'email_me_post_data' );
```
Note that user\_register action occurs AFTER the new user is created. Not sure you can get to the post data before user is created, although you could still modify data and re-save the changes.
|
228,870 |
<p>By default, Wordpress uses Gravatar for user avatars.</p>
<p>I've created a custom field for avatar uploads, and I'm using this as users' avatars on various pages in the theme.</p>
<p>In the admin - on the all users page - there is a column that would normally display the user's avatar (see below). Is there a way to use my custom field <em>instead</em> of the default gravatar field?</p>
<p><a href="https://i.stack.imgur.com/liK7I.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/liK7I.jpg" alt="enter image description here"></a></p>
|
[
{
"answer_id": 228872,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 1,
"selected": false,
"text": "<p><strong>EDIT:</strong> My original solution is below, but <a href=\"https://wordpress.stackexchange.com/users/32475/sumit\">Sumit</a> alerted me in the comments to the existence of the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/get_avatar\" rel=\"nofollow noreferrer\">get_avatar filter</a>. I've posted <a href=\"https://wordpress.stackexchange.com/a/228906/46066\">an additional answer</a> that shows how to implement that option as well.</p>\n\n<hr>\n\n<p>Yes, you can do this.</p>\n\n<p>The columns displayed in any of these 'list tables' in Wordpress admin are filterable - so using a custom function in your theme's <code>functions.php</code>, you can remove columns or add your own.</p>\n\n<p>This function will allow you to both remove the default column and add a custom one:</p>\n\n<pre><code>add_filter(\"manage_users_columns\", \"wpse_228870_custom_user_avatar\");\n\nfunction wpse_228870_custom_user_avatar($columns){\n\n $columns = \n array_slice($columns, 0, 1) // leave the checkbox in place (the 0th column)\n + array(\"custom_avatar\" => \"\") // splice in a custom avatar column in the next space\n + array_slice($columns, 1) // include any other remaining columns (the 1st column onwards)\n ;\n\n return $columns;\n\n}\n</code></pre>\n\n<p>There's many ways you can do that but in this I've basically just taken the <code>$columns</code> array and massaged it to stick your custom avatar in at the second position. You can use any PHP array function to do whatever you want to these columns.</p>\n\n<p>Next, we need to tell Wordpress what to display in that <code>custom_avatar</code> column:</p>\n\n<pre><code>add_filter(\"manage_users_custom_column\", \"wpse_228870_custom_user_avatar_column\", 10, 3);\n\nfunction wpse_228870_custom_user_avatar_column($output, $column_name, $user_id){\n\n // bow out early if this isn't our custom column!\n if($column_name != \"custom_avatar\"){ return $output; }\n\n // get your custom field here, using $user_id to get the correct one\n // ........\n\n // enter your custom image output here\n $output = '<img src=\"image.png\" width=\"50\" height=\"50\" />';\n\n return $output;\n\n}\n</code></pre>\n\n<p>If the image doesn't come out at the right dimensions or isn't styled appropriately, you can <a href=\"https://wordpress.stackexchange.com/a/110899/46066\">add styles to Wordpress admin</a> if you want to have more control over how the columns and their contents are sized.</p>\n\n<p>You can also read more about the two filters I used in the Wordpress documentation - <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/manage_users_columns\" rel=\"nofollow noreferrer\">manage_users_columns</a> is on the Codex and <a href=\"https://developer.wordpress.org/reference/hooks/manage_users_custom_column/\" rel=\"nofollow noreferrer\">manage_users_custom_column</a> is on the newer code reference. Similar filters exist for any of the other tables, such as posts and pages.</p>\n"
},
{
"answer_id": 228906,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 3,
"selected": false,
"text": "<p>As an alternative to my other answer, you can also use the <code>get_avatar</code> filter. Props to <a href=\"https://wordpress.stackexchange.com/users/32475/sumit\">Sumit</a> to alerting me to this one.</p>\n\n<p>The benefit of using the <code>get_avatar</code> filter is your custom avatar should be applied <em>anywhere</em> Wordpress uses it, rather than just in this users list like my other answer deals with. If you use plugins that display user avatars, this solution should also work for them, providing they play nicely and use the Wordpress filters they should be using :)</p>\n\n<p>The <a href=\"https://developer.wordpress.org/reference/functions/get_avatar/\" rel=\"nofollow noreferrer\">official docs for the <code>get_avatar</code> filter are here</a>.</p>\n\n<p>In your theme's <code>functions.php</code>, you'll want set up your function like this:</p>\n\n<pre><code>add_filter(\"get_avatar\", \"wpse_228870_custom_user_avatar\", 1, 5);\n\nfunction wpse_228870_custom_user_avatar($avatar, $id_or_email, $size, $alt, $args){\n\n // determine which user we're asking about - this is the hard part!\n // ........\n\n // get your custom field here, using the user's object to get the correct one\n // ........\n\n // enter your custom image output here\n $avatar = '<img alt=\"' . $alt . '\" src=\"image.png\" width=\"' . $size . '\" height=\"' . $size . '\" />';\n\n return $avatar;\n\n}\n</code></pre>\n\n<p>Now there's a lot missing from that because, perhaps frustratingly, Wordpress doesn't send a nice clean user object or user ID through to this filter - according to the docs it can give us:</p>\n\n<blockquote>\n <p>a user_id, gravatar md5 hash, user email, WP_User object, WP_Post object, or WP_Comment object</p>\n</blockquote>\n\n<p>Most of these we can deal with - if we got a Gravatar hash that'd be a bit difficult - but the rest we can use the built in Wordpress functions to get the correct user object.</p>\n\n<p>There's <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/get_avatar#Example\" rel=\"nofollow noreferrer\">an example that gets started on this in the old Wordpress docs</a>. However for this filter to work properly everywhere it's used, you'll need to write a little extra to make sure you can detect and deal with a post or comment object coming through as well (perhaps using the <a href=\"http://php.net/is_a\" rel=\"nofollow noreferrer\">PHP is_a function</a>) and then getting the associated post or comment author.</p>\n"
},
{
"answer_id": 228913,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>We could also use one of the following filters, available since WordPress 4.2:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/pre_get_avatar_data/\" rel=\"nofollow\"><code>pre_get_avatar_data</code></a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/get_avatar_url/\" rel=\"nofollow\"><code>get_avatar_url</code></a> </li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/get_avatar_data/\" rel=\"nofollow\"><code>get_avatar_data</code></a></li>\n</ul>\n\n<p>Regarding how to get the user ID from the <code>$id_or_email</code> we can see how it's done in the <a href=\"https://github.com/WordPress/WordPress/blob/4.5-branch/wp-includes/link-template.php#L3838-3883\" rel=\"nofollow\">core</a>:</p>\n\n<pre><code>$email_hash = '';\n$user = $email = false;\nif ( is_object( $id_or_email ) && isset( $id_or_email->comment_ID ) ) {\n $id_or_email = get_comment( $id_or_email );\n}\n// Process the user identifier.\nif ( is_numeric( $id_or_email ) ) {\n $user = get_user_by( 'id', absint( $id_or_email ) );\n} elseif ( is_string( $id_or_email ) ) {\n if ( strpos( $id_or_email, '@md5.gravatar.com' ) ) {\n // md5 hash\n list( $email_hash ) = explode( '@', $id_or_email );\n } else {\n // email address\n $email = $id_or_email;\n }\n} elseif ( $id_or_email instanceof WP_User ) {\n // User Object\n $user = $id_or_email;\n} elseif ( $id_or_email instanceof WP_Post ) {\n // Post Object\n $user = get_user_by( 'id', (int) $id_or_email->post_author );\n} elseif ( $id_or_email instanceof WP_Comment ) {\n /**\n * Filter the list of allowed comment types for retrieving avatars.\n *\n * @since 3.0.0\n *\n * @param array $types An array of content types. Default only contains 'comment'.\n */\n $allowed_comment_types = apply_filters( 'get_avatar_comment_types', array( 'comment' ) );\n if ( ! empty( $id_or_email->comment_type ) && ! in_array( $id_or_email->comment_type, (array) $allowed_comment_types ) ) {\n $args['url'] = false;\n /** This filter is documented in wp-includes/link-template.php */\n return apply_filters( 'get_avatar_data', $args, $id_or_email );\n }\n if ( ! empty( $id_or_email->user_id ) ) {\n $user = get_user_by( 'id', (int) $id_or_email->user_id );\n }\n if ( ( ! $user || is_wp_error( $user ) ) && ! empty( $id_or_email->comment_author_email ) ) {\n $email = $id_or_email->comment_author_email;\n }\n}\n</code></pre>\n\n<p>It would be easier if the user ID would be passed to the filter callbacks or if there would be a special function available for this, e.g. </p>\n\n<pre><code>wp_get_user_from_id_or_email( $id_or_email )\n</code></pre>\n"
}
] |
2016/06/06
|
[
"https://wordpress.stackexchange.com/questions/228870",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96286/"
] |
By default, Wordpress uses Gravatar for user avatars.
I've created a custom field for avatar uploads, and I'm using this as users' avatars on various pages in the theme.
In the admin - on the all users page - there is a column that would normally display the user's avatar (see below). Is there a way to use my custom field *instead* of the default gravatar field?
[](https://i.stack.imgur.com/liK7I.jpg)
|
As an alternative to my other answer, you can also use the `get_avatar` filter. Props to [Sumit](https://wordpress.stackexchange.com/users/32475/sumit) to alerting me to this one.
The benefit of using the `get_avatar` filter is your custom avatar should be applied *anywhere* Wordpress uses it, rather than just in this users list like my other answer deals with. If you use plugins that display user avatars, this solution should also work for them, providing they play nicely and use the Wordpress filters they should be using :)
The [official docs for the `get_avatar` filter are here](https://developer.wordpress.org/reference/functions/get_avatar/).
In your theme's `functions.php`, you'll want set up your function like this:
```
add_filter("get_avatar", "wpse_228870_custom_user_avatar", 1, 5);
function wpse_228870_custom_user_avatar($avatar, $id_or_email, $size, $alt, $args){
// determine which user we're asking about - this is the hard part!
// ........
// get your custom field here, using the user's object to get the correct one
// ........
// enter your custom image output here
$avatar = '<img alt="' . $alt . '" src="image.png" width="' . $size . '" height="' . $size . '" />';
return $avatar;
}
```
Now there's a lot missing from that because, perhaps frustratingly, Wordpress doesn't send a nice clean user object or user ID through to this filter - according to the docs it can give us:
>
> a user\_id, gravatar md5 hash, user email, WP\_User object, WP\_Post object, or WP\_Comment object
>
>
>
Most of these we can deal with - if we got a Gravatar hash that'd be a bit difficult - but the rest we can use the built in Wordpress functions to get the correct user object.
There's [an example that gets started on this in the old Wordpress docs](https://codex.wordpress.org/Plugin_API/Filter_Reference/get_avatar#Example). However for this filter to work properly everywhere it's used, you'll need to write a little extra to make sure you can detect and deal with a post or comment object coming through as well (perhaps using the [PHP is\_a function](http://php.net/is_a)) and then getting the associated post or comment author.
|
228,875 |
<p>I'm having trouble getting my shortcode to output all of the markup - for some reason it's only outputting part of it.</p>
<p>I have the following function:</p>
<pre><code>function shortcode_container($atts, $content = null) {
$type = isset($atts['type']) ? $atts['type'] : '';
$margintop = isset($atts['margintop']) ? $atts['margintop'] : '';
$marginbottom = isset($atts['marginbottom']) ? $atts['marginbottom'] : '';
$output = '';
$output .= '<div class="container '.$type.'" style="margin-top:'.$margintop.'; margin-bottom:'.$marginbottom.'">';
$output .= '<section>';
$output .= '<div class="row">';
$output .= apply_filters('the_content', $content);
$output .= '</div>';
$output .= '</section>';
$output .= '</div>';
return $output;
}
</code></pre>
<p>I want to be able to write into the WP WYSIWYG: </p>
<pre><code>[container]
Text
[/container]
</code></pre>
<p>So it'll output as:</p>
<pre><code><div class="container">
<section>
<div class="row">
Text
</div>
</section>
</div>
</code></pre>
<p>The code currently only outputs the <code><div class="container"></code> and nothing else, no <code><section></code> or <code><div class="row"></code>.</p>
<p>My full functions.php file is <a href="http://pastebin.com/Jjn52zKD" rel="nofollow">here</a>.</p>
|
[
{
"answer_id": 228872,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 1,
"selected": false,
"text": "<p><strong>EDIT:</strong> My original solution is below, but <a href=\"https://wordpress.stackexchange.com/users/32475/sumit\">Sumit</a> alerted me in the comments to the existence of the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/get_avatar\" rel=\"nofollow noreferrer\">get_avatar filter</a>. I've posted <a href=\"https://wordpress.stackexchange.com/a/228906/46066\">an additional answer</a> that shows how to implement that option as well.</p>\n\n<hr>\n\n<p>Yes, you can do this.</p>\n\n<p>The columns displayed in any of these 'list tables' in Wordpress admin are filterable - so using a custom function in your theme's <code>functions.php</code>, you can remove columns or add your own.</p>\n\n<p>This function will allow you to both remove the default column and add a custom one:</p>\n\n<pre><code>add_filter(\"manage_users_columns\", \"wpse_228870_custom_user_avatar\");\n\nfunction wpse_228870_custom_user_avatar($columns){\n\n $columns = \n array_slice($columns, 0, 1) // leave the checkbox in place (the 0th column)\n + array(\"custom_avatar\" => \"\") // splice in a custom avatar column in the next space\n + array_slice($columns, 1) // include any other remaining columns (the 1st column onwards)\n ;\n\n return $columns;\n\n}\n</code></pre>\n\n<p>There's many ways you can do that but in this I've basically just taken the <code>$columns</code> array and massaged it to stick your custom avatar in at the second position. You can use any PHP array function to do whatever you want to these columns.</p>\n\n<p>Next, we need to tell Wordpress what to display in that <code>custom_avatar</code> column:</p>\n\n<pre><code>add_filter(\"manage_users_custom_column\", \"wpse_228870_custom_user_avatar_column\", 10, 3);\n\nfunction wpse_228870_custom_user_avatar_column($output, $column_name, $user_id){\n\n // bow out early if this isn't our custom column!\n if($column_name != \"custom_avatar\"){ return $output; }\n\n // get your custom field here, using $user_id to get the correct one\n // ........\n\n // enter your custom image output here\n $output = '<img src=\"image.png\" width=\"50\" height=\"50\" />';\n\n return $output;\n\n}\n</code></pre>\n\n<p>If the image doesn't come out at the right dimensions or isn't styled appropriately, you can <a href=\"https://wordpress.stackexchange.com/a/110899/46066\">add styles to Wordpress admin</a> if you want to have more control over how the columns and their contents are sized.</p>\n\n<p>You can also read more about the two filters I used in the Wordpress documentation - <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/manage_users_columns\" rel=\"nofollow noreferrer\">manage_users_columns</a> is on the Codex and <a href=\"https://developer.wordpress.org/reference/hooks/manage_users_custom_column/\" rel=\"nofollow noreferrer\">manage_users_custom_column</a> is on the newer code reference. Similar filters exist for any of the other tables, such as posts and pages.</p>\n"
},
{
"answer_id": 228906,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 3,
"selected": false,
"text": "<p>As an alternative to my other answer, you can also use the <code>get_avatar</code> filter. Props to <a href=\"https://wordpress.stackexchange.com/users/32475/sumit\">Sumit</a> to alerting me to this one.</p>\n\n<p>The benefit of using the <code>get_avatar</code> filter is your custom avatar should be applied <em>anywhere</em> Wordpress uses it, rather than just in this users list like my other answer deals with. If you use plugins that display user avatars, this solution should also work for them, providing they play nicely and use the Wordpress filters they should be using :)</p>\n\n<p>The <a href=\"https://developer.wordpress.org/reference/functions/get_avatar/\" rel=\"nofollow noreferrer\">official docs for the <code>get_avatar</code> filter are here</a>.</p>\n\n<p>In your theme's <code>functions.php</code>, you'll want set up your function like this:</p>\n\n<pre><code>add_filter(\"get_avatar\", \"wpse_228870_custom_user_avatar\", 1, 5);\n\nfunction wpse_228870_custom_user_avatar($avatar, $id_or_email, $size, $alt, $args){\n\n // determine which user we're asking about - this is the hard part!\n // ........\n\n // get your custom field here, using the user's object to get the correct one\n // ........\n\n // enter your custom image output here\n $avatar = '<img alt=\"' . $alt . '\" src=\"image.png\" width=\"' . $size . '\" height=\"' . $size . '\" />';\n\n return $avatar;\n\n}\n</code></pre>\n\n<p>Now there's a lot missing from that because, perhaps frustratingly, Wordpress doesn't send a nice clean user object or user ID through to this filter - according to the docs it can give us:</p>\n\n<blockquote>\n <p>a user_id, gravatar md5 hash, user email, WP_User object, WP_Post object, or WP_Comment object</p>\n</blockquote>\n\n<p>Most of these we can deal with - if we got a Gravatar hash that'd be a bit difficult - but the rest we can use the built in Wordpress functions to get the correct user object.</p>\n\n<p>There's <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/get_avatar#Example\" rel=\"nofollow noreferrer\">an example that gets started on this in the old Wordpress docs</a>. However for this filter to work properly everywhere it's used, you'll need to write a little extra to make sure you can detect and deal with a post or comment object coming through as well (perhaps using the <a href=\"http://php.net/is_a\" rel=\"nofollow noreferrer\">PHP is_a function</a>) and then getting the associated post or comment author.</p>\n"
},
{
"answer_id": 228913,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>We could also use one of the following filters, available since WordPress 4.2:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/pre_get_avatar_data/\" rel=\"nofollow\"><code>pre_get_avatar_data</code></a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/get_avatar_url/\" rel=\"nofollow\"><code>get_avatar_url</code></a> </li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/get_avatar_data/\" rel=\"nofollow\"><code>get_avatar_data</code></a></li>\n</ul>\n\n<p>Regarding how to get the user ID from the <code>$id_or_email</code> we can see how it's done in the <a href=\"https://github.com/WordPress/WordPress/blob/4.5-branch/wp-includes/link-template.php#L3838-3883\" rel=\"nofollow\">core</a>:</p>\n\n<pre><code>$email_hash = '';\n$user = $email = false;\nif ( is_object( $id_or_email ) && isset( $id_or_email->comment_ID ) ) {\n $id_or_email = get_comment( $id_or_email );\n}\n// Process the user identifier.\nif ( is_numeric( $id_or_email ) ) {\n $user = get_user_by( 'id', absint( $id_or_email ) );\n} elseif ( is_string( $id_or_email ) ) {\n if ( strpos( $id_or_email, '@md5.gravatar.com' ) ) {\n // md5 hash\n list( $email_hash ) = explode( '@', $id_or_email );\n } else {\n // email address\n $email = $id_or_email;\n }\n} elseif ( $id_or_email instanceof WP_User ) {\n // User Object\n $user = $id_or_email;\n} elseif ( $id_or_email instanceof WP_Post ) {\n // Post Object\n $user = get_user_by( 'id', (int) $id_or_email->post_author );\n} elseif ( $id_or_email instanceof WP_Comment ) {\n /**\n * Filter the list of allowed comment types for retrieving avatars.\n *\n * @since 3.0.0\n *\n * @param array $types An array of content types. Default only contains 'comment'.\n */\n $allowed_comment_types = apply_filters( 'get_avatar_comment_types', array( 'comment' ) );\n if ( ! empty( $id_or_email->comment_type ) && ! in_array( $id_or_email->comment_type, (array) $allowed_comment_types ) ) {\n $args['url'] = false;\n /** This filter is documented in wp-includes/link-template.php */\n return apply_filters( 'get_avatar_data', $args, $id_or_email );\n }\n if ( ! empty( $id_or_email->user_id ) ) {\n $user = get_user_by( 'id', (int) $id_or_email->user_id );\n }\n if ( ( ! $user || is_wp_error( $user ) ) && ! empty( $id_or_email->comment_author_email ) ) {\n $email = $id_or_email->comment_author_email;\n }\n}\n</code></pre>\n\n<p>It would be easier if the user ID would be passed to the filter callbacks or if there would be a special function available for this, e.g. </p>\n\n<pre><code>wp_get_user_from_id_or_email( $id_or_email )\n</code></pre>\n"
}
] |
2016/06/06
|
[
"https://wordpress.stackexchange.com/questions/228875",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96257/"
] |
I'm having trouble getting my shortcode to output all of the markup - for some reason it's only outputting part of it.
I have the following function:
```
function shortcode_container($atts, $content = null) {
$type = isset($atts['type']) ? $atts['type'] : '';
$margintop = isset($atts['margintop']) ? $atts['margintop'] : '';
$marginbottom = isset($atts['marginbottom']) ? $atts['marginbottom'] : '';
$output = '';
$output .= '<div class="container '.$type.'" style="margin-top:'.$margintop.'; margin-bottom:'.$marginbottom.'">';
$output .= '<section>';
$output .= '<div class="row">';
$output .= apply_filters('the_content', $content);
$output .= '</div>';
$output .= '</section>';
$output .= '</div>';
return $output;
}
```
I want to be able to write into the WP WYSIWYG:
```
[container]
Text
[/container]
```
So it'll output as:
```
<div class="container">
<section>
<div class="row">
Text
</div>
</section>
</div>
```
The code currently only outputs the `<div class="container">` and nothing else, no `<section>` or `<div class="row">`.
My full functions.php file is [here](http://pastebin.com/Jjn52zKD).
|
As an alternative to my other answer, you can also use the `get_avatar` filter. Props to [Sumit](https://wordpress.stackexchange.com/users/32475/sumit) to alerting me to this one.
The benefit of using the `get_avatar` filter is your custom avatar should be applied *anywhere* Wordpress uses it, rather than just in this users list like my other answer deals with. If you use plugins that display user avatars, this solution should also work for them, providing they play nicely and use the Wordpress filters they should be using :)
The [official docs for the `get_avatar` filter are here](https://developer.wordpress.org/reference/functions/get_avatar/).
In your theme's `functions.php`, you'll want set up your function like this:
```
add_filter("get_avatar", "wpse_228870_custom_user_avatar", 1, 5);
function wpse_228870_custom_user_avatar($avatar, $id_or_email, $size, $alt, $args){
// determine which user we're asking about - this is the hard part!
// ........
// get your custom field here, using the user's object to get the correct one
// ........
// enter your custom image output here
$avatar = '<img alt="' . $alt . '" src="image.png" width="' . $size . '" height="' . $size . '" />';
return $avatar;
}
```
Now there's a lot missing from that because, perhaps frustratingly, Wordpress doesn't send a nice clean user object or user ID through to this filter - according to the docs it can give us:
>
> a user\_id, gravatar md5 hash, user email, WP\_User object, WP\_Post object, or WP\_Comment object
>
>
>
Most of these we can deal with - if we got a Gravatar hash that'd be a bit difficult - but the rest we can use the built in Wordpress functions to get the correct user object.
There's [an example that gets started on this in the old Wordpress docs](https://codex.wordpress.org/Plugin_API/Filter_Reference/get_avatar#Example). However for this filter to work properly everywhere it's used, you'll need to write a little extra to make sure you can detect and deal with a post or comment object coming through as well (perhaps using the [PHP is\_a function](http://php.net/is_a)) and then getting the associated post or comment author.
|
228,889 |
<p>I am creating a website. There is a column for latest updates.
This is the code that i have now. I don't really good in php coding. Would like to get guidance from someone.</p>
<pre><code><?php
$postslist = get_posts('numberposts=1&order=DESC&orderby=date');
foreach ($postslist as $post) :
setup_postdata($post);
?>
<?php the_excerpt(); ?>
<p class="date"><?php echo get_the_date(); ?></p>
<span class="button">
<a href="<?php the_permalink(); ?>">Read More</a>
</code></pre>
<p>But, i would like to exclude some posts from certain categories. Is there any solution to make it happen? Thank you!</p>
|
[
{
"answer_id": 228891,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 2,
"selected": false,
"text": "<p>From a quick look at the <a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow noreferrer\">documentation for get_posts()</a>, it doesn't look like you can exclude a post based on its category.</p>\n\n<p><strong>EDIT:</strong> Actually, thanks to <a href=\"https://wordpress.stackexchange.com/users/5077/antonchanning\">AntonChanning</a>, turns out you can - just add <code>&cat=-1</code> to your argument string, where 1 is the ID of the category you wish to exclude:</p>\n\n<pre><code>$postslist = get_posts('numberposts=1&order=DESC&orderby=date&cat=-1');\n</code></pre>\n\n<p>You can also add multiple categories to this if you need to, eg. <code>cat=-1,-2,-3</code></p>\n\n<hr>\n\n<p>The preferred 'Wordpress way' to do this is <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">using WP_Query</a>.</p>\n\n<p>If you want to do it this way, instead of your call to <code>get_posts()</code>, you'll need to create a new instance of WP_Query and pass your arguments through in an array. From the above link under the <em>Category Parameters</em> heading:</p>\n\n<blockquote>\n <p>category__not_in (array) – use category id</p>\n</blockquote>\n\n<p>That's the argument you'll want to use to exclude a category:</p>\n\n<pre><code>$postslist = new WP_Query(array(\n \"post_type\" => \"post\",\n \"posts_per_page\" => 1,\n \"order\" => \"DESC\"\n \"orderby\" => \"date\",\n \"category__not_in\" => 1,\n));\n</code></pre>\n\n<p>You'll notice I also added the 'post' post type to mimic the behaviour you would have had with <code>get_posts()</code>, and the <code>posts_per_page</code> parameter is the way to specify the number of posts returned with WP_Query.</p>\n\n<p>One other change you'll need to make if you do go down this WP_Query route is to use a <code>while</code> loop instead of the <code>foreach</code> you currently have. There's <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">clear usage examples</a> under the <em>Usage</em> heading in the docs so I'll avoid copying and pasting them out.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 228915,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>In addition to the answer by Tim, one can always use a proper <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow\"><code>tax_query</code></a>. All the build in tag and category parameters gets converted to a proper <code>tax_query</code> before being passed to the <code>WP_Tax_Query</code> class to build the <code>JOIN</code> clause for the SQL query.</p>\n\n<p>I use a <code>tax_query</code> in almost all applications as it gives one a lot of flexibilty, specially when it comes to child terms, exclusions of multiple terms and even multiple taxonomies. Maybe the only downfall is that you cannot use the string syntax here as in the OP, bacause a <code>tax_query</code> is an array, one should use the array syntax for the query args</p>\n\n<p>In short, to exclude categories, you can try the following</p>\n\n<pre><code>$args = [\n // Your other args\n 'tax_query' => [\n [\n 'taxonomy' => 'category',\n 'field' => 'term_id',\n 'terms' => [1,2,3], // Array of term ids to exclude\n 'operator' => 'NOT IN', // Exclude\n 'exclude_children' => false // Do not exclude the child terms from the terms defined to exclude\n ]\n ]\n];\n$postslist = get_posts( $args );\n</code></pre>\n"
}
] |
2016/06/06
|
[
"https://wordpress.stackexchange.com/questions/228889",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23036/"
] |
I am creating a website. There is a column for latest updates.
This is the code that i have now. I don't really good in php coding. Would like to get guidance from someone.
```
<?php
$postslist = get_posts('numberposts=1&order=DESC&orderby=date');
foreach ($postslist as $post) :
setup_postdata($post);
?>
<?php the_excerpt(); ?>
<p class="date"><?php echo get_the_date(); ?></p>
<span class="button">
<a href="<?php the_permalink(); ?>">Read More</a>
```
But, i would like to exclude some posts from certain categories. Is there any solution to make it happen? Thank you!
|
In addition to the answer by Tim, one can always use a proper [`tax_query`](https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters). All the build in tag and category parameters gets converted to a proper `tax_query` before being passed to the `WP_Tax_Query` class to build the `JOIN` clause for the SQL query.
I use a `tax_query` in almost all applications as it gives one a lot of flexibilty, specially when it comes to child terms, exclusions of multiple terms and even multiple taxonomies. Maybe the only downfall is that you cannot use the string syntax here as in the OP, bacause a `tax_query` is an array, one should use the array syntax for the query args
In short, to exclude categories, you can try the following
```
$args = [
// Your other args
'tax_query' => [
[
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => [1,2,3], // Array of term ids to exclude
'operator' => 'NOT IN', // Exclude
'exclude_children' => false // Do not exclude the child terms from the terms defined to exclude
]
]
];
$postslist = get_posts( $args );
```
|
228,917 |
<p>I have created a WordPress plugin to create a widget area to display category names (total nmbr of post) and description.Now I want to show the category image just after the category name and after the image I want to show category description. Although category names and description display successfully I just want the complete code of how to add feature image to category and how that will display in my category description widget area.</p>
<p>For Reference here is my complete <strong>Category Description Widget Area</strong> code.</p>
<pre><code><?php
/*
Plugin Name: My Category Description Widget Plugin
Plugin URI: http://mkrdip.me/category-posts-widget
Description: Adds a widget that shows all categories along with their description.
Author: Muhammad Jahangir
Version: 1.0
Author URI: http://facebook.com/jahangirKhattakPk
*/
class categories_description extends WP_Widget
{
function __construct()
{
$widget_ops = array(
'classname' => 'categoryDescription widget',
'description' => 'Show all categories with their description.',
);
parent::__construct( 'categories_description', 'My Category Description', $widget_ops );
}
// end __construct()
public function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : __( 'New title', 'text_domain' );
?>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php _e( esc_attr( 'Title:' ) ); ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
</p>
<?php
}
// End form function
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
// End update function
function widget($args,$instance){
echo $args['before_widget'];
if ( ! empty( $instance['title'] ) )
{
?>
<div class="categoriesDescription bgWhite">
<div class="container innerContainer">
<h2 class="widgetTitle"><?php echo apply_filters( 'widget_title', $instance['title'] ); } ?></h2>
<?php $categories = get_categories();
foreach ($categories as $cat)
{
$cat_name = $cat->name;
$CategoryID = get_cat_ID( $cat_name );
$totalPosts = $cat->count;
$currentcatname = $cat_name;
?>
<div class="category-image">
</div>
<div class="singleCategory col-lg-4">
<a href="<?php echo get_category_link( $cat ); ?>" class="uppercase categoryTitle">
<?php echo $cat_name; ?></a>
<span class="numberOfPosts">
<?php
echo '( '.$totalPosts.' )';
?>
</span>
<div class="CategoryImg"><?php echo $cat->term_icon; ?>
// here I want to show category feature image...
<div class="my-image">
<?php
?>
<header class="archive-header <?php if ($category_image==true) echo 'category-image'; ?>">
</div>
</div>
<p class="CategoryDescription"><?php echo $cat->description; ?></p>
<p><?php echo $CategoryID; ?></p>
</div>
<?php
} ?>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
<?php
}
// End widget function
}
//end categories_description class
add_action('widgets_init', function() {
register_widget('categories_description');
})
?>
</code></pre>
|
[
{
"answer_id": 228979,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": -1,
"selected": false,
"text": "<p>I'd say register a custom post type, eg. <code>cat_image</code>, so the images can be uploaded to a post using the existing featured image metabox.</p>\n\n<p>You could sync the data using <code>wp_insert_post</code> matching the widget ID to the custom post slug..?</p>\n\n<pre><code>// to match widget to an existing custom post\n// similar to get_post but can use slug (if no post parents)\n$slug = $instance['id']; // not sure on this?\n$post = get_page_by_path($slug,OBJECT,'cat_image');\n\nif (!$post) {\n // create fresh post from widget instance data\n $args = array('post_type' => 'cat_image'); // ...and all the rest\n $post = wp_insert_post($args);\n}\n\n$thumbnail_id = get_post_meta( $post->ID, '_thumbnail_id', true ); \n$postthumbnailhtml = _wp_post_thumbnail_html( $thumbnail_id, $post->ID );\n</code></pre>\n\n<p>This will give you the upload element linked to the post ID... (plus you may need to make sure you have <code>wp_enqueue_media</code> enqueued on the widget page if it's not already?)</p>\n\n<p>Anyway that is one suggestion, you would still have to build a form element around it the HTML metabox and see what happens... have not had time to test it out yet, hopefully the output is easy enough to access and insert as an attachment to the linked custom post.</p>\n"
},
{
"answer_id": 294917,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>In general there is no such thing as a \"featured image\" for categories or other types of terms. The easiest thing to do is to integrate with existing plugins and themes that support this kind of functionality and/or supply an easy to use filter that for site owners to be able to customize where to get the information from.</p>\n"
}
] |
2016/06/06
|
[
"https://wordpress.stackexchange.com/questions/228917",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96314/"
] |
I have created a WordPress plugin to create a widget area to display category names (total nmbr of post) and description.Now I want to show the category image just after the category name and after the image I want to show category description. Although category names and description display successfully I just want the complete code of how to add feature image to category and how that will display in my category description widget area.
For Reference here is my complete **Category Description Widget Area** code.
```
<?php
/*
Plugin Name: My Category Description Widget Plugin
Plugin URI: http://mkrdip.me/category-posts-widget
Description: Adds a widget that shows all categories along with their description.
Author: Muhammad Jahangir
Version: 1.0
Author URI: http://facebook.com/jahangirKhattakPk
*/
class categories_description extends WP_Widget
{
function __construct()
{
$widget_ops = array(
'classname' => 'categoryDescription widget',
'description' => 'Show all categories with their description.',
);
parent::__construct( 'categories_description', 'My Category Description', $widget_ops );
}
// end __construct()
public function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : __( 'New title', 'text_domain' );
?>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php _e( esc_attr( 'Title:' ) ); ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
</p>
<?php
}
// End form function
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
// End update function
function widget($args,$instance){
echo $args['before_widget'];
if ( ! empty( $instance['title'] ) )
{
?>
<div class="categoriesDescription bgWhite">
<div class="container innerContainer">
<h2 class="widgetTitle"><?php echo apply_filters( 'widget_title', $instance['title'] ); } ?></h2>
<?php $categories = get_categories();
foreach ($categories as $cat)
{
$cat_name = $cat->name;
$CategoryID = get_cat_ID( $cat_name );
$totalPosts = $cat->count;
$currentcatname = $cat_name;
?>
<div class="category-image">
</div>
<div class="singleCategory col-lg-4">
<a href="<?php echo get_category_link( $cat ); ?>" class="uppercase categoryTitle">
<?php echo $cat_name; ?></a>
<span class="numberOfPosts">
<?php
echo '( '.$totalPosts.' )';
?>
</span>
<div class="CategoryImg"><?php echo $cat->term_icon; ?>
// here I want to show category feature image...
<div class="my-image">
<?php
?>
<header class="archive-header <?php if ($category_image==true) echo 'category-image'; ?>">
</div>
</div>
<p class="CategoryDescription"><?php echo $cat->description; ?></p>
<p><?php echo $CategoryID; ?></p>
</div>
<?php
} ?>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
<?php
}
// End widget function
}
//end categories_description class
add_action('widgets_init', function() {
register_widget('categories_description');
})
?>
```
|
In general there is no such thing as a "featured image" for categories or other types of terms. The easiest thing to do is to integrate with existing plugins and themes that support this kind of functionality and/or supply an easy to use filter that for site owners to be able to customize where to get the information from.
|
228,941 |
<p>i have a meta box for some email address and i save value in save_post hook</p>
<pre><code>add_action( 'save_post', 'sm12_save_post' );
function sm12_save_post( $postid ){
update_post_meta( $postid, '_some_email_address', $_POST['some_email_address'] );
}
</code></pre>
<p>Now i want to send email to this email address only when this post is published. So i use</p>
<pre><code>add_action( 'publish_post', 'sm12_publish_post' );
function sm12_publish_post( $postid ){
$email = get_post_meta( $postid, '_some_email_address', true );
if( ! $email )
return;
$sub = 'test subject';
$mgs = 'test message';
wp_mail( $email, $sub, $mgs );
}
</code></pre>
<p>if post is saved in any other status other than 'publish' then it sends email when publish, but if post is directly publish it can not send email, because 'publish_post' is called before 'save_post' and meta is not yet available there. how to send email only when published in my case? should not call wp_transition_post_status() last of everything during save?</p>
|
[
{
"answer_id": 228979,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": -1,
"selected": false,
"text": "<p>I'd say register a custom post type, eg. <code>cat_image</code>, so the images can be uploaded to a post using the existing featured image metabox.</p>\n\n<p>You could sync the data using <code>wp_insert_post</code> matching the widget ID to the custom post slug..?</p>\n\n<pre><code>// to match widget to an existing custom post\n// similar to get_post but can use slug (if no post parents)\n$slug = $instance['id']; // not sure on this?\n$post = get_page_by_path($slug,OBJECT,'cat_image');\n\nif (!$post) {\n // create fresh post from widget instance data\n $args = array('post_type' => 'cat_image'); // ...and all the rest\n $post = wp_insert_post($args);\n}\n\n$thumbnail_id = get_post_meta( $post->ID, '_thumbnail_id', true ); \n$postthumbnailhtml = _wp_post_thumbnail_html( $thumbnail_id, $post->ID );\n</code></pre>\n\n<p>This will give you the upload element linked to the post ID... (plus you may need to make sure you have <code>wp_enqueue_media</code> enqueued on the widget page if it's not already?)</p>\n\n<p>Anyway that is one suggestion, you would still have to build a form element around it the HTML metabox and see what happens... have not had time to test it out yet, hopefully the output is easy enough to access and insert as an attachment to the linked custom post.</p>\n"
},
{
"answer_id": 294917,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>In general there is no such thing as a \"featured image\" for categories or other types of terms. The easiest thing to do is to integrate with existing plugins and themes that support this kind of functionality and/or supply an easy to use filter that for site owners to be able to customize where to get the information from.</p>\n"
}
] |
2016/06/06
|
[
"https://wordpress.stackexchange.com/questions/228941",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70211/"
] |
i have a meta box for some email address and i save value in save\_post hook
```
add_action( 'save_post', 'sm12_save_post' );
function sm12_save_post( $postid ){
update_post_meta( $postid, '_some_email_address', $_POST['some_email_address'] );
}
```
Now i want to send email to this email address only when this post is published. So i use
```
add_action( 'publish_post', 'sm12_publish_post' );
function sm12_publish_post( $postid ){
$email = get_post_meta( $postid, '_some_email_address', true );
if( ! $email )
return;
$sub = 'test subject';
$mgs = 'test message';
wp_mail( $email, $sub, $mgs );
}
```
if post is saved in any other status other than 'publish' then it sends email when publish, but if post is directly publish it can not send email, because 'publish\_post' is called before 'save\_post' and meta is not yet available there. how to send email only when published in my case? should not call wp\_transition\_post\_status() last of everything during save?
|
In general there is no such thing as a "featured image" for categories or other types of terms. The easiest thing to do is to integrate with existing plugins and themes that support this kind of functionality and/or supply an easy to use filter that for site owners to be able to customize where to get the information from.
|
229,003 |
<p>Using:</p>
<pre><code>$query = new WP_Query();
</code></pre>
<p>How do I filter to get records with titles OR content OR meta keys which contain a part of a string.</p>
<p>I currently have</p>
<pre><code>$args=array(
'order'=>'asc',
'post_type' => $type,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'my_meta_key',
'value' => sanitize_text_field($_GET["search"]),
'compare' => 'LIKE'
)
),
'posts_per_page' => -1,
'caller_get_posts'=> 1);
</code></pre>
<p>Which is currently working perfectly but does not obvious filter by title and content as well.</p>
|
[
{
"answer_id": 229006,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p>Such condition is impossible to express in current WP API. You can use search for title/content matches and meta query for LIKE matches on post meta, but there is no way to establish OR relationship between the two.</p>\n\n<p>The closest API way would be two–stage query where you query IDs for two sets of results (one for search, one for meta), then query full data for their combination.</p>\n\n<p>Outside of that it is realm custom SQL. Not impossible, but relatively hard to write and harder to maintain.</p>\n"
},
{
"answer_id": 244920,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 0,
"selected": false,
"text": "<p>I think this code can do what you want:</p>\n\n<pre><code>$q1 = get_posts(array(\n 'post_type' => 'product',\n 'post_status' => 'publish',\n 'posts_per_page' => '-1',\n 's' => get_search_query()\n));\n$q2 = get_posts(array(\n 'post_type' => 'product',\n 'post_status' => 'publish',\n 'posts_per_page' => '-1',\n 'meta_query' => array(\n array(\n 'key' => '_sku',\n 'value' => get_search_query(),\n 'compare' => 'LIKE'\n )\n )\n));\n$merged = array_merge( $q1, $q2 );\n$post_ids = array();\nforeach( $merged as $item ) {\n $post_ids[] = $item->ID;\n}\n$unique = array_unique($post_ids);\nif(!$unique){\n $unique=array('0');\n}\n$args = array(\n 'post_type' => 'product',\n 'posts_per_page' => '10',\n 'post__in' => $unique,\n 'paged' => get_query_var('paged'),\n);\n$wp_query = new WP_Query($args);\n</code></pre>\n"
},
{
"answer_id": 255080,
"author": "Patrick McCullough",
"author_id": 112484,
"author_profile": "https://wordpress.stackexchange.com/users/112484",
"pm_score": 0,
"selected": false,
"text": "<p>You should just be able to tack on</p>\n\n<pre><code>'s' => get_search_query()\n</code></pre>\n\n<p>to your existing query, no? As in:</p>\n\n<pre><code>$args=array(\n 'order'=>'asc',\n 'post_type' => $type,\n 'post_status' => 'publish',\n 'meta_query' => array(\n array(\n 'key' => 'my_meta_key',\n 'value' => sanitize_text_field($_GET[\"search\"]),\n 'compare' => 'LIKE'\n )\n ),\n 's' => get_search_query(),\n 'posts_per_page' => -1,\n 'caller_get_posts'=> 1); \n</code></pre>\n\n<p>I use pretty much this exact approach to a database search where you can search last name or first name (stored as custom fields), and then choose to add in keywords which searches post content within posts that match the custom fields.</p>\n"
},
{
"answer_id": 373252,
"author": "rAthus",
"author_id": 154000,
"author_profile": "https://wordpress.stackexchange.com/users/154000",
"pm_score": 2,
"selected": false,
"text": "<p>I couldn't find a solution to look for multiple keywords that can be mixed in either post title, description AND/OR one or several metas, so I made my own addition to the search function.</p>\n<p>All you is to add the following code in <em>function.php</em>, and whenever you us the 's' argument in WP_Query() and want it to search in one or several as well you simply add a 's_meta_keys' argument that is an array of the meta(s) key you want to search in:</p>\n<pre><code>/************************************************************************\\\n|** **|\n|** Allow WP_Query() search function to look for multiple keywords **|\n|** in metas in addition to post_title and post_content **|\n|** **|\n|** By rAthus @ Arkanite **|\n|** Created: 2020-08-18 **|\n|** Updated: 2020-08-19 **|\n|** **|\n|** Just use the usual 's' argument and add a 's_meta_keys' argument **|\n|** containing an array of the meta(s) key you want to search in :) **|\n|** **|\n|** Example : **|\n|** **|\n|** $args = array( **|\n|** 'numberposts' => -1, **|\n|** 'post_type' => 'post', **|\n|** 's' => $MY_SEARCH_STRING, **|\n|** 's_meta_keys' => array('META_KEY_1','META_KEY_2'); **|\n|** 'orderby' => 'date', **|\n|** 'order' => 'DESC', **|\n|** ); **|\n|** $posts = new WP_Query($args); **|\n|** **|\n\\************************************************************************/\nadd_action('pre_get_posts', 'my_search_query'); // add the special search fonction on each get_posts query (this includes WP_Query())\nfunction my_search_query($query) {\n if ($query->is_search() and $query->query_vars and $query->query_vars['s'] and $query->query_vars['s_meta_keys']) { // if we are searching using the 's' argument and added a 's_meta_keys' argument\n global $wpdb;\n $search = $query->query_vars['s']; // get the search string\n $ids = array(); // initiate array of martching post ids per searched keyword\n foreach (explode(' ',$search) as $term) { // explode keywords and look for matching results for each\n $term = trim($term); // remove unnecessary spaces\n if (!empty($term)) { // check the the keyword is not empty\n $query_posts = $wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE post_status='publish' AND ((post_title LIKE '%%%s%%') OR (post_content LIKE '%%%s%%'))", $term, $term); // search in title and content like the normal function does\n $ids_posts = [];\n $results = $wpdb->get_results($query_posts);\n if ($wpdb->last_error)\n die($wpdb->last_error);\n foreach ($results as $result)\n $ids_posts[] = $result->ID; // gather matching post ids\n $query_meta = [];\n foreach($query->query_vars['s_meta_keys'] as $meta_key) // now construct a search query the search in each desired meta key\n $query_meta[] = $wpdb->prepare("meta_key='%s' AND meta_value LIKE '%%%s%%'", $meta_key, $term);\n $query_metas = $wpdb->prepare("SELECT * FROM {$wpdb->postmeta} WHERE ((".implode(') OR (',$query_meta)."))");\n $ids_metas = [];\n $results = $wpdb->get_results($query_metas);\n if ($wpdb->last_error)\n die($wpdb->last_error);\n foreach ($results as $result)\n $ids_metas[] = $result->post_id; // gather matching post ids\n $merged = array_merge($ids_posts,$ids_metas); // merge the title, content and meta ids resulting from both queries\n $unique = array_unique($merged); // remove duplicates\n if (!$unique)\n $unique = array(0); // if no result, add a "0" id otherwise all posts will be returned\n $ids[] = $unique; // add array of matching ids into the main array\n }\n }\n if (count($ids)>1)\n $intersected = call_user_func_array('array_intersect',$ids); // if several keywords keep only ids that are found in all keywords' matching arrays\n else\n $intersected = $ids[0]; // otherwise keep the only matching ids array\n $unique = array_unique($intersected); // remove duplicates\n if (!$unique)\n $unique = array(0); // if no result, add a "0" id otherwise all posts will be returned\n unset($query->query_vars['s']); // unset normal search query\n $query->set('post__in',$unique); // add a filter by post id instead\n }\n}\n</code></pre>\n<p>Example use:</p>\n<pre><code>$search= "kewords to search";\n\n$args = array(\n 'numberposts' => -1,\n 'post_type' => 'post',\n 's' => $search,\n 's_meta_keys' => array('short_desc','tags');\n 'orderby' => 'date',\n 'order' => 'DESC',\n);\n\n$posts = new WP_Query($args);\n</code></pre>\n<p>This example will look for the keywords "kewords to search" in post titles, descriptions, and meta keys 'short_desc' and 'tags'.</p>\n<p>Keywords can be found in one or several of the fileds, in any order, it will return any post that has all the keywords in any of the designated fields.</p>\n<p>You can obiously force the search in a list of meta keys you include in the fonction and get rid of the extra agruments if you want ALL search queries to include these meta keys :)</p>\n<p>Hope that will help anyone who face the same issue I did!</p>\n"
}
] |
2016/06/07
|
[
"https://wordpress.stackexchange.com/questions/229003",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91596/"
] |
Using:
```
$query = new WP_Query();
```
How do I filter to get records with titles OR content OR meta keys which contain a part of a string.
I currently have
```
$args=array(
'order'=>'asc',
'post_type' => $type,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'my_meta_key',
'value' => sanitize_text_field($_GET["search"]),
'compare' => 'LIKE'
)
),
'posts_per_page' => -1,
'caller_get_posts'=> 1);
```
Which is currently working perfectly but does not obvious filter by title and content as well.
|
Such condition is impossible to express in current WP API. You can use search for title/content matches and meta query for LIKE matches on post meta, but there is no way to establish OR relationship between the two.
The closest API way would be two–stage query where you query IDs for two sets of results (one for search, one for meta), then query full data for their combination.
Outside of that it is realm custom SQL. Not impossible, but relatively hard to write and harder to maintain.
|
229,032 |
<p>For some reason I cannot output the color. Everything works, but <code>text_color</code> just doesn't want to output its value.</p>
<p>What is going wrong?</p>
<p>Back end code (functions.php):</p>
<pre><code>$wp_customize->add_setting('text_color', array(
'default' => '#fff',
'sanitize_callback' => 'sanitize_hex_color',
'type' => 'option',
));
$wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, 'text_color', array(
'label' => __('Text color', 'pc'),
'section' => 'colors',
'settings' => 'text_color',
)));
</code></pre>
<p>Front end code:</p>
<pre><code>if(!empty(get_theme_mod( 'text_color' ))) {
?>
h1, h2, h3, h4, h5, h6 {
color:<?php echo get_theme_mod( 'text_color' ); ?>
}
<?php
}
</code></pre>
|
[
{
"answer_id": 229257,
"author": "mistertaylor",
"author_id": 64117,
"author_profile": "https://wordpress.stackexchange.com/users/64117",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>'type'=>'option'</code> parameter is not required for the colour picker, instead use:</p>\n\n<pre><code>$wp_customize->add_setting('text_color', array(\n 'default' => '#fff',\n 'sanitize_callback' => 'sanitize_hex_color',\n));\n</code></pre>\n"
},
{
"answer_id": 283630,
"author": "Abdelhadi Abdo",
"author_id": 120733,
"author_profile": "https://wordpress.stackexchange.com/users/120733",
"pm_score": -1,
"selected": false,
"text": "<p>if you are using this </p>\n\n<pre><code>add_setting('text_color'...\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>add_setting('themename_theme['text_color'] ....\n</code></pre>\n\n<p>you should retrieve data by</p>\n\n<pre><code>get_option('text_color');\n</code></pre>\n"
},
{
"answer_id": 315714,
"author": "ttn_",
"author_id": 91856,
"author_profile": "https://wordpress.stackexchange.com/users/91856",
"pm_score": 2,
"selected": false,
"text": "<p>With</p>\n\n<pre>type => option</pre>\n\n<p>use</p>\n\n<pre>get_option( 'text_color' )</pre>\n\n<p>and</p>\n\n<pre>type => theme_mod (default)</pre>\n\n<p>use</p>\n\n<pre>get_theme_mod( 'text_color' )</pre>\n\n<p>More here: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Customize_Manager/add_setting\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Customize_Manager/add_setting</a></p>\n"
}
] |
2016/06/07
|
[
"https://wordpress.stackexchange.com/questions/229032",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94984/"
] |
For some reason I cannot output the color. Everything works, but `text_color` just doesn't want to output its value.
What is going wrong?
Back end code (functions.php):
```
$wp_customize->add_setting('text_color', array(
'default' => '#fff',
'sanitize_callback' => 'sanitize_hex_color',
'type' => 'option',
));
$wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, 'text_color', array(
'label' => __('Text color', 'pc'),
'section' => 'colors',
'settings' => 'text_color',
)));
```
Front end code:
```
if(!empty(get_theme_mod( 'text_color' ))) {
?>
h1, h2, h3, h4, h5, h6 {
color:<?php echo get_theme_mod( 'text_color' ); ?>
}
<?php
}
```
|
The `'type'=>'option'` parameter is not required for the colour picker, instead use:
```
$wp_customize->add_setting('text_color', array(
'default' => '#fff',
'sanitize_callback' => 'sanitize_hex_color',
));
```
|
229,060 |
<p>In my WordPress workflow I use Gulp and have a task that runs my PHP files through PHPCS using the WordPress coding standards tests (<a href="https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards" rel="nofollow">https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards</a>).</p>
<p>While writing my <code>comments.php</code> file, I have run across the following error:</p>
<blockquote>
<p>Expected next thing to be an escaping function (see Codex for 'Data Validation'), not '_x'</p>
</blockquote>
<p>This is being generateds by the following line of code:</p>
<pre><code>printf( _x( '1 Comment on &ldquo;%s&rdquo;', 'Comments Title', 'jldc' ), get_the_title() );
</code></pre>
<p>I pretty much reused the same line from the Twenty Sixteen theme that ships with WordPress. Out of curiosity I ran PHPCS against Twenty Sixteen's <code>comments.php</code>file and got the same errors.</p>
<p>Now, I can easily use <code>esc_html_x()</code> instead of <code>_x</code> as I presume that is what the guidelines want me to use. But what about this line:</p>
<pre><code>printf(
_nx(
'%1$s Comment on &ldquo;%2$s&rdquo;',
'%1$s Comments on &ldquo;%2$s&rdquo;',
$comment_count,
'Comments Title',
'theme-text-domain'
),
number_format_i18n( $comment_count ),
get_the_title()
);
</code></pre>
<p>Or can I simply ignore the error?</p>
|
[
{
"answer_id": 229052,
"author": "Raviraj Deora",
"author_id": 42652,
"author_profile": "https://wordpress.stackexchange.com/users/42652",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like you have not imported the backup of database (sql file) to new database you have created in your localhost. Also after importing the database to local server you will need to replace the live site URL with new localhost URL at all instances in local database. </p>\n"
},
{
"answer_id": 229057,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>When you copy the files from goDaddy all sorts of oddities from that host may come with it. If I were you I would do a clean install.</p>\n\n<ol>\n<li><p><a href=\"https://wordpress.org/download/\" rel=\"nofollow\">Download WordPress</a> and install it</p></li>\n<li><p>Check which plugins and themes you have running on your goDaddy. Download fresh ones and install them.</p></li>\n<li><p>Export all content from goDaddy (under tools -> export) and upload it locally.</p></li>\n<li><p>Copy the uploads folder from goDaddy to your local install.</p></li>\n<li><p>This leave the options of your widgets, themes and plugins to transfer. If there are few of them just set them anew. There's a plugin for <a href=\"https://nl.wordpress.org/plugins/customizer-export-import/\" rel=\"nofollow\">importing/exporting theme customizer options</a>. Other options can be exported with <a href=\"https://digwp.com/2014/04/backup-restore-theme-options/\" rel=\"nofollow\">this snippet</a>, but it's rather cumbersome.</p></li>\n</ol>\n\n<p>Or you could try the <a href=\"https://wordpress.org/plugins/duplicator/\" rel=\"nofollow\">Duplicator plugin</a>, which I have no experience with.</p>\n"
}
] |
2016/06/07
|
[
"https://wordpress.stackexchange.com/questions/229060",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80069/"
] |
In my WordPress workflow I use Gulp and have a task that runs my PHP files through PHPCS using the WordPress coding standards tests (<https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards>).
While writing my `comments.php` file, I have run across the following error:
>
> Expected next thing to be an escaping function (see Codex for 'Data Validation'), not '\_x'
>
>
>
This is being generateds by the following line of code:
```
printf( _x( '1 Comment on “%s”', 'Comments Title', 'jldc' ), get_the_title() );
```
I pretty much reused the same line from the Twenty Sixteen theme that ships with WordPress. Out of curiosity I ran PHPCS against Twenty Sixteen's `comments.php`file and got the same errors.
Now, I can easily use `esc_html_x()` instead of `_x` as I presume that is what the guidelines want me to use. But what about this line:
```
printf(
_nx(
'%1$s Comment on “%2$s”',
'%1$s Comments on “%2$s”',
$comment_count,
'Comments Title',
'theme-text-domain'
),
number_format_i18n( $comment_count ),
get_the_title()
);
```
Or can I simply ignore the error?
|
It looks like you have not imported the backup of database (sql file) to new database you have created in your localhost. Also after importing the database to local server you will need to replace the live site URL with new localhost URL at all instances in local database.
|
229,094 |
<p>I want to write unit tests for a plugin. I have used WP-CLI to scaffold the test WordPress instance and can successfully run tests.</p>
<p>The plugin I'm writing unit tests for is a site specific plugin rather than a stand-alone plugin destined for the wordpress.org repository. Being a site specific plugin, some functions use functions provided by other plugins, Advanced Custom Fields for example.</p>
<p><strong>Question</strong>: How do I install and load additional plugins, within the WP-CLI scaffolded site, when testing my site specific plugin?</p>
<p>I looked at the <code>bin/install-wp-test.sh</code> file hoping I could add additional wp-cli commands to install and activate the required plugins, but this script does not appear to use wp-cli to create the test WordPress instance.</p>
<p>I've also tried updating the <code>_manually_load_plugin</code> functions within <code>tests/bootstrap.php</code> file with the following code, but it had no effect.</p>
<pre><code>/**
* PHPUnit bootstrap file
*
* @package Site Specific Plugin
*/
$_tests_dir = getenv( 'WP_TESTS_DIR' );
if ( ! $_tests_dir ) {
$_tests_dir = '/tmp/wordpress-tests-lib';
}
// Give access to tests_add_filter() function.
require_once $_tests_dir . '/includes/functions.php';
/**
* Manually load the plugin being tested.
*/
function _manually_load_plugin() {
require dirname( dirname( __FILE__ ) ) . '/battingforchange.php';
// Update array with plugins to include ...
$plugins_to_active = array(
'advanced-custom-fields-pro/acf.php'
);
update_option( 'active_plugins', $plugins_to_active );
}
tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' );
// Start up the WP testing environment.
require $_tests_dir . '/includes/bootstrap.php';
</code></pre>
|
[
{
"answer_id": 229098,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": true,
"text": "<p>What you are trying to do is not unit testing but integration testing, and as integration usually requires some initialization which will be specific to the relevant plugin it is hard to give a general answer which is more then the obvious\"include the plugin file\"</p>\n\n<p>The idea of unit testing is to check that your APIs do what they are supposed to do and the base assumption should be that external APIs work correctly, otherwise there is just no limit to the amount of tests you will have to write.</p>\n\n<p>Once you assume that the external APIs work correctly it doesn't make any difference if you actually call them or just write a function in the same name that just mimics their behavior.</p>\n\n<p>As an example to the idea. In a plugin I write there are several settings that control with which argument <code>WP_Query</code> is being called. To test that I just check the resulting array of argument without bothering actually calling <code>WP_Query</code>. </p>\n"
},
{
"answer_id": 229335,
"author": "Andrew",
"author_id": 50767,
"author_profile": "https://wordpress.stackexchange.com/users/50767",
"pm_score": 0,
"selected": false,
"text": "<p>The testing environment generated by WP-CLI is designed to unit test a single plugin, not for integration testing as pointed out by <a href=\"https://wordpress.stackexchange.com/users/23970/mark-kaplun\">Mark Kaplun</a>.</p>\n\n<p>However, by following this post on <a href=\"https://nerds.inn.org/2014/10/22/unit-testing-themes-and-plugins-in-wordpress/\" rel=\"nofollow noreferrer\">Unit Testing Themes and Plugins in WordPress</a> and you can load themes and additional plugins to do broader intergration tests.</p>\n"
}
] |
2016/06/08
|
[
"https://wordpress.stackexchange.com/questions/229094",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/50767/"
] |
I want to write unit tests for a plugin. I have used WP-CLI to scaffold the test WordPress instance and can successfully run tests.
The plugin I'm writing unit tests for is a site specific plugin rather than a stand-alone plugin destined for the wordpress.org repository. Being a site specific plugin, some functions use functions provided by other plugins, Advanced Custom Fields for example.
**Question**: How do I install and load additional plugins, within the WP-CLI scaffolded site, when testing my site specific plugin?
I looked at the `bin/install-wp-test.sh` file hoping I could add additional wp-cli commands to install and activate the required plugins, but this script does not appear to use wp-cli to create the test WordPress instance.
I've also tried updating the `_manually_load_plugin` functions within `tests/bootstrap.php` file with the following code, but it had no effect.
```
/**
* PHPUnit bootstrap file
*
* @package Site Specific Plugin
*/
$_tests_dir = getenv( 'WP_TESTS_DIR' );
if ( ! $_tests_dir ) {
$_tests_dir = '/tmp/wordpress-tests-lib';
}
// Give access to tests_add_filter() function.
require_once $_tests_dir . '/includes/functions.php';
/**
* Manually load the plugin being tested.
*/
function _manually_load_plugin() {
require dirname( dirname( __FILE__ ) ) . '/battingforchange.php';
// Update array with plugins to include ...
$plugins_to_active = array(
'advanced-custom-fields-pro/acf.php'
);
update_option( 'active_plugins', $plugins_to_active );
}
tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' );
// Start up the WP testing environment.
require $_tests_dir . '/includes/bootstrap.php';
```
|
What you are trying to do is not unit testing but integration testing, and as integration usually requires some initialization which will be specific to the relevant plugin it is hard to give a general answer which is more then the obvious"include the plugin file"
The idea of unit testing is to check that your APIs do what they are supposed to do and the base assumption should be that external APIs work correctly, otherwise there is just no limit to the amount of tests you will have to write.
Once you assume that the external APIs work correctly it doesn't make any difference if you actually call them or just write a function in the same name that just mimics their behavior.
As an example to the idea. In a plugin I write there are several settings that control with which argument `WP_Query` is being called. To test that I just check the resulting array of argument without bothering actually calling `WP_Query`.
|
229,139 |
<p>I've a listing post page where all posts are shown. On each post's row I can perform actions like delete, archive etc. So imagine that:</p>
<ul>
<li>I have an "archive" button;</li>
<li>I push on it and I get a modal (form) saying "Do you want archive this post?"</li>
<li>Into the modal I have the submit button, which should perform the form action and refresh the page, hiding the post just archived.</li>
</ul>
<p><strong>My problem:</strong> My post is archived but I have to refresh the page 2 times before I see it disappeared from my page. When I just click submit, the page refresh but I still see the post which is hidden the second time I reload.</p>
<p>I suppose that I'm doing wrong performing the action. My code in functions.php:</p>
<pre><code>add_action('archive_post','archive_action');
function archive_action($pid) {
if(isset($_POST['archive']))
{
update_post_meta($pid, 'archived', "1");
//other code
}
?>
<div id="archive-modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="box_title">
<?php printf(__("Do you want archive this",'metheme'), $pid);?>
<a class="pull-right" href="#" data-dismiss="modal">&times;</a>
</div>
<div class="box_content">
<form method="post" action="">
<input type="submit" name="archive" style="width:100%; text-align:center;" ?>" />
</form>
</div>
</div>
</div>
<?php }
</code></pre>
<p>I call this function in my loop for passing the <code>$post->id</code> to archive like this:</p>
<pre><code>do_action('archive_post', $pid);
</code></pre>
<p>What I've tried so far:</p>
<ul>
<li>form <code>action=""</code> empty for refreshing the page, as in code: <strong>not working</strong>, the post stays and only if I refresh again it disappears;</li>
<li><code>wp_redirect(get_permalink());</code> in the <code>$_POST</code> function: <strong>same of before</strong>;</li>
<li><code>echo '<meta http-equiv="refresh" content="0.5;url='.$mylink.'" />';</code> it works but, once again, it refreshes the page twice, it's like before, only automated.</li>
</ul>
<p>Is there some other solution? What am I missing please?</p>
|
[
{
"answer_id": 229143,
"author": "Bruno Cantuaria",
"author_id": 65717,
"author_profile": "https://wordpress.stackexchange.com/users/65717",
"pm_score": 1,
"selected": false,
"text": "<p>It's because your function <code>archive_action</code> is executed when the loop was already made. Try hooking your function into the <code>init</code> action, so it would be executed before the loop.</p>\n\n<p>Another prettier approach would be using ajax. So you send the request through Ajax to archive and just use javascript to remove the post from the DOM.</p>\n"
},
{
"answer_id": 229234,
"author": "middlelady",
"author_id": 93927,
"author_profile": "https://wordpress.stackexchange.com/users/93927",
"pm_score": 2,
"selected": false,
"text": "<p>Searching around and not being able to implement the action through <code>init</code> hook I've found this workaround which for sure isn't the best but does the job nicely.</p>\n\n<pre><code>echo \"<script type='text/javascript'>\n window.location=document.location.href;\n </script>\";\n</code></pre>\n\n<p>at the end of <code>$_POST</code> instructions.\nIf somebody has a better solution, welcome to share.</p>\n"
},
{
"answer_id": 247886,
"author": "DarkNeuron",
"author_id": 86731,
"author_profile": "https://wordpress.stackexchange.com/users/86731",
"pm_score": 2,
"selected": false,
"text": "<p>If your page has been submitted, then you can be pretty sure that <code>$_SERVER['HTTP_REFERER']</code> is available.</p>\n\n<p>So you can do either:\n<code>wp_redirect($_SERVER['HTTP_REFERER']);</code>\nor\n<code>header('Location: ' . $_SERVER['HTTP_REFERER'])</code></p>\n\n<p>This will do a redirect to the same page as you're already on.</p>\n"
}
] |
2016/06/08
|
[
"https://wordpress.stackexchange.com/questions/229139",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93927/"
] |
I've a listing post page where all posts are shown. On each post's row I can perform actions like delete, archive etc. So imagine that:
* I have an "archive" button;
* I push on it and I get a modal (form) saying "Do you want archive this post?"
* Into the modal I have the submit button, which should perform the form action and refresh the page, hiding the post just archived.
**My problem:** My post is archived but I have to refresh the page 2 times before I see it disappeared from my page. When I just click submit, the page refresh but I still see the post which is hidden the second time I reload.
I suppose that I'm doing wrong performing the action. My code in functions.php:
```
add_action('archive_post','archive_action');
function archive_action($pid) {
if(isset($_POST['archive']))
{
update_post_meta($pid, 'archived', "1");
//other code
}
?>
<div id="archive-modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="box_title">
<?php printf(__("Do you want archive this",'metheme'), $pid);?>
<a class="pull-right" href="#" data-dismiss="modal">×</a>
</div>
<div class="box_content">
<form method="post" action="">
<input type="submit" name="archive" style="width:100%; text-align:center;" ?>" />
</form>
</div>
</div>
</div>
<?php }
```
I call this function in my loop for passing the `$post->id` to archive like this:
```
do_action('archive_post', $pid);
```
What I've tried so far:
* form `action=""` empty for refreshing the page, as in code: **not working**, the post stays and only if I refresh again it disappears;
* `wp_redirect(get_permalink());` in the `$_POST` function: **same of before**;
* `echo '<meta http-equiv="refresh" content="0.5;url='.$mylink.'" />';` it works but, once again, it refreshes the page twice, it's like before, only automated.
Is there some other solution? What am I missing please?
|
Searching around and not being able to implement the action through `init` hook I've found this workaround which for sure isn't the best but does the job nicely.
```
echo "<script type='text/javascript'>
window.location=document.location.href;
</script>";
```
at the end of `$_POST` instructions.
If somebody has a better solution, welcome to share.
|
229,154 |
<p>How can I add a Customizer widget to add social media icons with links to their social media profiles? To clear it up, I have created a few images with the inspect element.</p>
<p><strong>I want to have a section like this, with an <em>add widget</em> button:</strong></p>
<p><a href="https://i.stack.imgur.com/emPVT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/emPVT.png" alt=""></a></p>
<p><strong>When you click on it, the user will see the Social Media widget:</strong></p>
<p><a href="https://i.stack.imgur.com/zkpJw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zkpJw.png" alt=""></a></p>
<p><strong>The user clicks on it and gets the following form:</strong></p>
<p><a href="https://i.stack.imgur.com/XWGV5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XWGV5.png" alt=""></a></p>
<hr>
<p>What have I tried? I have tried the examples on the <a href="https://codex.wordpress.org/Widgets_API" rel="nofollow noreferrer">widgets API page</a> and I have tried <code>register_sidebar</code>:</p>
<pre><code>function arphabet_widgets_init() {
register_sidebar( array(
'name' => 'Social Media button',
'id' => 'smb',
'before_widget' => '<div>',
'after_widget' => '</div>',
) );
register_sidebar( array(
'name' => 'Link button',
'id' => 'lb',
'before_widget' => '<div>',
'after_widget' => '</div>',
) );
class My_Widget extends WP_Widget {
public function __construct() {
$widget_ops = array(
'classname' => 'my_widget',
'description' => 'Adds a new Social Media button',
);
parent::__construct( 'my_widget', 'Social Media button', $widget_ops );
}
public function widget( $args, $instance ) {
echo $args['before_widget'];
if ( ! empty( $instance['title'] ) ) {
echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
}
echo __( esc_attr( 'Hello, World!' ), 'text_domain' );
echo $args['after_widget'];
}
public function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : __( 'New title', 'text_domain' );
?>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php _e( esc_attr( 'Title:' ) ); ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
}
register_widget( 'My_Widget' );
}
add_action( 'widgets_init', 'arphabet_widgets_init' );
</code></pre>
<p>But that didn't add a "Add Widget" button to the Widget section of the customizer. I'm not sure how I should work this out.</p>
|
[
{
"answer_id": 229143,
"author": "Bruno Cantuaria",
"author_id": 65717,
"author_profile": "https://wordpress.stackexchange.com/users/65717",
"pm_score": 1,
"selected": false,
"text": "<p>It's because your function <code>archive_action</code> is executed when the loop was already made. Try hooking your function into the <code>init</code> action, so it would be executed before the loop.</p>\n\n<p>Another prettier approach would be using ajax. So you send the request through Ajax to archive and just use javascript to remove the post from the DOM.</p>\n"
},
{
"answer_id": 229234,
"author": "middlelady",
"author_id": 93927,
"author_profile": "https://wordpress.stackexchange.com/users/93927",
"pm_score": 2,
"selected": false,
"text": "<p>Searching around and not being able to implement the action through <code>init</code> hook I've found this workaround which for sure isn't the best but does the job nicely.</p>\n\n<pre><code>echo \"<script type='text/javascript'>\n window.location=document.location.href;\n </script>\";\n</code></pre>\n\n<p>at the end of <code>$_POST</code> instructions.\nIf somebody has a better solution, welcome to share.</p>\n"
},
{
"answer_id": 247886,
"author": "DarkNeuron",
"author_id": 86731,
"author_profile": "https://wordpress.stackexchange.com/users/86731",
"pm_score": 2,
"selected": false,
"text": "<p>If your page has been submitted, then you can be pretty sure that <code>$_SERVER['HTTP_REFERER']</code> is available.</p>\n\n<p>So you can do either:\n<code>wp_redirect($_SERVER['HTTP_REFERER']);</code>\nor\n<code>header('Location: ' . $_SERVER['HTTP_REFERER'])</code></p>\n\n<p>This will do a redirect to the same page as you're already on.</p>\n"
}
] |
2016/06/08
|
[
"https://wordpress.stackexchange.com/questions/229154",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94984/"
] |
How can I add a Customizer widget to add social media icons with links to their social media profiles? To clear it up, I have created a few images with the inspect element.
**I want to have a section like this, with an *add widget* button:**
[](https://i.stack.imgur.com/emPVT.png)
**When you click on it, the user will see the Social Media widget:**
[](https://i.stack.imgur.com/zkpJw.png)
**The user clicks on it and gets the following form:**
[](https://i.stack.imgur.com/XWGV5.png)
---
What have I tried? I have tried the examples on the [widgets API page](https://codex.wordpress.org/Widgets_API) and I have tried `register_sidebar`:
```
function arphabet_widgets_init() {
register_sidebar( array(
'name' => 'Social Media button',
'id' => 'smb',
'before_widget' => '<div>',
'after_widget' => '</div>',
) );
register_sidebar( array(
'name' => 'Link button',
'id' => 'lb',
'before_widget' => '<div>',
'after_widget' => '</div>',
) );
class My_Widget extends WP_Widget {
public function __construct() {
$widget_ops = array(
'classname' => 'my_widget',
'description' => 'Adds a new Social Media button',
);
parent::__construct( 'my_widget', 'Social Media button', $widget_ops );
}
public function widget( $args, $instance ) {
echo $args['before_widget'];
if ( ! empty( $instance['title'] ) ) {
echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
}
echo __( esc_attr( 'Hello, World!' ), 'text_domain' );
echo $args['after_widget'];
}
public function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : __( 'New title', 'text_domain' );
?>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php _e( esc_attr( 'Title:' ) ); ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
}
register_widget( 'My_Widget' );
}
add_action( 'widgets_init', 'arphabet_widgets_init' );
```
But that didn't add a "Add Widget" button to the Widget section of the customizer. I'm not sure how I should work this out.
|
Searching around and not being able to implement the action through `init` hook I've found this workaround which for sure isn't the best but does the job nicely.
```
echo "<script type='text/javascript'>
window.location=document.location.href;
</script>";
```
at the end of `$_POST` instructions.
If somebody has a better solution, welcome to share.
|
229,166 |
<p>I am using a custom taxonomy series to keep track of posts that are in a series. I would like to find the posts that do not have a series. I have the following query:</p>
<pre><code>global $wpdb;
$pr = $wpdb->prefix;
$sql_no_series=
"Select
*
from
wp_term_taxonomy tt,
wp_term_relationships tr,
wp_posts p
WHERE
tt.term_taxonomy_id=tr.term_taxonomy_id AND
tr.object_id=p.ID AND
p.ID NOT IN
(Select
p.ID
from
wp_term_taxonomy tt,
wp_term_relationships tr,
wp_posts p
WHERE
tt.term_taxonomy_id=tr.term_taxonomy_id AND
tr.object_id=p.ID AND
tt.taxonomy='series')
AND tt.term_taxonomy_id = $category ";
$no_series = $wpdb->get_results($sql_no_series,ARRAY_A);
</code></pre>
<p>Is there a way to do it using WP_Query?</p>
|
[
{
"answer_id": 229170,
"author": "emily",
"author_id": 66454,
"author_profile": "https://wordpress.stackexchange.com/users/66454",
"pm_score": 1,
"selected": false,
"text": "<p>Something like this should work, where series is the taxonomy name and not a option within a taxonomy:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'my_post_type',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'series',\n 'operator' => 'NOT_EXISTS',\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>reference with plenty of code examples: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow\">https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters</a></p>\n"
},
{
"answer_id": 346728,
"author": "Glenn Forrest",
"author_id": 174701,
"author_profile": "https://wordpress.stackexchange.com/users/174701",
"pm_score": 2,
"selected": false,
"text": "<p>Emily's answer is mostly correct, just that the operator shouldn't have an underscore in it:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'my_post_type',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'series',\n 'operator' => 'NOT EXISTS',\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n"
}
] |
2016/06/08
|
[
"https://wordpress.stackexchange.com/questions/229166",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96456/"
] |
I am using a custom taxonomy series to keep track of posts that are in a series. I would like to find the posts that do not have a series. I have the following query:
```
global $wpdb;
$pr = $wpdb->prefix;
$sql_no_series=
"Select
*
from
wp_term_taxonomy tt,
wp_term_relationships tr,
wp_posts p
WHERE
tt.term_taxonomy_id=tr.term_taxonomy_id AND
tr.object_id=p.ID AND
p.ID NOT IN
(Select
p.ID
from
wp_term_taxonomy tt,
wp_term_relationships tr,
wp_posts p
WHERE
tt.term_taxonomy_id=tr.term_taxonomy_id AND
tr.object_id=p.ID AND
tt.taxonomy='series')
AND tt.term_taxonomy_id = $category ";
$no_series = $wpdb->get_results($sql_no_series,ARRAY_A);
```
Is there a way to do it using WP\_Query?
|
Emily's answer is mostly correct, just that the operator shouldn't have an underscore in it:
```
$args = array(
'post_type' => 'my_post_type',
'tax_query' => array(
array(
'taxonomy' => 'series',
'operator' => 'NOT EXISTS',
),
),
);
$query = new WP_Query( $args );
```
|
229,181 |
<p>I'm trying to learn how to use the Custom Field function. I have a series of posts with titles like "Adams County," "Lane County," etc. All are in the category "Washington" and are tagged with "county."</p>
<p>I want to display the following on each page:</p>
<p>"If you live in $MyCounty, tell us what you think."</p>
<p>$MyCounty would echo the page title (e.g. Adams County). I can easily do this with a PHP include on my regular sites. However, I've been advised that I should use Custom Fields and Shortcodes with WordPress.</p>
<p>I created a Custom Field titled "County Intro." I've been advised to use the following code:</p>
<pre><code>function show_county() {
global $post;
// assumes the string is in the custom field 'county'
$county = get_post_meta( $post->ID, 'county');
if ( $county ) {
return $county;
}
}
add_shortcode( 'county', 'show_county');
</code></pre>
<p>But I don't even know where to insert the code, other than "the loop." Can someone tell me the name of the file I need to open? I'm using a child theme; do I need to copy this file from the theme folder into the child theme folder?</p>
|
[
{
"answer_id": 229201,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": false,
"text": "<p>Quickest way is actually to make a standalone php file (wrap the code in <code><?php</code> CODE <code>?></code> and save it in your <code>/wp-content/mu-plugins/</code> directory, eg, I often use a <code>site-shortcodes.php</code>... </p>\n\n<p>WordPress will auto-load the file, and your functionality will be independent of the theme you use. otherwise if the functionality is tied in to your theme specifically somehow you could use your child theme's <code>functions.php</code></p>\n"
},
{
"answer_id": 229242,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>I would not use custom fields or shortcodes for this functionality, I would look at filters. <code>the_content</code> filter and the <code>loop_end</code> action (<em>just make sure that your theme uses <code>while ( have_posts() )</code> in single post pages</em>) comes to immediate mind here. These are two options which requires no modification of any of your files in your theme. This way you can add extra content to your single post pages (<em>which I assume is what you need</em>) without having to create a child theme. </p>\n\n<p>Approaching your problem this way, you also do not need to remember to use the shortcode or set the custoim field for a particular post, so you have a more dynamic way which you set once and forget about it</p>\n\n<p>For conveniency, and also the recommended way, is to create your <a href=\"https://codex.wordpress.org/Writing_a_Plugin\" rel=\"nofollow\">own custom plugin</a> in which you can dump the code. This way, even if you switch themes, your custom text will still show without having to modify the new theme or create yet another child theme.</p>\n\n<p>Lets look at the two methods to add your custom text line: (<strong><em>NOTE:</strong> All code is untested and should go into a custom plugin</em>)</p>\n\n<h2><code>the_content</code> FILTER</h2>\n\n<p>This will add your custom text after the content on your single post page</p>\n\n<pre><code>add_filter( 'the_content', function ( $content )\n{\n /** \n * Only filter the content on the main query, and when the post belongs\n * to the washington category and are tagged county. Adjust as needed\n */\n if ( !is_single() )\n return $content;\n\n if ( !in_the_loop() )\n return $content;\n\n $post = get_queried_object();\n if ( !in_category( 'washington', $post ) \n && !has_tag( 'county', $post )\n )\n return $content;\n\n // We are inside the main loop, and the post have our category and tag\n // Get the post title\n $MyCounty = apply_filters( 'the_title', $post->post_title );\n // Set our custom text\n $text = \"If you live in $MyCounty, tell us what you think.\";\n\n return $content . $text;\n}):\n</code></pre>\n\n<h2><code>loop_end</code> ACTION</h2>\n\n<p>This will add your text after the post, you can also use <code>loop_start</code> to add the text before the loop, or even <code>the_post</code> which will also add the text before the post. Just note, all actions needs to echo their output</p>\n\n<pre><code>add_action( 'loop_end', function ( \\WP_Query $q )\n{\n // Only target the main query on single pages\n if ( $q->is_main_query()\n && $q->is_single()\n ) {\n $post = get_queried_object();\n if ( in_category( 'washington', $post )\n && has_tag( 'county', $post )\n ) {\n $MyCounty = apply_filters( 'the_title', $post->post_title );\n $text = \"If you live in $MyCounty, tell us what you think.\";\n\n // Echo our custom text\n echo $text;\n }\n }\n}); \n</code></pre>\n"
}
] |
2016/06/08
|
[
"https://wordpress.stackexchange.com/questions/229181",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94575/"
] |
I'm trying to learn how to use the Custom Field function. I have a series of posts with titles like "Adams County," "Lane County," etc. All are in the category "Washington" and are tagged with "county."
I want to display the following on each page:
"If you live in $MyCounty, tell us what you think."
$MyCounty would echo the page title (e.g. Adams County). I can easily do this with a PHP include on my regular sites. However, I've been advised that I should use Custom Fields and Shortcodes with WordPress.
I created a Custom Field titled "County Intro." I've been advised to use the following code:
```
function show_county() {
global $post;
// assumes the string is in the custom field 'county'
$county = get_post_meta( $post->ID, 'county');
if ( $county ) {
return $county;
}
}
add_shortcode( 'county', 'show_county');
```
But I don't even know where to insert the code, other than "the loop." Can someone tell me the name of the file I need to open? I'm using a child theme; do I need to copy this file from the theme folder into the child theme folder?
|
I would not use custom fields or shortcodes for this functionality, I would look at filters. `the_content` filter and the `loop_end` action (*just make sure that your theme uses `while ( have_posts() )` in single post pages*) comes to immediate mind here. These are two options which requires no modification of any of your files in your theme. This way you can add extra content to your single post pages (*which I assume is what you need*) without having to create a child theme.
Approaching your problem this way, you also do not need to remember to use the shortcode or set the custoim field for a particular post, so you have a more dynamic way which you set once and forget about it
For conveniency, and also the recommended way, is to create your [own custom plugin](https://codex.wordpress.org/Writing_a_Plugin) in which you can dump the code. This way, even if you switch themes, your custom text will still show without having to modify the new theme or create yet another child theme.
Lets look at the two methods to add your custom text line: (***NOTE:*** All code is untested and should go into a custom plugin)
`the_content` FILTER
--------------------
This will add your custom text after the content on your single post page
```
add_filter( 'the_content', function ( $content )
{
/**
* Only filter the content on the main query, and when the post belongs
* to the washington category and are tagged county. Adjust as needed
*/
if ( !is_single() )
return $content;
if ( !in_the_loop() )
return $content;
$post = get_queried_object();
if ( !in_category( 'washington', $post )
&& !has_tag( 'county', $post )
)
return $content;
// We are inside the main loop, and the post have our category and tag
// Get the post title
$MyCounty = apply_filters( 'the_title', $post->post_title );
// Set our custom text
$text = "If you live in $MyCounty, tell us what you think.";
return $content . $text;
}):
```
`loop_end` ACTION
-----------------
This will add your text after the post, you can also use `loop_start` to add the text before the loop, or even `the_post` which will also add the text before the post. Just note, all actions needs to echo their output
```
add_action( 'loop_end', function ( \WP_Query $q )
{
// Only target the main query on single pages
if ( $q->is_main_query()
&& $q->is_single()
) {
$post = get_queried_object();
if ( in_category( 'washington', $post )
&& has_tag( 'county', $post )
) {
$MyCounty = apply_filters( 'the_title', $post->post_title );
$text = "If you live in $MyCounty, tell us what you think.";
// Echo our custom text
echo $text;
}
}
});
```
|
229,182 |
<p>I'm a software engineer with a WordPress site with hundreds of pages, and it's working very well. </p>
<p>There are certain cases, however, where I'd love to be able to code my own page with <em>no</em> interaction with / interference from the WordPress system (no themes, no styles, no javascript, etc) yet still have it located on that same subdomain.</p>
<p><strong>How can I set <code>https://example.com/special-page</code> to display an HTML file uploaded somewhere within <code>/wp-content/</code>?</strong></p>
<p>And as a bonus, I'd love if it would also work with a PHP file (which would generate the HTML).</p>
<p>I'd like to do this without manually editing the <code>.htaccess</code> file.</p>
<p>Here is an example that comes close: </p>
<p>The <a href="https://support.leadpages.net/hc/en-us/articles/203522080-Installing-the-WordPress-Plugin" rel="noreferrer">LeadPages WordPress plugin</a> seems to do a variation of what I'm hoping for. It allows a user to specify a "slug" (relative path, such as <code>special-page</code>) and what content to display there. But the content needs to be hosted on LeadPages.net to use this plugin, obviously.</p>
<p><a href="https://i.stack.imgur.com/G59Jc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/G59Jc.png" alt="LeadPages plugin"></a></p>
<p>What I'm hoping to do is host my own HTML file somewhere on my server (e.g. in a publicly-accessible folder such as <code>/wp-content/</code>) and then have a certain relative path point to it.</p>
<p>Look at this <code>.htaccess</code> file that I manually edited (and which works how I want):</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
Options +FollowSymLinks
DirectoryIndex /wp-content/raw/book-sale.html [L]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteRule ^thanks$ /wp-content/raw/book-opt-in-thank-you.html [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>I would have loved to have been able to specify from within the WordPress admin that the site root (<code>/</code>) should show the contents of <code>/wp-content/raw/book-sale.html</code>, and <code>/thanks</code> should show <code>/wp-content/raw/book-opt-in-thank-you.html</code> (so that I wouldn't need to go in an edit the <code>.htaccess</code> file directly.</p>
|
[
{
"answer_id": 229200,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 0,
"selected": false,
"text": "<p>You could create a page with the slug you want, and add a custom field that specifies the HTML path to output (in this example using either <code>htmlfilepath</code> or <code>htmlurl</code> as the metakey):</p>\n\n<pre><code>add_action('wp','maybe_direct_html_output');\n\nfunction maybe_direct_html_output() {\n if (is_singular()) {\n global $post;\n $htmlfilepath = get_post_meta($post->ID,'htmlfilepath',true);\n if ( ($htmlfilepath) && (file_exists($htmlfilepath)) ) {\n echo file_get_contents($htmlfilepath); exit;\n }\n $htmlurl = get_post_meta($post->ID,'htmlurl',true);\n if ($htmlurl) {\n $html = wp_remote_get($html);\n if (!is_wp_error($html)) {echo $html['body']; exit;}\n }\n }\n}\n</code></pre>\n\n<p>So no need for <code>.htaccess</code> when doing it this way... I just noticed you want to use <code>wp-content</code> so you could just use a relative path and simplify this to (using <code>htmlfile</code> metakey):</p>\n\n<pre><code>add_action('wp','maybe_direct_html_output');\n\nfunction maybe_direct_html_output() {\n if (is_singular()) {\n global $post;\n $htmlrelpath = get_post_meta($post->ID,'htmlfile',true);\n if (!$htmlrelpath) {return;}\n $htmlfilepath = WP_CONTENT_DIR.$htmlrelpath;\n if (!file_exists($htmlfilepath)) {return;}\n echo file_get_contents($htmlrelpath); exit;\n }\n}\n</code></pre>\n\n<p>Remembering that <code>WP_CONTENT_DIR</code> has no trailing slash so you would enter a relative path custom field value for the page such as <code>/raw/book-sale.html</code></p>\n"
},
{
"answer_id": 229431,
"author": "Scott Nelle",
"author_id": 52296,
"author_profile": "https://wordpress.stackexchange.com/users/52296",
"pm_score": 1,
"selected": false,
"text": "<p>If you're willing to create a child theme and put your PHP files in there, this approach is relatively clean. For each file, create a rewrite rule where you specify the path you want to use and the filename that should load. In the example below, <code>/custom-path/</code> loads <code>custom-file.php</code> from the root of your child theme directory and <code>/custom-path-2/</code> loads <code>custom-file-2.php</code>. Don't forget to flush permalinks after adding rewrites.</p>\n\n<pre><code>/*\n * Set up a rewrite for each path which should load a file.\n */\nfunction my_standalone_rewrites() {\n add_rewrite_rule( '^custom-path/?', 'index.php?standalone=custom-file', 'top' );\n add_rewrite_rule( '^custom-path-2/?', 'index.php?standalone=custom-file-2', 'top' );\n}\nadd_action( 'init', 'my_standalone_rewrites' );\n\n/*\n * Make `standalone` available as a query var.\n */\nfunction my_query_vars( $vars ) {\n $vars[] = 'standalone';\n return $vars;\n}\nadd_filter( 'query_vars', 'my_query_vars' );\n\n/*\n * If `standalone` is set when parsing the main query, load the standalone file.\n */\nfunction my_standalone_path( &$wp_query ) {\n if ( $wp_query->is_main_query() && get_query_var( 'standalone', false ) ) {\n // Load filename.php from your child theme root.\n get_template_part( get_query_var( 'standalone' ) );\n exit;\n }\n}\nadd_action( 'parse_query', 'my_standalone_path' );\n</code></pre>\n"
},
{
"answer_id": 392644,
"author": "Krafter",
"author_id": 131780,
"author_profile": "https://wordpress.stackexchange.com/users/131780",
"pm_score": 0,
"selected": false,
"text": "<p>For anyone with similar problem, this free plugin has been around for a long time and does partly what is asked here (it doesn't work with PHP files). It lets you create custom HTML pages that bypass WordPress's templating system and they are called by custom URIs. <a href=\"https://wordpress.org/plugins/wp-custom-html-pages/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-custom-html-pages/</a></p>\n<ol>\n<li>Look for WP Custom HTML Pages plugin on the repository, install and activate</li>\n<li>Under Pages menu in admin panel look for HTML Pages menu item</li>\n<li>Create any number of pages and assign them custom URI. The pages are made by adding code into Ace editor.</li>\n</ol>\n"
}
] |
2016/06/08
|
[
"https://wordpress.stackexchange.com/questions/229182",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51462/"
] |
I'm a software engineer with a WordPress site with hundreds of pages, and it's working very well.
There are certain cases, however, where I'd love to be able to code my own page with *no* interaction with / interference from the WordPress system (no themes, no styles, no javascript, etc) yet still have it located on that same subdomain.
**How can I set `https://example.com/special-page` to display an HTML file uploaded somewhere within `/wp-content/`?**
And as a bonus, I'd love if it would also work with a PHP file (which would generate the HTML).
I'd like to do this without manually editing the `.htaccess` file.
Here is an example that comes close:
The [LeadPages WordPress plugin](https://support.leadpages.net/hc/en-us/articles/203522080-Installing-the-WordPress-Plugin) seems to do a variation of what I'm hoping for. It allows a user to specify a "slug" (relative path, such as `special-page`) and what content to display there. But the content needs to be hosted on LeadPages.net to use this plugin, obviously.
[](https://i.stack.imgur.com/G59Jc.png)
What I'm hoping to do is host my own HTML file somewhere on my server (e.g. in a publicly-accessible folder such as `/wp-content/`) and then have a certain relative path point to it.
Look at this `.htaccess` file that I manually edited (and which works how I want):
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
Options +FollowSymLinks
DirectoryIndex /wp-content/raw/book-sale.html [L]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteRule ^thanks$ /wp-content/raw/book-opt-in-thank-you.html [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
I would have loved to have been able to specify from within the WordPress admin that the site root (`/`) should show the contents of `/wp-content/raw/book-sale.html`, and `/thanks` should show `/wp-content/raw/book-opt-in-thank-you.html` (so that I wouldn't need to go in an edit the `.htaccess` file directly.
|
If you're willing to create a child theme and put your PHP files in there, this approach is relatively clean. For each file, create a rewrite rule where you specify the path you want to use and the filename that should load. In the example below, `/custom-path/` loads `custom-file.php` from the root of your child theme directory and `/custom-path-2/` loads `custom-file-2.php`. Don't forget to flush permalinks after adding rewrites.
```
/*
* Set up a rewrite for each path which should load a file.
*/
function my_standalone_rewrites() {
add_rewrite_rule( '^custom-path/?', 'index.php?standalone=custom-file', 'top' );
add_rewrite_rule( '^custom-path-2/?', 'index.php?standalone=custom-file-2', 'top' );
}
add_action( 'init', 'my_standalone_rewrites' );
/*
* Make `standalone` available as a query var.
*/
function my_query_vars( $vars ) {
$vars[] = 'standalone';
return $vars;
}
add_filter( 'query_vars', 'my_query_vars' );
/*
* If `standalone` is set when parsing the main query, load the standalone file.
*/
function my_standalone_path( &$wp_query ) {
if ( $wp_query->is_main_query() && get_query_var( 'standalone', false ) ) {
// Load filename.php from your child theme root.
get_template_part( get_query_var( 'standalone' ) );
exit;
}
}
add_action( 'parse_query', 'my_standalone_path' );
```
|
229,190 |
<p>In the past my organisation has had some problems where a development copy of a site was cloned (through Installatron in cPanel) to a new hosting account, but the new (live) copy of the site had some absolute references to images or files on the development copy of the site.</p>
<p>This meant that when the development site was taken down, some things broke on the live site.</p>
<p><strong>How can I make the development copy of the site offline, including images and other files, so that any absolute URLs referencing it from the live site don't work?</strong> This way when we do our go-live review of the live site, we'll see any problems before the development copy is removed. I don't want to delete the development copy of the site just yet.</p>
<p>A method that can be used through the front end of the site (WP admin or cPanel) would be preferable so that non-technical staff can do it too.</p>
|
[
{
"answer_id": 229200,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 0,
"selected": false,
"text": "<p>You could create a page with the slug you want, and add a custom field that specifies the HTML path to output (in this example using either <code>htmlfilepath</code> or <code>htmlurl</code> as the metakey):</p>\n\n<pre><code>add_action('wp','maybe_direct_html_output');\n\nfunction maybe_direct_html_output() {\n if (is_singular()) {\n global $post;\n $htmlfilepath = get_post_meta($post->ID,'htmlfilepath',true);\n if ( ($htmlfilepath) && (file_exists($htmlfilepath)) ) {\n echo file_get_contents($htmlfilepath); exit;\n }\n $htmlurl = get_post_meta($post->ID,'htmlurl',true);\n if ($htmlurl) {\n $html = wp_remote_get($html);\n if (!is_wp_error($html)) {echo $html['body']; exit;}\n }\n }\n}\n</code></pre>\n\n<p>So no need for <code>.htaccess</code> when doing it this way... I just noticed you want to use <code>wp-content</code> so you could just use a relative path and simplify this to (using <code>htmlfile</code> metakey):</p>\n\n<pre><code>add_action('wp','maybe_direct_html_output');\n\nfunction maybe_direct_html_output() {\n if (is_singular()) {\n global $post;\n $htmlrelpath = get_post_meta($post->ID,'htmlfile',true);\n if (!$htmlrelpath) {return;}\n $htmlfilepath = WP_CONTENT_DIR.$htmlrelpath;\n if (!file_exists($htmlfilepath)) {return;}\n echo file_get_contents($htmlrelpath); exit;\n }\n}\n</code></pre>\n\n<p>Remembering that <code>WP_CONTENT_DIR</code> has no trailing slash so you would enter a relative path custom field value for the page such as <code>/raw/book-sale.html</code></p>\n"
},
{
"answer_id": 229431,
"author": "Scott Nelle",
"author_id": 52296,
"author_profile": "https://wordpress.stackexchange.com/users/52296",
"pm_score": 1,
"selected": false,
"text": "<p>If you're willing to create a child theme and put your PHP files in there, this approach is relatively clean. For each file, create a rewrite rule where you specify the path you want to use and the filename that should load. In the example below, <code>/custom-path/</code> loads <code>custom-file.php</code> from the root of your child theme directory and <code>/custom-path-2/</code> loads <code>custom-file-2.php</code>. Don't forget to flush permalinks after adding rewrites.</p>\n\n<pre><code>/*\n * Set up a rewrite for each path which should load a file.\n */\nfunction my_standalone_rewrites() {\n add_rewrite_rule( '^custom-path/?', 'index.php?standalone=custom-file', 'top' );\n add_rewrite_rule( '^custom-path-2/?', 'index.php?standalone=custom-file-2', 'top' );\n}\nadd_action( 'init', 'my_standalone_rewrites' );\n\n/*\n * Make `standalone` available as a query var.\n */\nfunction my_query_vars( $vars ) {\n $vars[] = 'standalone';\n return $vars;\n}\nadd_filter( 'query_vars', 'my_query_vars' );\n\n/*\n * If `standalone` is set when parsing the main query, load the standalone file.\n */\nfunction my_standalone_path( &$wp_query ) {\n if ( $wp_query->is_main_query() && get_query_var( 'standalone', false ) ) {\n // Load filename.php from your child theme root.\n get_template_part( get_query_var( 'standalone' ) );\n exit;\n }\n}\nadd_action( 'parse_query', 'my_standalone_path' );\n</code></pre>\n"
},
{
"answer_id": 392644,
"author": "Krafter",
"author_id": 131780,
"author_profile": "https://wordpress.stackexchange.com/users/131780",
"pm_score": 0,
"selected": false,
"text": "<p>For anyone with similar problem, this free plugin has been around for a long time and does partly what is asked here (it doesn't work with PHP files). It lets you create custom HTML pages that bypass WordPress's templating system and they are called by custom URIs. <a href=\"https://wordpress.org/plugins/wp-custom-html-pages/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-custom-html-pages/</a></p>\n<ol>\n<li>Look for WP Custom HTML Pages plugin on the repository, install and activate</li>\n<li>Under Pages menu in admin panel look for HTML Pages menu item</li>\n<li>Create any number of pages and assign them custom URI. The pages are made by adding code into Ace editor.</li>\n</ol>\n"
}
] |
2016/06/09
|
[
"https://wordpress.stackexchange.com/questions/229190",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76260/"
] |
In the past my organisation has had some problems where a development copy of a site was cloned (through Installatron in cPanel) to a new hosting account, but the new (live) copy of the site had some absolute references to images or files on the development copy of the site.
This meant that when the development site was taken down, some things broke on the live site.
**How can I make the development copy of the site offline, including images and other files, so that any absolute URLs referencing it from the live site don't work?** This way when we do our go-live review of the live site, we'll see any problems before the development copy is removed. I don't want to delete the development copy of the site just yet.
A method that can be used through the front end of the site (WP admin or cPanel) would be preferable so that non-technical staff can do it too.
|
If you're willing to create a child theme and put your PHP files in there, this approach is relatively clean. For each file, create a rewrite rule where you specify the path you want to use and the filename that should load. In the example below, `/custom-path/` loads `custom-file.php` from the root of your child theme directory and `/custom-path-2/` loads `custom-file-2.php`. Don't forget to flush permalinks after adding rewrites.
```
/*
* Set up a rewrite for each path which should load a file.
*/
function my_standalone_rewrites() {
add_rewrite_rule( '^custom-path/?', 'index.php?standalone=custom-file', 'top' );
add_rewrite_rule( '^custom-path-2/?', 'index.php?standalone=custom-file-2', 'top' );
}
add_action( 'init', 'my_standalone_rewrites' );
/*
* Make `standalone` available as a query var.
*/
function my_query_vars( $vars ) {
$vars[] = 'standalone';
return $vars;
}
add_filter( 'query_vars', 'my_query_vars' );
/*
* If `standalone` is set when parsing the main query, load the standalone file.
*/
function my_standalone_path( &$wp_query ) {
if ( $wp_query->is_main_query() && get_query_var( 'standalone', false ) ) {
// Load filename.php from your child theme root.
get_template_part( get_query_var( 'standalone' ) );
exit;
}
}
add_action( 'parse_query', 'my_standalone_path' );
```
|
229,209 |
<p>I have been searching around the web for this but it doesn't seems there's any topic like this (or maybe I am searching in the wrong direction).</p>
<p>Currently I have a jQuery file which will retrieve 9 additional posts from the database and append to the current posts listing.</p>
<p><strong>File: load-more.js</strong></p>
<pre><code>var data = {
action: 'be_ajax_load_more(tv)', // <-- this is the function in functions.php
nonce: beloadmore.nonce,
page: page,
query: beloadmore.query
};
$.post(beloadmore.url, data, function(res) {
... code function to handle additional posts
}
</code></pre>
<p><strong>File: functions.php</strong></p>
<pre><code>function be_ajax_load_more($category) {
check_ajax_referer( 'be-load-more-nonce', 'nonce' );
error_log( 'Made it into the be_ajax_load_more function');
error_log($category); // <-- this value is empty
return morePosts;
}
</code></pre>
<p>It works perfectly fine if I change both the value of data.action = 'be_ajax_load_more' and function be_ajax_load_more() that receives no parameter, but once I added the parameter, the .post function doesn't recognise it.</p>
<p>Am I passing the parameter correctly? I even tried adding a new key value into my data array:</p>
<pre><code>var data = {
action: 'be_ajax_load_more',
category: 'tv',
nonce: beloadmore.nonce,
page: page,
query: beloadmore.query
};
</code></pre>
<p>But I am not sure how to get that data.category in my functions.php, can anyone help?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 229200,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 0,
"selected": false,
"text": "<p>You could create a page with the slug you want, and add a custom field that specifies the HTML path to output (in this example using either <code>htmlfilepath</code> or <code>htmlurl</code> as the metakey):</p>\n\n<pre><code>add_action('wp','maybe_direct_html_output');\n\nfunction maybe_direct_html_output() {\n if (is_singular()) {\n global $post;\n $htmlfilepath = get_post_meta($post->ID,'htmlfilepath',true);\n if ( ($htmlfilepath) && (file_exists($htmlfilepath)) ) {\n echo file_get_contents($htmlfilepath); exit;\n }\n $htmlurl = get_post_meta($post->ID,'htmlurl',true);\n if ($htmlurl) {\n $html = wp_remote_get($html);\n if (!is_wp_error($html)) {echo $html['body']; exit;}\n }\n }\n}\n</code></pre>\n\n<p>So no need for <code>.htaccess</code> when doing it this way... I just noticed you want to use <code>wp-content</code> so you could just use a relative path and simplify this to (using <code>htmlfile</code> metakey):</p>\n\n<pre><code>add_action('wp','maybe_direct_html_output');\n\nfunction maybe_direct_html_output() {\n if (is_singular()) {\n global $post;\n $htmlrelpath = get_post_meta($post->ID,'htmlfile',true);\n if (!$htmlrelpath) {return;}\n $htmlfilepath = WP_CONTENT_DIR.$htmlrelpath;\n if (!file_exists($htmlfilepath)) {return;}\n echo file_get_contents($htmlrelpath); exit;\n }\n}\n</code></pre>\n\n<p>Remembering that <code>WP_CONTENT_DIR</code> has no trailing slash so you would enter a relative path custom field value for the page such as <code>/raw/book-sale.html</code></p>\n"
},
{
"answer_id": 229431,
"author": "Scott Nelle",
"author_id": 52296,
"author_profile": "https://wordpress.stackexchange.com/users/52296",
"pm_score": 1,
"selected": false,
"text": "<p>If you're willing to create a child theme and put your PHP files in there, this approach is relatively clean. For each file, create a rewrite rule where you specify the path you want to use and the filename that should load. In the example below, <code>/custom-path/</code> loads <code>custom-file.php</code> from the root of your child theme directory and <code>/custom-path-2/</code> loads <code>custom-file-2.php</code>. Don't forget to flush permalinks after adding rewrites.</p>\n\n<pre><code>/*\n * Set up a rewrite for each path which should load a file.\n */\nfunction my_standalone_rewrites() {\n add_rewrite_rule( '^custom-path/?', 'index.php?standalone=custom-file', 'top' );\n add_rewrite_rule( '^custom-path-2/?', 'index.php?standalone=custom-file-2', 'top' );\n}\nadd_action( 'init', 'my_standalone_rewrites' );\n\n/*\n * Make `standalone` available as a query var.\n */\nfunction my_query_vars( $vars ) {\n $vars[] = 'standalone';\n return $vars;\n}\nadd_filter( 'query_vars', 'my_query_vars' );\n\n/*\n * If `standalone` is set when parsing the main query, load the standalone file.\n */\nfunction my_standalone_path( &$wp_query ) {\n if ( $wp_query->is_main_query() && get_query_var( 'standalone', false ) ) {\n // Load filename.php from your child theme root.\n get_template_part( get_query_var( 'standalone' ) );\n exit;\n }\n}\nadd_action( 'parse_query', 'my_standalone_path' );\n</code></pre>\n"
},
{
"answer_id": 392644,
"author": "Krafter",
"author_id": 131780,
"author_profile": "https://wordpress.stackexchange.com/users/131780",
"pm_score": 0,
"selected": false,
"text": "<p>For anyone with similar problem, this free plugin has been around for a long time and does partly what is asked here (it doesn't work with PHP files). It lets you create custom HTML pages that bypass WordPress's templating system and they are called by custom URIs. <a href=\"https://wordpress.org/plugins/wp-custom-html-pages/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-custom-html-pages/</a></p>\n<ol>\n<li>Look for WP Custom HTML Pages plugin on the repository, install and activate</li>\n<li>Under Pages menu in admin panel look for HTML Pages menu item</li>\n<li>Create any number of pages and assign them custom URI. The pages are made by adding code into Ace editor.</li>\n</ol>\n"
}
] |
2016/06/09
|
[
"https://wordpress.stackexchange.com/questions/229209",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96471/"
] |
I have been searching around the web for this but it doesn't seems there's any topic like this (or maybe I am searching in the wrong direction).
Currently I have a jQuery file which will retrieve 9 additional posts from the database and append to the current posts listing.
**File: load-more.js**
```
var data = {
action: 'be_ajax_load_more(tv)', // <-- this is the function in functions.php
nonce: beloadmore.nonce,
page: page,
query: beloadmore.query
};
$.post(beloadmore.url, data, function(res) {
... code function to handle additional posts
}
```
**File: functions.php**
```
function be_ajax_load_more($category) {
check_ajax_referer( 'be-load-more-nonce', 'nonce' );
error_log( 'Made it into the be_ajax_load_more function');
error_log($category); // <-- this value is empty
return morePosts;
}
```
It works perfectly fine if I change both the value of data.action = 'be\_ajax\_load\_more' and function be\_ajax\_load\_more() that receives no parameter, but once I added the parameter, the .post function doesn't recognise it.
Am I passing the parameter correctly? I even tried adding a new key value into my data array:
```
var data = {
action: 'be_ajax_load_more',
category: 'tv',
nonce: beloadmore.nonce,
page: page,
query: beloadmore.query
};
```
But I am not sure how to get that data.category in my functions.php, can anyone help?
Thanks.
|
If you're willing to create a child theme and put your PHP files in there, this approach is relatively clean. For each file, create a rewrite rule where you specify the path you want to use and the filename that should load. In the example below, `/custom-path/` loads `custom-file.php` from the root of your child theme directory and `/custom-path-2/` loads `custom-file-2.php`. Don't forget to flush permalinks after adding rewrites.
```
/*
* Set up a rewrite for each path which should load a file.
*/
function my_standalone_rewrites() {
add_rewrite_rule( '^custom-path/?', 'index.php?standalone=custom-file', 'top' );
add_rewrite_rule( '^custom-path-2/?', 'index.php?standalone=custom-file-2', 'top' );
}
add_action( 'init', 'my_standalone_rewrites' );
/*
* Make `standalone` available as a query var.
*/
function my_query_vars( $vars ) {
$vars[] = 'standalone';
return $vars;
}
add_filter( 'query_vars', 'my_query_vars' );
/*
* If `standalone` is set when parsing the main query, load the standalone file.
*/
function my_standalone_path( &$wp_query ) {
if ( $wp_query->is_main_query() && get_query_var( 'standalone', false ) ) {
// Load filename.php from your child theme root.
get_template_part( get_query_var( 'standalone' ) );
exit;
}
}
add_action( 'parse_query', 'my_standalone_path' );
```
|
229,222 |
<p>I'm trying to access custom meta data from a custom post type called 'Videos'</p>
<p>The following code is on a template page called 'single-videos.php'</p>
<p>A custom field called 'Video URL', 'Video Width' and 'Video Height'</p>
<p>However when i run the script, these don't return the values for that particular post.</p>
<p>Any ideas where I might be going wrong?</p>
<pre><code><?php
/**
*Template Name: Individual Video
*/
get_header('inner');
?>
<section class="section2 portfolio">
<div class="container">
<h1 class="title-nml-individual-post text-center gal-title">
<?php
echo get_the_title($post_id);
?>
</h1>
<div class="row" style="padding-left: 50px; padding-right: 50px; padding-top: 39px;">
// *** THESE TWO SECTIONS I WAS JUST EXPERIMENTING BUT STILL
HAD NO LUCK GETTING THE VALUES I NEEDED
<?php
get_post_meta(get_the_ID());
?>
<?php
the_meta($video->ID, 'video_url', true);
?>
<iframe class="wistia_embed" src="" name="wistia_embed" width="<?php
the_meta($video->ID, 'video_width', true);
?>" height="<?php
the_meta($video->ID, 'video_height', true);
?>" frameborder="0" scrolling="no" allowfullscreen="allowfullscreen" mozallowfullscreen="mozallowfullscreen" webkitallowfullscreen="webkitallowfullscreen" oallowfullscreen="oallowfullscreen" msallowfullscreen="msallowfullscreen"></iframe>
<img class="post-feature-image" src=" <?php
the_post_thumbnail_url('full');
?> "></img>
</div> <!--end row -->
</div> <!-- end container-->
</section>
<?php
include_once('include/form.php');
?>
<?php
get_footer('inner');
?>
</code></pre>
<p><a href="https://i.stack.imgur.com/9xlov.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9xlov.png" alt="Screenshot of WP Admin"></a></p>
<p>Please let me know if there is anything else i need to provide in the way of details.</p>
|
[
{
"answer_id": 229240,
"author": "Aishan",
"author_id": 89530,
"author_profile": "https://wordpress.stackexchange.com/users/89530",
"pm_score": 0,
"selected": false,
"text": "<p>Were you showing all of your Custom Post Type \"Video\" post on a loop?</p>\n\n<p>Im not sure if your $video->ID matches with your CPT post id.</p>\n\n<p>Try Using get_the_ID() in place of $video->ID \nfor reference: <a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/get_the_id/</a></p>\n"
},
{
"answer_id": 229247,
"author": "Boris Kuzmanov",
"author_id": 68965,
"author_profile": "https://wordpress.stackexchange.com/users/68965",
"pm_score": 2,
"selected": true,
"text": "<p>I don't know why you are using a custom template for displaying an individual Video post when there is a single file that is used for this purpose - <code>single-{post_type}</code>.</p>\n\n<p><a href=\"https://codex.wordpress.org/Post_Type_Templates\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Post_Type_Templates</a></p>\n\n<p>Using the single file, you will be able to get the post ID with <code>$post->ID</code> or <code>get_the_ID()</code>.</p>\n\n<pre><code>if( have_posts() ) : while( have_posts() ) : the_post();\necho get_post_meta( $post->ID, 'video_url', true );\n// you can display all post's information within this loop\nendwhile; endif;\n</code></pre>\n\n<p>You can find more about the WordPress Template Hierarchy <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/C3kqK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/C3kqK.png\" alt=\"WordPress Template Hierarchy.\"></a></p>\n"
}
] |
2016/06/09
|
[
"https://wordpress.stackexchange.com/questions/229222",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96261/"
] |
I'm trying to access custom meta data from a custom post type called 'Videos'
The following code is on a template page called 'single-videos.php'
A custom field called 'Video URL', 'Video Width' and 'Video Height'
However when i run the script, these don't return the values for that particular post.
Any ideas where I might be going wrong?
```
<?php
/**
*Template Name: Individual Video
*/
get_header('inner');
?>
<section class="section2 portfolio">
<div class="container">
<h1 class="title-nml-individual-post text-center gal-title">
<?php
echo get_the_title($post_id);
?>
</h1>
<div class="row" style="padding-left: 50px; padding-right: 50px; padding-top: 39px;">
// *** THESE TWO SECTIONS I WAS JUST EXPERIMENTING BUT STILL
HAD NO LUCK GETTING THE VALUES I NEEDED
<?php
get_post_meta(get_the_ID());
?>
<?php
the_meta($video->ID, 'video_url', true);
?>
<iframe class="wistia_embed" src="" name="wistia_embed" width="<?php
the_meta($video->ID, 'video_width', true);
?>" height="<?php
the_meta($video->ID, 'video_height', true);
?>" frameborder="0" scrolling="no" allowfullscreen="allowfullscreen" mozallowfullscreen="mozallowfullscreen" webkitallowfullscreen="webkitallowfullscreen" oallowfullscreen="oallowfullscreen" msallowfullscreen="msallowfullscreen"></iframe>
<img class="post-feature-image" src=" <?php
the_post_thumbnail_url('full');
?> "></img>
</div> <!--end row -->
</div> <!-- end container-->
</section>
<?php
include_once('include/form.php');
?>
<?php
get_footer('inner');
?>
```
[](https://i.stack.imgur.com/9xlov.png)
Please let me know if there is anything else i need to provide in the way of details.
|
I don't know why you are using a custom template for displaying an individual Video post when there is a single file that is used for this purpose - `single-{post_type}`.
<https://codex.wordpress.org/Post_Type_Templates>
Using the single file, you will be able to get the post ID with `$post->ID` or `get_the_ID()`.
```
if( have_posts() ) : while( have_posts() ) : the_post();
echo get_post_meta( $post->ID, 'video_url', true );
// you can display all post's information within this loop
endwhile; endif;
```
You can find more about the WordPress Template Hierarchy [here](https://developer.wordpress.org/themes/basics/template-hierarchy/).
[](https://i.stack.imgur.com/C3kqK.png)
|
229,236 |
<p>I have a custom post type where I can create pages in.("article.php")<br>
It automatically uses the template "single.php" when I create a page, although I want to change some things in it without effecting some other pages on the website.<br>
I tried making a single-article.php file, but it is still using the single.php template page. Based on the documentation it should work. What could I've done wrong?</p>
|
[
{
"answer_id": 229238,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 3,
"selected": true,
"text": "<p><strong>If you want to change the single page</strong></p>\n<p><code>page-{page-slug}</code> is a good choice if you want the page template for specific page only and not multiple pages.</p>\n<p>Check out his <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/#creating-a-custom-page-template-for-one-specific-page\" rel=\"nofollow noreferrer\">custom page template for specific page</a></p>\n<p><strong>If you are talking about custom post type</strong></p>\n<p>We can use <code>single-$posttype.php</code> , here <code>$posttype</code> is your custom post type slug.</p>\n<p>WordPress template Hierarchy for single post page's custom post is in the order of :</p>\n<pre><code>single-$posttype.php ==> single.php ==> singular.php(WP 4.3+)\n</code></pre>\n<p>So if a custom post single page is requested, WP first looks for <code>single-$posttype</code> file if it's available it uses that file else it goes to <code>single.php</code> and so on as the above order.</p>\n<p>Refer to <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">Template Hierarchy</a> for more details.</p>\n"
},
{
"answer_id": 229239,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming that you are talking about a custom post type the answer is <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post\" rel=\"nofollow\">right in the codex</a>. Generate a template called <code>single-{post-type}.php</code> and WP takes care of the rest.</p>\n"
}
] |
2016/06/09
|
[
"https://wordpress.stackexchange.com/questions/229236",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96482/"
] |
I have a custom post type where I can create pages in.("article.php")
It automatically uses the template "single.php" when I create a page, although I want to change some things in it without effecting some other pages on the website.
I tried making a single-article.php file, but it is still using the single.php template page. Based on the documentation it should work. What could I've done wrong?
|
**If you want to change the single page**
`page-{page-slug}` is a good choice if you want the page template for specific page only and not multiple pages.
Check out his [custom page template for specific page](https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/#creating-a-custom-page-template-for-one-specific-page)
**If you are talking about custom post type**
We can use `single-$posttype.php` , here `$posttype` is your custom post type slug.
WordPress template Hierarchy for single post page's custom post is in the order of :
```
single-$posttype.php ==> single.php ==> singular.php(WP 4.3+)
```
So if a custom post single page is requested, WP first looks for `single-$posttype` file if it's available it uses that file else it goes to `single.php` and so on as the above order.
Refer to [Template Hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) for more details.
|
229,250 |
<p>I'am trying to make a wordpress website accessibility compliant but I have come across a problem with menu bar. It uses a modified them based on Twenty_Twelve.</p>
<p>I need to change the "ul" tag to "ol" which is required to make it compliant.
( I tried <a href="https://wordpress.stackexchange.com/questions/172582/edit-html-of-wordpress-navigation-bar">Edit HTML of Wordpress navigation bar</a> following solution but i really could not understand the walker solutions in it ).
Thank you</p>
<p>This is how the header.php file looks like : </p>
<pre><code><?php
/**
* The Header for our theme.
*
* Displays all of the <head> section and everything up till <div id="main">
*
* @package WordPress
* @subpackage Twenty_Twelve
* @since Twenty Twelve 1.0
*/
?><!DOCTYPE html>
<!--[if IE 7]>
<html class="ie ie7" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 8]>
<html class="ie ie8" <?php language_attributes(); ?>>
<![endif]-->
<!--[if !(IE 7) | !(IE 8) ]><!-->
<html <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php wp_title( '|', true, 'right' ); ?></title>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<?php // Loads HTML5 JavaScript file to add support for HTML5 elements in older IE versions. ?>
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js" type="text/javascript"></script>
<![endif]-->
<?php wp_head(); ?>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-57162369-1', 'auto');
ga('send', 'pageview');
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
// DOM ready
$(function() {
// Create the dropdown base
$("<select />").appendTo("nav");
// Create default option "Go to..."
$("<option />", {
"selected": "selected",
"value" : "",
"text" : "Menu"
}).appendTo("nav select");
// Populate dropdown with menu items
$("nav a").each(function() {
var el = $(this);
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo("nav select");
});
// To make dropdown actually work
// To make more unobtrusive: http://css-tricks.com/4064-unobtrusive-page-changer/
$("nav select").change(function() {
window.location = $(this).find("option:selected").val();
});
});
</script>
</head>
<body <?php body_class(); ?>>
<div id="page" class="hfeed site">
<div id="masthead" class="site-header" >
<div class="logo">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home">
<img src="<?php echo get_template_directory_uri(); ?>/images/logo.png" alt="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" />
</a>
</div>
<div class="nav-right">
<div class="header-call"><a href="/contact-us/">Call us today on <span>02 6247 3611</span></a></div>
<nav id="site-navigation" class="main-navigation" >
<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu' ) ); ?>
</nav><!-- #site-navigation -->
<nav id="site-navigation2" class="main-navigation2" role="navigation">
<?php wp_nav_menu( array( 'theme_location' => 'secondary', 'menu_class' => 'nav-menu' ) ); ?>
</nav><!-- #site-navigation -->
</div>
</div><!-- #masthead -->
<div id="main" class="wrapper">
</code></pre>
|
[
{
"answer_id": 229238,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 3,
"selected": true,
"text": "<p><strong>If you want to change the single page</strong></p>\n<p><code>page-{page-slug}</code> is a good choice if you want the page template for specific page only and not multiple pages.</p>\n<p>Check out his <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/#creating-a-custom-page-template-for-one-specific-page\" rel=\"nofollow noreferrer\">custom page template for specific page</a></p>\n<p><strong>If you are talking about custom post type</strong></p>\n<p>We can use <code>single-$posttype.php</code> , here <code>$posttype</code> is your custom post type slug.</p>\n<p>WordPress template Hierarchy for single post page's custom post is in the order of :</p>\n<pre><code>single-$posttype.php ==> single.php ==> singular.php(WP 4.3+)\n</code></pre>\n<p>So if a custom post single page is requested, WP first looks for <code>single-$posttype</code> file if it's available it uses that file else it goes to <code>single.php</code> and so on as the above order.</p>\n<p>Refer to <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">Template Hierarchy</a> for more details.</p>\n"
},
{
"answer_id": 229239,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming that you are talking about a custom post type the answer is <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post\" rel=\"nofollow\">right in the codex</a>. Generate a template called <code>single-{post-type}.php</code> and WP takes care of the rest.</p>\n"
}
] |
2016/06/09
|
[
"https://wordpress.stackexchange.com/questions/229250",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96492/"
] |
I'am trying to make a wordpress website accessibility compliant but I have come across a problem with menu bar. It uses a modified them based on Twenty\_Twelve.
I need to change the "ul" tag to "ol" which is required to make it compliant.
( I tried [Edit HTML of Wordpress navigation bar](https://wordpress.stackexchange.com/questions/172582/edit-html-of-wordpress-navigation-bar) following solution but i really could not understand the walker solutions in it ).
Thank you
This is how the header.php file looks like :
```
<?php
/**
* The Header for our theme.
*
* Displays all of the <head> section and everything up till <div id="main">
*
* @package WordPress
* @subpackage Twenty_Twelve
* @since Twenty Twelve 1.0
*/
?><!DOCTYPE html>
<!--[if IE 7]>
<html class="ie ie7" <?php language_attributes(); ?>>
<![endif]-->
<!--[if IE 8]>
<html class="ie ie8" <?php language_attributes(); ?>>
<![endif]-->
<!--[if !(IE 7) | !(IE 8) ]><!-->
<html <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php wp_title( '|', true, 'right' ); ?></title>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<?php // Loads HTML5 JavaScript file to add support for HTML5 elements in older IE versions. ?>
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js" type="text/javascript"></script>
<![endif]-->
<?php wp_head(); ?>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-57162369-1', 'auto');
ga('send', 'pageview');
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
// DOM ready
$(function() {
// Create the dropdown base
$("<select />").appendTo("nav");
// Create default option "Go to..."
$("<option />", {
"selected": "selected",
"value" : "",
"text" : "Menu"
}).appendTo("nav select");
// Populate dropdown with menu items
$("nav a").each(function() {
var el = $(this);
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo("nav select");
});
// To make dropdown actually work
// To make more unobtrusive: http://css-tricks.com/4064-unobtrusive-page-changer/
$("nav select").change(function() {
window.location = $(this).find("option:selected").val();
});
});
</script>
</head>
<body <?php body_class(); ?>>
<div id="page" class="hfeed site">
<div id="masthead" class="site-header" >
<div class="logo">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home">
<img src="<?php echo get_template_directory_uri(); ?>/images/logo.png" alt="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" />
</a>
</div>
<div class="nav-right">
<div class="header-call"><a href="/contact-us/">Call us today on <span>02 6247 3611</span></a></div>
<nav id="site-navigation" class="main-navigation" >
<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu' ) ); ?>
</nav><!-- #site-navigation -->
<nav id="site-navigation2" class="main-navigation2" role="navigation">
<?php wp_nav_menu( array( 'theme_location' => 'secondary', 'menu_class' => 'nav-menu' ) ); ?>
</nav><!-- #site-navigation -->
</div>
</div><!-- #masthead -->
<div id="main" class="wrapper">
```
|
**If you want to change the single page**
`page-{page-slug}` is a good choice if you want the page template for specific page only and not multiple pages.
Check out his [custom page template for specific page](https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/#creating-a-custom-page-template-for-one-specific-page)
**If you are talking about custom post type**
We can use `single-$posttype.php` , here `$posttype` is your custom post type slug.
WordPress template Hierarchy for single post page's custom post is in the order of :
```
single-$posttype.php ==> single.php ==> singular.php(WP 4.3+)
```
So if a custom post single page is requested, WP first looks for `single-$posttype` file if it's available it uses that file else it goes to `single.php` and so on as the above order.
Refer to [Template Hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) for more details.
|
229,256 |
<p>When I write a quote in the text widget and displayed the text is wrapped as "My text...". I would like to remove the div and put simply "My text...". without using jquery.</p>
<p>For Example: Current output</p>
<pre><code><div class="container">
<div class=“textwidget”>
My text...
</div>
</div>
</code></pre>
<p>Required output:</p>
<pre><code><div class="container">
My text...
</div>
</code></pre>
<p>This is the actual code:</p>
<pre><code><div class="container">
<?php dynamic_sidebar('text_show');?>
</div>
</code></pre>
|
[
{
"answer_id": 229259,
"author": "Greg McMullen",
"author_id": 36028,
"author_profile": "https://wordpress.stackexchange.com/users/36028",
"pm_score": 3,
"selected": true,
"text": "<p>More than likely this is an issue with the <a href=\"https://codex.wordpress.org/Function_Reference/register_sidebars\" rel=\"nofollow\"><code>register_sidebar()</code></a> call in <code>functions.php</code>.</p>\n\n<p>Look for <code>before_widget</code> and <code>after_widget</code>. The code below is the default usage.</p>\n\n<pre><code>'before_widget' => '<li id=\"%1$s\" class=\"widget %2$s\">',\n'after_widget' => '</li>',\n</code></pre>\n\n<p><strong>Note:</strong> This will alter all of the widgets within the sidebar, not just the TextWidget.</p>\n"
},
{
"answer_id": 229263,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>What you want is probably better to do with css by applying a <code>display:inline;</code> style to the specific widget. something like</p>\n\n<pre><code>#id.textwidget {\n display:inline;\n}\n</code></pre>\n\n<p>Where \"id\" is the id attribute of the widget. If you don't have one you should change your sidebar registration code to create one.</p>\n\n<p>I don't think it is very likely that you will want such a behaviour on all your text widgets.</p>\n"
}
] |
2016/06/09
|
[
"https://wordpress.stackexchange.com/questions/229256",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96491/"
] |
When I write a quote in the text widget and displayed the text is wrapped as "My text...". I would like to remove the div and put simply "My text...". without using jquery.
For Example: Current output
```
<div class="container">
<div class=“textwidget”>
My text...
</div>
</div>
```
Required output:
```
<div class="container">
My text...
</div>
```
This is the actual code:
```
<div class="container">
<?php dynamic_sidebar('text_show');?>
</div>
```
|
More than likely this is an issue with the [`register_sidebar()`](https://codex.wordpress.org/Function_Reference/register_sidebars) call in `functions.php`.
Look for `before_widget` and `after_widget`. The code below is the default usage.
```
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
```
**Note:** This will alter all of the widgets within the sidebar, not just the TextWidget.
|
229,310 |
<p>I need to iframe a series of content on our site. I need to pass on the the user information via a URL - vendor request.</p>
<p>I have tons of shortcodes that display the username. It works fine. But when I append the src record it doesn't work.</p>
<pre><code><iframe src="https://test.com/video/112/[currentuser_username]" width="800" height="450">
<p>Your browser does not support iframes.</p>
</iframe>
</code></pre>
<blockquote>
<p>This should display:</p>
<p><a href="https://test.com/video/112/user123" rel="nofollow">https://test.com/video/112/user123</a></p>
<p>but of course it displays...</p>
<p><a href="https://test.com/video/112/[currentuser_username]" rel="nofollow">https://test.com/video/112/[currentuser_username]</a></p>
</blockquote>
<p>I know of ways I can do this via templating and in php. Would like a way to do this inside the html editor so that our authors have more flexibility. Am I just having a brain fart or is it that complicated?</p>
|
[
{
"answer_id": 229325,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Don't remember exactly when (4.3?) core had gone with a much more restrictive parsing of shortcodes due to many security problems that the lax parsing with combination of poorly implemented shortcodes had created. The end result is that you can not use a shortcode in an attribute.</p>\n\n<p>The right solution is to have a shortcode that produces the whole iframe. Partial kinds of shortcodes are never a great idea as in most cases, they are not easy to understand and too easy to break with some accidental input.</p>\n"
},
{
"answer_id": 230662,
"author": "STing",
"author_id": 32393,
"author_profile": "https://wordpress.stackexchange.com/users/32393",
"pm_score": 1,
"selected": true,
"text": "<pre><code><iframe src=https://test.com/video/112/[currentuser_username] width=\"800\" height=\"450\">\n <p>Your browser does not support iframes.</p>\n</iframe>\n</code></pre>\n\n<p>Simply removing the quotes around everything worked. All modern browsers add these back in - when that stops working (doubt anytime soon) we might have to create some advanced shortcode but this leaves us more options right now.</p>\n"
}
] |
2016/06/09
|
[
"https://wordpress.stackexchange.com/questions/229310",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32393/"
] |
I need to iframe a series of content on our site. I need to pass on the the user information via a URL - vendor request.
I have tons of shortcodes that display the username. It works fine. But when I append the src record it doesn't work.
```
<iframe src="https://test.com/video/112/[currentuser_username]" width="800" height="450">
<p>Your browser does not support iframes.</p>
</iframe>
```
>
> This should display:
>
>
> <https://test.com/video/112/user123>
>
>
> but of course it displays...
>
>
> <https://test.com/video/112/[currentuser_username]>
>
>
>
I know of ways I can do this via templating and in php. Would like a way to do this inside the html editor so that our authors have more flexibility. Am I just having a brain fart or is it that complicated?
|
```
<iframe src=https://test.com/video/112/[currentuser_username] width="800" height="450">
<p>Your browser does not support iframes.</p>
</iframe>
```
Simply removing the quotes around everything worked. All modern browsers add these back in - when that stops working (doubt anytime soon) we might have to create some advanced shortcode but this leaves us more options right now.
|
229,337 |
<p>I very much like <a href="https://en.wikipedia.org/wiki/This_will_be_a_new_Site" rel="nofollow noreferrer">Wikipedia's feature</a> to create an article from a yet non-existing URL as shown below:</p>
<p><a href="https://i.stack.imgur.com/a4tJI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a4tJI.png" alt="enter image description here"></a></p>
<p>I imagine the workflow to be like this:</p>
<ol>
<li>Open URL of the site you wish to create</li>
<li>If logged in, a button allows you to create the page with exactly this URL slug by forwarding you to the WP-Admin</li>
<li>If not logged in, you would only see a 404 error.</li>
</ol>
<p>How would I begin building a plugin for this?</p>
|
[
{
"answer_id": 229386,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": true,
"text": "<p>Somehow the url must make clear that this is an editable link. So you need a filter on <code>the_content</code> that checks if there are internal links that do not yet exist. Alternatively, if you let users determine which links are editable you need to check if the url's they give perhaps already exist. The filter should set a class on the link. Here's a function to determine if a slug already exists:</p>\n\n<pre><code>function the_slug_exists($post_name) {\n global $wpdb;\n if($wpdb->get_row(\"SELECT post_name FROM wp_posts WHERE post_name = '\" . $post_name . \"'\", 'ARRAY_A')) {\n return true;\n } else {\n return false;\n }\n }\n</code></pre>\n\n<p>Now you get a page with links, some of which have the class <code>editable</code>. You can bind a javascript function to this class, which prevents normal link behaviour. You could even use it to hide the link completely for users who are not logged in. Logged in users get a little popup thats asks them if they want to create the page for the link.</p>\n\n<p>The 'yes' button in the popup does not lead people to the url. Rather it takes the slug and adds it as a query variable to the new posts page: <code>http://www.example.com/wp-admin/post-new.php?slug=yournewpostslug</code>.</p>\n\n<p>In your <code>functions.php</code> you add an action to <code>wp_insert_post</code> to catch the query variable and use it to fill fields in the editor. Read more about that method <a href=\"https://wordpress.stackexchange.com/questions/77504/how-to-add-category-to-wp-admin-post-new-php\">in @toscho 's anwer here</a>. Beware that editors at this point may still change the slug, so you may want to remove that box in this case using <a href=\"https://codex.wordpress.org/Function_Reference/remove_meta_box\" rel=\"nofollow noreferrer\"><code>remove_meta_box</code></a></p>\n"
},
{
"answer_id": 229419,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 2,
"selected": false,
"text": "<p>I'd put an is_user_logged_in conditional into my theme's 404.php. Then for logged in users show a form with the new slug as a hidden or uneditable field that creates a new page and redirects to the admin edit screen for that page. </p>\n"
}
] |
2016/06/10
|
[
"https://wordpress.stackexchange.com/questions/229337",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75760/"
] |
I very much like [Wikipedia's feature](https://en.wikipedia.org/wiki/This_will_be_a_new_Site) to create an article from a yet non-existing URL as shown below:
[](https://i.stack.imgur.com/a4tJI.png)
I imagine the workflow to be like this:
1. Open URL of the site you wish to create
2. If logged in, a button allows you to create the page with exactly this URL slug by forwarding you to the WP-Admin
3. If not logged in, you would only see a 404 error.
How would I begin building a plugin for this?
|
Somehow the url must make clear that this is an editable link. So you need a filter on `the_content` that checks if there are internal links that do not yet exist. Alternatively, if you let users determine which links are editable you need to check if the url's they give perhaps already exist. The filter should set a class on the link. Here's a function to determine if a slug already exists:
```
function the_slug_exists($post_name) {
global $wpdb;
if($wpdb->get_row("SELECT post_name FROM wp_posts WHERE post_name = '" . $post_name . "'", 'ARRAY_A')) {
return true;
} else {
return false;
}
}
```
Now you get a page with links, some of which have the class `editable`. You can bind a javascript function to this class, which prevents normal link behaviour. You could even use it to hide the link completely for users who are not logged in. Logged in users get a little popup thats asks them if they want to create the page for the link.
The 'yes' button in the popup does not lead people to the url. Rather it takes the slug and adds it as a query variable to the new posts page: `http://www.example.com/wp-admin/post-new.php?slug=yournewpostslug`.
In your `functions.php` you add an action to `wp_insert_post` to catch the query variable and use it to fill fields in the editor. Read more about that method [in @toscho 's anwer here](https://wordpress.stackexchange.com/questions/77504/how-to-add-category-to-wp-admin-post-new-php). Beware that editors at this point may still change the slug, so you may want to remove that box in this case using [`remove_meta_box`](https://codex.wordpress.org/Function_Reference/remove_meta_box)
|
229,352 |
<p>I need to build a website for a client where the can password protect certain pages and posts on the front end. So, a visitor is required to enter a password on these pages / posts.</p>
<p>Having searched and tried out a couple of plugins 'password protected' and 'smart passworded pages' without much success. </p>
<p>I was wondering if there is a way to set the wordpress built in password protect password globally. So the client only has to select if they want the page / post protected and not have to enter the password each time... which is not an option here.</p>
<p>Also, as they will be changing the password each term being able to do so from a single place would be great!</p>
<p>If anyone can point me in the right direction that would be a great help.</p>
<p>Many thanks</p>
|
[
{
"answer_id": 229357,
"author": "rémy",
"author_id": 92681,
"author_profile": "https://wordpress.stackexchange.com/users/92681",
"pm_score": -1,
"selected": false,
"text": "<p>You could create a template, which then should be choosen for protected sites. There you just copy the default template, and add a custom login check:</p>\n\n<pre><code><?php if ( !is_user_logged_in() ) :\n if ( 'failed' == get_query_var( 'login', '' ) ) :\n <h2 class=\"red\">Wrong credentials !</h2>\n endif;\n wp_login_form( $args );\nelse:\n the_content();\nendif; ?>\n</code></pre>\n\n<p>Needs some more for error handling etc ... You can see a reference for the $args <a href=\"https://codex.wordpress.org/Function_Reference/wp_login_form\" rel=\"nofollow\">here</a>.</p>\n\n<p>And add this to funcitons.php for your custom query var:</p>\n\n<pre><code>function my_front_end_login_fail( $username ) {\n $referrer = wp_get_referer();\n if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') ) {\n if (!strstr($referrer,'?login=failed')) {\n $referrer .= '?login=failed';\n }\n wp_redirect( $referrer );\n exit;\n }\n}\nadd_action( 'wp_login_failed', 'my_front_end_login_fail' );\n\nfunction add_query_vars_filter( $vars ){\n $vars[] = 'login';\n return $vars;\n}\nadd_filter( 'query_vars', 'add_query_vars_filter' );\n</code></pre>\n\n<p><strong>And, this would require, that you create a general user, which could be used to login.</strong></p>\n\n<blockquote>\n <p>You could also go with post_password_required() instead of\n user_is_logged_in().</p>\n</blockquote>\n"
},
{
"answer_id": 229370,
"author": "dg4220",
"author_id": 91201,
"author_profile": "https://wordpress.stackexchange.com/users/91201",
"pm_score": 0,
"selected": false,
"text": "<p>I've used the following to protect individual pages:\nFirst add a field to the Publish Metabox:</p>\n\n<pre><code>add_action( 'post_submitbox_misc_actions', 'my_post_submitbox_misc_actions1' );\n\nfunction my_post_submitbox_misc_actions1(){\n\n echo '<div class=\"misc-pub-section my-options\">\n <input type=\"checkbox\" id=\"fgpsn_protected_content\" name=\"fgpsn_protected_content\" value=\"true\"';\n\n if ( get_post_meta(get_the_ID(), 'fgpsn_protected_content', true) == 'true' ){ echo ' checked'; }\n echo '>\n <label for=\"fgpsn_protected_content\">FGPSN Content</label></div>';\n\n}\n</code></pre>\n\n<p>Then save the meta data - the one flaw currently is that the post must be save first. Then you can check and save the box.</p>\n\n<pre><code>add_action( 'save_post', 'fgpsn_protect_content_save' );\nfunction fgpsn_protect_content_save($post_id)\n {\n\n if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )\n return;\n\n if ( 'page' == $_POST['post_type'] ) {\n if ( !current_user_can( 'edit_page', $post_id ) )\n return;\n } else {\n if ( !current_user_can( 'edit_post', $post_id ) )\n return;\n }\n\n /* check if the custom field is submitted (checkboxes that aren't marked, aren't submitted) */\n if(isset($_POST['fgpsn_protected_content'])){\n\n update_post_meta($post_id, 'fgpsn_protected_content', $_POST['fgpsn_protected_content']);\n //add_post_meta($postid, 'fgpsn_update_zillow_feed_result', 1, true );\n }\n else{\n\n update_post_meta($post_id, 'fgpsn_protected_content', 'false');\n }\n\n }\n</code></pre>\n\n<p>Finally, add the check:</p>\n\n<pre><code>add_action( 'get_header', 'site_access_filter' );\nfunction site_access_filter() {\n\n if ( get_post_meta(get_the_ID(), 'fgpsn_protected_content', true) == 'true' && is_user_logged_in() === false ) {\n wp_redirect( 'http://fgpsn.com/login' ); exit;\n\n } \n\n}\n</code></pre>\n\n<p>Obviously, I redirect users to the login page but you could manage this anyway you want from here. </p>\n"
}
] |
2016/06/10
|
[
"https://wordpress.stackexchange.com/questions/229352",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96549/"
] |
I need to build a website for a client where the can password protect certain pages and posts on the front end. So, a visitor is required to enter a password on these pages / posts.
Having searched and tried out a couple of plugins 'password protected' and 'smart passworded pages' without much success.
I was wondering if there is a way to set the wordpress built in password protect password globally. So the client only has to select if they want the page / post protected and not have to enter the password each time... which is not an option here.
Also, as they will be changing the password each term being able to do so from a single place would be great!
If anyone can point me in the right direction that would be a great help.
Many thanks
|
I've used the following to protect individual pages:
First add a field to the Publish Metabox:
```
add_action( 'post_submitbox_misc_actions', 'my_post_submitbox_misc_actions1' );
function my_post_submitbox_misc_actions1(){
echo '<div class="misc-pub-section my-options">
<input type="checkbox" id="fgpsn_protected_content" name="fgpsn_protected_content" value="true"';
if ( get_post_meta(get_the_ID(), 'fgpsn_protected_content', true) == 'true' ){ echo ' checked'; }
echo '>
<label for="fgpsn_protected_content">FGPSN Content</label></div>';
}
```
Then save the meta data - the one flaw currently is that the post must be save first. Then you can check and save the box.
```
add_action( 'save_post', 'fgpsn_protect_content_save' );
function fgpsn_protect_content_save($post_id)
{
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ) )
return;
} else {
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
/* check if the custom field is submitted (checkboxes that aren't marked, aren't submitted) */
if(isset($_POST['fgpsn_protected_content'])){
update_post_meta($post_id, 'fgpsn_protected_content', $_POST['fgpsn_protected_content']);
//add_post_meta($postid, 'fgpsn_update_zillow_feed_result', 1, true );
}
else{
update_post_meta($post_id, 'fgpsn_protected_content', 'false');
}
}
```
Finally, add the check:
```
add_action( 'get_header', 'site_access_filter' );
function site_access_filter() {
if ( get_post_meta(get_the_ID(), 'fgpsn_protected_content', true) == 'true' && is_user_logged_in() === false ) {
wp_redirect( 'http://fgpsn.com/login' ); exit;
}
}
```
Obviously, I redirect users to the login page but you could manage this anyway you want from here.
|
229,355 |
<p><code>wp_title()</code> from theme's <code>header.php</code> shows "Page not found". Also the <code>body_class</code> displays the word "error404". </p>
<ul>
<li>the WP blog is installed on site.com/blog/</li>
<li>a post is rendered outside WP installation, more specific on wildcard-subdomain.site.com/articles/post-slug</li>
</ul>
<p>I added on page:</p>
<pre><code>define('WP_USE_THEMES', false);
require( ROOT_DIR . '/blog/wp-blog-header.php');
</code></pre>
<ul>
<li>i added <code>get_header()</code>, <code>get_footer()</code> and it works fine</li>
<li>in the theme's <code>functions.php</code> file I added <code>add_theme_support( 'title-tag' );</code></li>
<li>The hooks work fine, also plugins are loading</li>
</ul>
<p>Why doesn't the post title display?</p>
|
[
{
"answer_id": 229388,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>To be able to show the title and have a proper body_class, wordpress has to parse first the url and find out what type of page is being referenced in geenral and which specific page it is. You can setup the <code>$_SERVER</code> variable with url data that will make sense for wordpress.</p>\n\n<p>.... or do an explicit query to set everything as in @dan's answer</p>\n"
},
{
"answer_id": 229392,
"author": "Dan Kinchen",
"author_id": 65580,
"author_profile": "https://wordpress.stackexchange.com/users/65580",
"pm_score": 1,
"selected": false,
"text": "<p>You could do an outside query instead.</p>\n\n<pre><code><?php\ndefine('WP_USE_THEMES', false);\nglobal $wpdb;\nrequire(ROOT_DIR.'/blog/wp-load.php');\nquery_posts('showposts=1');\n\nget_header();\n\ntry{\n $args = array('post_type' => array('post'), 'posts_per_page' => -1);\n $qry = null;\n $qry = new WP_Query($args);\n if($qry->have_posts()){\n while($qry->have_posts()){\n $qry->the_post();\n $theTitle = get_the_title();\n print $theTitle.'<br>';\n }\n wp_reset_query();\n }else{\n print 'no records found';\n }\n}catch(Exception $e){\n print $e->getMessage();\n}\n\nget_footer();\n?>\n</code></pre>\n"
}
] |
2016/06/10
|
[
"https://wordpress.stackexchange.com/questions/229355",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69275/"
] |
`wp_title()` from theme's `header.php` shows "Page not found". Also the `body_class` displays the word "error404".
* the WP blog is installed on site.com/blog/
* a post is rendered outside WP installation, more specific on wildcard-subdomain.site.com/articles/post-slug
I added on page:
```
define('WP_USE_THEMES', false);
require( ROOT_DIR . '/blog/wp-blog-header.php');
```
* i added `get_header()`, `get_footer()` and it works fine
* in the theme's `functions.php` file I added `add_theme_support( 'title-tag' );`
* The hooks work fine, also plugins are loading
Why doesn't the post title display?
|
You could do an outside query instead.
```
<?php
define('WP_USE_THEMES', false);
global $wpdb;
require(ROOT_DIR.'/blog/wp-load.php');
query_posts('showposts=1');
get_header();
try{
$args = array('post_type' => array('post'), 'posts_per_page' => -1);
$qry = null;
$qry = new WP_Query($args);
if($qry->have_posts()){
while($qry->have_posts()){
$qry->the_post();
$theTitle = get_the_title();
print $theTitle.'<br>';
}
wp_reset_query();
}else{
print 'no records found';
}
}catch(Exception $e){
print $e->getMessage();
}
get_footer();
?>
```
|
229,390 |
<p>I have set-up my first VPS (Ubuntu). Apache 2 and php were pre-installed, I was able to install wp-cli, but it is kinda useless for me know. I am getting user permissions error. For example when I run </p>
<pre><code>wp core download
</code></pre>
<p>I am getting an error</p>
<pre><code>Error: /var/www/example.com/public_html/ is not writable by current user
</code></pre>
<p>I am using user which is member of <code>root</code> group and I have also tried to add user into a <code>www-data</code> group. The folder <code>public_html</code> is own by <code>www-data:www-data</code> (default Apache settings).</p>
<p>I know that this might be more Ubuntu than Wordpress issue, but I though this is still better place to ask the question than AskUbuntu.com. If I am wrong, I don't mind moving this question.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 229395,
"author": "user3865184",
"author_id": 59612,
"author_profile": "https://wordpress.stackexchange.com/users/59612",
"pm_score": 1,
"selected": false,
"text": "<p>I think the error is very clear. The owner of <code>public_html</code> is <code>www-data</code>, you don't have any permisson to write to that folder.</p>\n\n<p>You can use whatever user you want as long as that user have permission to read, write and execute your <code>DOCUMENT_ROOT</code> folder. But you shouldn't use <code>root</code> user.</p>\n\n<p>So, to solve that error, try:</p>\n\n<pre><code>sudo chown -R `whoami`:www-data /var/www/example.com/public_html\n</code></pre>\n\n<p>That's all ;-)</p>\n"
},
{
"answer_id": 229404,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 0,
"selected": false,
"text": "<p>If the file owner is allowed to run a shell I find that su-ing to that user works fine. I'm running suPHP so each site has its own user which can login. I don't know if the default Apache user is more restricted. </p>\n\n<p>I wouldn't follow the advice to chown the files as your web server might then choke. </p>\n"
}
] |
2016/06/10
|
[
"https://wordpress.stackexchange.com/questions/229390",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67602/"
] |
I have set-up my first VPS (Ubuntu). Apache 2 and php were pre-installed, I was able to install wp-cli, but it is kinda useless for me know. I am getting user permissions error. For example when I run
```
wp core download
```
I am getting an error
```
Error: /var/www/example.com/public_html/ is not writable by current user
```
I am using user which is member of `root` group and I have also tried to add user into a `www-data` group. The folder `public_html` is own by `www-data:www-data` (default Apache settings).
I know that this might be more Ubuntu than Wordpress issue, but I though this is still better place to ask the question than AskUbuntu.com. If I am wrong, I don't mind moving this question.
Thanks.
|
I think the error is very clear. The owner of `public_html` is `www-data`, you don't have any permisson to write to that folder.
You can use whatever user you want as long as that user have permission to read, write and execute your `DOCUMENT_ROOT` folder. But you shouldn't use `root` user.
So, to solve that error, try:
```
sudo chown -R `whoami`:www-data /var/www/example.com/public_html
```
That's all ;-)
|
229,394 |
<p>My issue was the adminbar started to disappear for users who weren't the administrator. I have found a work-around ( below code ) that checks if they're logged in just before the closing <code></head></code> tag.</p>
<p>Has anyone come across a similar problem and found the root cause, or is there a better-practice way of hiding the adminbar?</p>
<pre><code><?php
if ( is_user_logged_in() ) {
show_admin_bar( true );
}
elseif ( ! is_user_logged_in() ) {
show_admin_bar( false );
}
?>
</head>
<body <?php body_class(); ?>>
</code></pre>
|
[
{
"answer_id": 229397,
"author": "Dan Kinchen",
"author_id": 65580,
"author_profile": "https://wordpress.stackexchange.com/users/65580",
"pm_score": 0,
"selected": false,
"text": "<p>I have 2 choices for you. Both of which you place this code in your theme's function.php file.</p>\n\n<pre><code>// Disable WordPress Admin Bar for all users but admins.\nadd_action('after_setup_theme', 'remove_admin_bar');\nfunction remove_admin_bar(){\n if(!current_user_can('administrator') && !is_admin()){\n show_admin_bar(false);\n }\n}\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>// Hide admin bar from all users\nshow_admin_bar(false);\n</code></pre>\n"
},
{
"answer_id": 229407,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 1,
"selected": false,
"text": "<p>There's actually a <a href=\"https://codex.wordpress.org/Function_Reference/show_admin_bar\" rel=\"nofollow\"><code>show_admin_bar</code></a> hook where you can always return true or false. I haven't run across an issue where the admin bar is randomly disappearing though. Usually on my websites I like to turn it off for admins:</p>\n\n<pre><code>/**\n * Remove Admin Bar For Administrators\n * Or anyone who can activate plugins\n */\nfunction theme_hide_admin_bar() {\n return ( is_user_logged_in() && ! current_user_can( 'activate_plugins' ) ); // returns true or false\n}\nadd_filter( 'show_admin_bar', 'theme_hide_admin_bar' );\n</code></pre>\n\n<p>OR you can permanently turn it off by just adding the following:</p>\n\n<pre><code>add_filter( 'show_admin_bar', '__return_false' );\n</code></pre>\n\n<p>Always show the admin bar:</p>\n\n<pre><code>add_filter( 'show_admin_bar', '__return_true' );\n</code></pre>\n"
}
] |
2016/06/10
|
[
"https://wordpress.stackexchange.com/questions/229394",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96571/"
] |
My issue was the adminbar started to disappear for users who weren't the administrator. I have found a work-around ( below code ) that checks if they're logged in just before the closing `</head>` tag.
Has anyone come across a similar problem and found the root cause, or is there a better-practice way of hiding the adminbar?
```
<?php
if ( is_user_logged_in() ) {
show_admin_bar( true );
}
elseif ( ! is_user_logged_in() ) {
show_admin_bar( false );
}
?>
</head>
<body <?php body_class(); ?>>
```
|
There's actually a [`show_admin_bar`](https://codex.wordpress.org/Function_Reference/show_admin_bar) hook where you can always return true or false. I haven't run across an issue where the admin bar is randomly disappearing though. Usually on my websites I like to turn it off for admins:
```
/**
* Remove Admin Bar For Administrators
* Or anyone who can activate plugins
*/
function theme_hide_admin_bar() {
return ( is_user_logged_in() && ! current_user_can( 'activate_plugins' ) ); // returns true or false
}
add_filter( 'show_admin_bar', 'theme_hide_admin_bar' );
```
OR you can permanently turn it off by just adding the following:
```
add_filter( 'show_admin_bar', '__return_false' );
```
Always show the admin bar:
```
add_filter( 'show_admin_bar', '__return_true' );
```
|
229,432 |
<p>Is it possible to load scripts through <code>wp_enqueue_script</code> based on a browser's width?</p>
<p>Thanks</p>
|
[
{
"answer_id": 229435,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>No it isn't. Server can not know browser width. Not sure it is even a smart idea since the width of the browser can change at any point.</p>\n"
},
{
"answer_id": 229441,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 0,
"selected": false,
"text": "<p>As @Mark Kaplan correctly points out, the right answer to this clear question is <strong>No</strong>.</p>\n\n<p>What you <em>can</em> do, and maybe asking on Stackoverflow will get a better answer, is run scripts in response to certain browser sizes and also detect when the window is resized if that is also important to you. This isn't without its problems, but these are JS issues, not WP issues, so I won't go into that here.</p>\n\n<p>You could put a script loader into the mix if it's important to you that a script is only downloaded for certain window or screen sizes.</p>\n\n<p>If you're worried about performance then these things are a balancing act and you may find other types of optimisations are more helpful.</p>\n"
},
{
"answer_id": 229451,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 2,
"selected": true,
"text": "<p>Kinda just answering this to counter the \"not-possible\" answers... </p>\n\n<p>Yes it is probably not the best thing to do, since we are still unsure what the OP is trying to achieve, but that does not make it not possible... complex and impractical perhaps, but still entirely possible.</p>\n\n<p>First enqueue the script as you normally would... here setting the minimum and/or maximum screen widths to load for as well:</p>\n\n<pre><code>add_action('wp_enqueue_scripts','enqueue_screen_size_script');\nfunction enqueue_screen_size_script() {\n global $screensizescripturl, $screenminwidth, $screenmaxwidth;\n\n // set one or the other or both of these\n $screenminwidth = '319'; $screenmaxwidth = '769'; \n\n $screensizescripturl = get_stylesheet_directory_uri().'/screen-size.js';\n\n wp_enqueue_script('screen-size',$screensizescripturl,array('jquery'));\n}\n</code></pre>\n\n<p>Then you can filter the enqueue using the <code>script_loader_tag</code> filter, and add some magical javascript to conditionally load the script inside itself:</p>\n\n<pre><code>add_filter('script_loader_tag','enqueue_for_screen_size', 10, 2);\nfunction enqueue_for_screen_size($tag, $handle) {\n global $screensizescripturl, $screenminwidth, $screenmaxwidth;\n\n if ($handle == 'screen-size') {\n\n // this would get the src url dynamically, but using global instead\n // $scripturl = substr($tag,(strpos($tag,'src=\"')+5),strlen($tag));\n // $scripturl = substr($scripturl,0,strpos($tag,'\"'));\n\n $conditionaltag = \"if (window.jQuery) {x = jQuery(window).width();}\n else {x = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;} \";\n\n if ( ($screenminwidth) && ($screenmaxwidth) ) {\n $conditionaltag .= \"if ( (x > \".$screenminwidth.\") && (x < \".$screenmaxwidth.\") ) {\";\n }\n elseif ($screenminwidth) {$conditionaltag .= \"if (x > \".$screenminwidth.\") {\";}\n elseif ($screenmaxwidth) {$conditionaltag .= \"if (x < \".$screenmaxwidth.\") {\";}\n\n $conditionaltag .= \" document.write(unescape('%3Cscript id=\\\"screen-size-script\\\" src=\\\"\".$scripturl.\"\\\"%3E%3C\\/script%3E')); }</script>\";\n\n $tag = str_replace('src=\"'.$scripturl.'\"','',$tag);\n $tag = str_replace('</script>',$conditionaltag, $tag);\n }\n\n return $tag;\n}\n</code></pre>\n\n<p>So then, the point of responsiveness being responsive, you would probably need a window resize function to dynamically load the script if it fits your chosen specifications after resize... with a debounce thrown in for good measure.</p>\n\n<pre><code>add_action('wp_footer','screen_resizer_check');\n function screen_resizer_check() {\n global $screensizescripturl, $screenminwidth, $screenmaxwidth;\n\n // note: debounce window resize function from here:\n // http://stackoverflow.com/questions/2854407/javascript-jquery-window-resize-how-to-fire-after-the-resize-is-completed\n\n echo \"<script>jQuery(document).ready(function($) {\n\n function loadscreensizescript() {\n x = jQuery(window).width();\n \";\n\n if ( ($screenminwidth) && ($screenmaxwidth) ) {\n echo \"if ( (x > \".$screenminwidth.\") && (x < \".$screenmaxwidth.\") ) {\";\n }\n elseif ($screenminwidth) {echo \"if (x > \".$screenminwidth.\") {\";}\n elseif ($screenmaxwidth) {echo \"if (x < \".$screenmaxwidth.\") {\";}\n\n echo \"\n newscript = document.createElement('script');\n newscript.setAttribute('id','screen-size-script');\n newscript.src = '\".$screensizescripturl.\"';\n document.getElementsByTagName('head')[0].appendChild(newscript);\n }\n }\n\n /* could just script load here instead of using wp_enqueue script */\n /* loadscreensizescript(); */\n\n var resizeDebounce = (function () {\n var timers = {};\n return function (callback, ms, uniqueId) {\n if (!uniqueId) {uniqueId = \"nonuniqueid\";}\n if (timers[uniqueId]) {clearTimeout (timers[uniqueId]);}\n timers[uniqueId] = setTimeout(callback, ms);\n };\n })();\n\n\n jQuery(window).resize(function () {\n if (document.getElementById('screen-size-script')) {return;}\n resizeDebounce(function(){ \n loadscreensizescript();\n }, 1000, \"screensizescript\");\n }); \n });\n }\n</code></pre>\n\n<p>Although, it is arguably a better just to load the script using <code>jQuery(document).ready</code> in the first place as noted above and not bothering with <code>wp_enqueue_script</code>, but I guess that wouldn't fully answer the question. :-)</p>\n\n<p>Note: untested as a whole from otherwise working snippets I have lying around...</p>\n"
}
] |
2016/06/11
|
[
"https://wordpress.stackexchange.com/questions/229432",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8049/"
] |
Is it possible to load scripts through `wp_enqueue_script` based on a browser's width?
Thanks
|
Kinda just answering this to counter the "not-possible" answers...
Yes it is probably not the best thing to do, since we are still unsure what the OP is trying to achieve, but that does not make it not possible... complex and impractical perhaps, but still entirely possible.
First enqueue the script as you normally would... here setting the minimum and/or maximum screen widths to load for as well:
```
add_action('wp_enqueue_scripts','enqueue_screen_size_script');
function enqueue_screen_size_script() {
global $screensizescripturl, $screenminwidth, $screenmaxwidth;
// set one or the other or both of these
$screenminwidth = '319'; $screenmaxwidth = '769';
$screensizescripturl = get_stylesheet_directory_uri().'/screen-size.js';
wp_enqueue_script('screen-size',$screensizescripturl,array('jquery'));
}
```
Then you can filter the enqueue using the `script_loader_tag` filter, and add some magical javascript to conditionally load the script inside itself:
```
add_filter('script_loader_tag','enqueue_for_screen_size', 10, 2);
function enqueue_for_screen_size($tag, $handle) {
global $screensizescripturl, $screenminwidth, $screenmaxwidth;
if ($handle == 'screen-size') {
// this would get the src url dynamically, but using global instead
// $scripturl = substr($tag,(strpos($tag,'src="')+5),strlen($tag));
// $scripturl = substr($scripturl,0,strpos($tag,'"'));
$conditionaltag = "if (window.jQuery) {x = jQuery(window).width();}
else {x = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;} ";
if ( ($screenminwidth) && ($screenmaxwidth) ) {
$conditionaltag .= "if ( (x > ".$screenminwidth.") && (x < ".$screenmaxwidth.") ) {";
}
elseif ($screenminwidth) {$conditionaltag .= "if (x > ".$screenminwidth.") {";}
elseif ($screenmaxwidth) {$conditionaltag .= "if (x < ".$screenmaxwidth.") {";}
$conditionaltag .= " document.write(unescape('%3Cscript id=\"screen-size-script\" src=\"".$scripturl."\"%3E%3C\/script%3E')); }</script>";
$tag = str_replace('src="'.$scripturl.'"','',$tag);
$tag = str_replace('</script>',$conditionaltag, $tag);
}
return $tag;
}
```
So then, the point of responsiveness being responsive, you would probably need a window resize function to dynamically load the script if it fits your chosen specifications after resize... with a debounce thrown in for good measure.
```
add_action('wp_footer','screen_resizer_check');
function screen_resizer_check() {
global $screensizescripturl, $screenminwidth, $screenmaxwidth;
// note: debounce window resize function from here:
// http://stackoverflow.com/questions/2854407/javascript-jquery-window-resize-how-to-fire-after-the-resize-is-completed
echo "<script>jQuery(document).ready(function($) {
function loadscreensizescript() {
x = jQuery(window).width();
";
if ( ($screenminwidth) && ($screenmaxwidth) ) {
echo "if ( (x > ".$screenminwidth.") && (x < ".$screenmaxwidth.") ) {";
}
elseif ($screenminwidth) {echo "if (x > ".$screenminwidth.") {";}
elseif ($screenmaxwidth) {echo "if (x < ".$screenmaxwidth.") {";}
echo "
newscript = document.createElement('script');
newscript.setAttribute('id','screen-size-script');
newscript.src = '".$screensizescripturl."';
document.getElementsByTagName('head')[0].appendChild(newscript);
}
}
/* could just script load here instead of using wp_enqueue script */
/* loadscreensizescript(); */
var resizeDebounce = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) {uniqueId = "nonuniqueid";}
if (timers[uniqueId]) {clearTimeout (timers[uniqueId]);}
timers[uniqueId] = setTimeout(callback, ms);
};
})();
jQuery(window).resize(function () {
if (document.getElementById('screen-size-script')) {return;}
resizeDebounce(function(){
loadscreensizescript();
}, 1000, "screensizescript");
});
});
}
```
Although, it is arguably a better just to load the script using `jQuery(document).ready` in the first place as noted above and not bothering with `wp_enqueue_script`, but I guess that wouldn't fully answer the question. :-)
Note: untested as a whole from otherwise working snippets I have lying around...
|
229,438 |
<p>I am developing plugin right now, and I have one questions about <code>best practices</code> and conventions. </p>
<p><strong>What I need ?</strong> </p>
<p>My plugin is going to store some predefined object, list of objects (or just arrays/key-value pairs) and it will be possible to add new object and fill its fields.<br>
For example my object will have following content </p>
<pre><code>{
"id": 123,
"url": "http://google.com/",
"enabled" : true,
"name": "hello_world",
"api_key" : "api_key"
}
</code></pre>
<p>Simple <code>JSON</code> object. </p>
<p>And on <code>Plugin Admin configuration page</code> it will be possible to add, edit or remove such objects. </p>
<p><strong>What is my question ?</strong></p>
<p>What is the best way of storing such data. I have installed a lot of different plugins in order to see how does custom data from settings is stored. There some options I have seen </p>
<ol>
<li><p>Using <code>Settings API</code> provided by <code>Wordpress</code>. Even <code>UI</code> is handled by wordpress, you can just call the function and it will create proper input field and than save all settings into options table. All checks and security is handled by wordpress as well. But is it possible to create dynamic admin page where you can add new items ? </p></li>
<li><p>Using old <code>Options API</code> is also stored in the options table, but gives more freedom to developer to handle all validation. </p></li>
<li><p>Creating new database table and save data in it.</p></li>
</ol>
<p>I don't think I am going to use third method. </p>
<p>Please suggest better way to do this or maybe you know the plugin already implemented such functionality in a right way. I would grateful for any help.</p>
|
[
{
"answer_id": 229446,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li>Yes</li>\n<li><p>this is actually the same as point 1, just without the helpers</p></li>\n<li><p>Now this depends on how you want to use your setting. The instinct is that at 99% of the cases this will just add unneeded complexity to your code and hurt performance.</p></li>\n</ol>\n\n<p>As long as we are talking about setting and not content or widgets, the settings API is what you should use. It takes some time to get used to it, but it doesn't impose any limitation on the type of GUI or settings structure you can have. Whatever you can do with a html form you can also do with the settings API.</p>\n\n<p>But wait, there is an alternative, and that is to use the customizer. If your settings have front end implications you should consider using it </p>\n"
},
{
"answer_id": 229448,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Where to store plugin settings fields?</p>\n</blockquote>\n\n<p>Options table FTW. It's cached and easy to do CRUD.</p>\n\n<blockquote>\n <p>Settings API or Options API?</p>\n</blockquote>\n\n<p>Basically, you can <a href=\"https://codex.wordpress.org/Options_API\" rel=\"nofollow\">use Options API</a> without Settings API but you <s>cannot</s> <a href=\"https://developer.wordpress.org/plugins/settings/settings-api/#why-use-the-setting-api\" rel=\"nofollow\">use Settings API</a> without Options API. Even when you just need to add some fields to a existing WordPress page, you still need <a href=\"https://developer.wordpress.org/reference/functions/get_option/\" rel=\"nofollow\">get_option()</a> to retrieve data for your view template.</p>\n\n<p>But by using a existing WordPress page, your data will be fragmented and hard to retrieve/maintain because it's stored with different <code>option_name</code>. It might confuse end-users as well.</p>\n\n<p>When using Options API only, as the author of the plugin, you can add news sections/fields whenever you want but other people can't. Because view template is hardcoded without hooks which work like <a href=\"https://developer.wordpress.org/reference/functions/do_settings_sections/\" rel=\"nofollow\">do_settings_sections()</a> and <a href=\"https://developer.wordpress.org/reference/functions/do_settings_fields/\" rel=\"nofollow\">do_settings_fields()</a>. Of course, you can you use <a href=\"https://developer.wordpress.org/reference/functions/do_action/\" rel=\"nofollow\">do_action()</a> but it's will be much more complicated.</p>\n\n<p>Using Options API <em>gives more freedom to developer to handle all validation</em> is incorrect. Settings API has <code>sanitize_callback</code> which also allow developer to do whatever they want with input data.</p>\n\n<p>So, why don't use both of them?</p>\n\n<p>For example, let say a setting page using both Settings API and Options API with <code>option_group</code> is <code>my_app_group</code> and <code>option_name</code> is <code>my_app</code>:</p>\n\n<pre><code>$options = get_option('my_app');\n\n?><div class=\"wrap\">\n <h1><?= __('Plugin Settings', 'textdomain') ?></h1>\n <form class=\"form-table\" method=\"post\" action=\"options.php\">\n <?php settings_fields('my_app_group') ?>\n <table>\n <tr>\n <td>\n <label for=\"my_app[name]\">\n <?= __('App Name', 'textdomain') ?>\n </label>\n </td>\n <td>\n <input type=\"text\" name=\"my_app[name]\" value=\"<?= $options['name'] ?>\">\n </td>\n </tr>\n <tr>\n <td>\n <label for=\"my_app[app_key]\">\n <?= __('App Key', 'textdomain') ?>\n </label>\n </td>\n <td>\n <input type=\"text\" name=\"my_app[app_key]\" value=\"<?= $options['app_key'] ?>\">\n </td>\n </tr>\n <?php do_settings_fields('my_app_group', 'default') ?>\n </table>\n <?php do_settings_sections('my_app_group') ?>\n <?php submit_button() ?>\n </form>\n</div><?php\n</code></pre>\n\n<p>Now, all data is stored in options table under <code>my_app</code> option name then it's easy to retrieve/maintain. Other developers can also add new sections/fields to your plugin too.</p>\n"
},
{
"answer_id": 229449,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 4,
"selected": true,
"text": "<p>It depends on how you are going to use the stored data. </p>\n\n<p>If you want to run complex queries against the values, use a custom table with indexes optimized for those queries. </p>\n\n<p>If you will always just fetch all the values for a given object, create a non-public custom post type, and store the data as post meta.</p>\n\n<p>Do not store the data in a serialized string, like the options API does it. This is a nightmare when you want to change it per command line SQL, because the serialized format is PHP specific.</p>\n\n<p>The \"Settings API\" imposes some very outdated markup, and the code for the registration and storage is rather counter-intuitive. I wouldn't recommend to use it.</p>\n"
}
] |
2016/06/11
|
[
"https://wordpress.stackexchange.com/questions/229438",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93387/"
] |
I am developing plugin right now, and I have one questions about `best practices` and conventions.
**What I need ?**
My plugin is going to store some predefined object, list of objects (or just arrays/key-value pairs) and it will be possible to add new object and fill its fields.
For example my object will have following content
```
{
"id": 123,
"url": "http://google.com/",
"enabled" : true,
"name": "hello_world",
"api_key" : "api_key"
}
```
Simple `JSON` object.
And on `Plugin Admin configuration page` it will be possible to add, edit or remove such objects.
**What is my question ?**
What is the best way of storing such data. I have installed a lot of different plugins in order to see how does custom data from settings is stored. There some options I have seen
1. Using `Settings API` provided by `Wordpress`. Even `UI` is handled by wordpress, you can just call the function and it will create proper input field and than save all settings into options table. All checks and security is handled by wordpress as well. But is it possible to create dynamic admin page where you can add new items ?
2. Using old `Options API` is also stored in the options table, but gives more freedom to developer to handle all validation.
3. Creating new database table and save data in it.
I don't think I am going to use third method.
Please suggest better way to do this or maybe you know the plugin already implemented such functionality in a right way. I would grateful for any help.
|
It depends on how you are going to use the stored data.
If you want to run complex queries against the values, use a custom table with indexes optimized for those queries.
If you will always just fetch all the values for a given object, create a non-public custom post type, and store the data as post meta.
Do not store the data in a serialized string, like the options API does it. This is a nightmare when you want to change it per command line SQL, because the serialized format is PHP specific.
The "Settings API" imposes some very outdated markup, and the code for the registration and storage is rather counter-intuitive. I wouldn't recommend to use it.
|
229,480 |
<p>I read that if you create a php file and save it in the /wp-content/mu-plugins/ directory, WordPress will auto-load it.</p>
<p>However, I haven't yet figured it out. I don't have a folder named mu-plugins; it's just wp-content/plugins. I created a file at wp-content/plugins/echo-values.php, put a simple echo value in it and uploaded it, but I don't see the value I echoed in my source code.</p>
<p>I then opened wp-content/plugins/index.php and pasted in the following code:</p>
<pre><code>require_once("echo-values.php");
require_once("/wp-content/plugins/echo-values.php");
</code></pre>
<p>Again, I don't see anything in my source code, so it looks like those files aren't being included. For good measure, I echoed some text in /wp-content/plugins/index.php, but I don't even see that in the source code.</p>
<p>Can anyone tell me the best way to include my own PHP file? It doesn't have to be in the plugins folder, though I was advised that's the best place to put it.</p>
|
[
{
"answer_id": 229482,
"author": "user6454281",
"author_id": 96610,
"author_profile": "https://wordpress.stackexchange.com/users/96610",
"pm_score": 2,
"selected": false,
"text": "<p>That is not how it works in WordPress. The <code>index.php</code> file is put in <code>plugins</code> directory to prevent unwanted behaviors, it isn't used for including files.</p>\n\n<p>You should checkout <a href=\"https://developer.wordpress.org/plugins/\" rel=\"nofollow\">plugins development handbook</a> to know the best way to include your files.</p>\n"
},
{
"answer_id": 229484,
"author": "kaiser",
"author_id": 385,
"author_profile": "https://wordpress.stackexchange.com/users/385",
"pm_score": 2,
"selected": true,
"text": "<p>Yes, you can use a <code>/wp-content/mu-plugins</code> folder for </p>\n\n<ul>\n<li>single file</li>\n<li>autoloading</li>\n</ul>\n\n<p>plugins. The only thing you will have to do is to use a plugin header comment in this file:</p>\n\n<pre><code><?php /* Plugin Name: I am a MU-Plugin */\n</code></pre>\n\n<p>Then you will find a link on top of your <code>/wp-admin/plugins.php</code> page that says </p>\n\n<blockquote>\n <p>\"Must-Use Plugins\"</p>\n</blockquote>\n\n<p>where you will find the list of mu-plugins. Those plugins can not be deactivated by an administrator or anyone else — only someone having access to your servers filesystem will be able to deactivate them by removing them from this folder.</p>\n\n<p>Note, that plugins residing in subdirectories in this folder will <em>not</em> get loaded.</p>\n"
}
] |
2016/06/11
|
[
"https://wordpress.stackexchange.com/questions/229480",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94575/"
] |
I read that if you create a php file and save it in the /wp-content/mu-plugins/ directory, WordPress will auto-load it.
However, I haven't yet figured it out. I don't have a folder named mu-plugins; it's just wp-content/plugins. I created a file at wp-content/plugins/echo-values.php, put a simple echo value in it and uploaded it, but I don't see the value I echoed in my source code.
I then opened wp-content/plugins/index.php and pasted in the following code:
```
require_once("echo-values.php");
require_once("/wp-content/plugins/echo-values.php");
```
Again, I don't see anything in my source code, so it looks like those files aren't being included. For good measure, I echoed some text in /wp-content/plugins/index.php, but I don't even see that in the source code.
Can anyone tell me the best way to include my own PHP file? It doesn't have to be in the plugins folder, though I was advised that's the best place to put it.
|
Yes, you can use a `/wp-content/mu-plugins` folder for
* single file
* autoloading
plugins. The only thing you will have to do is to use a plugin header comment in this file:
```
<?php /* Plugin Name: I am a MU-Plugin */
```
Then you will find a link on top of your `/wp-admin/plugins.php` page that says
>
> "Must-Use Plugins"
>
>
>
where you will find the list of mu-plugins. Those plugins can not be deactivated by an administrator or anyone else — only someone having access to your servers filesystem will be able to deactivate them by removing them from this folder.
Note, that plugins residing in subdirectories in this folder will *not* get loaded.
|
229,530 |
<p>domain.com/rents/miami-dade/</p>
<p>domain.com/companies/miami-dade/</p>
<p>Then for, say rents/miami-dade/ I would loop through some different areas within miami, showing a list of rents for each area. For example:</p>
<p>domain.com/rents/miami-dade/</p>
<p>would render something like this by looping through the areas in Miami:</p>
<p>North Miami Beach</p>
<ul>
<li>rents table</li>
</ul>
<p>Hialeah</p>
<ul>
<li>rents table</li>
</ul>
<p>Cutler Ridge</p>
<ul>
<li>rents table</li>
</ul>
<p>I'd need to mimic the exact same sequence for a different object, 'companies'. </p>
<p>domain.com/companies/miami-dade/</p>
<p>would render something like this by looping through the areas in Miami:</p>
<p>North Miami Beach</p>
<ul>
<li>companies table</li>
</ul>
<p>Hialeah</p>
<ul>
<li>companies table</li>
</ul>
<p>Cutler Ridge</p>
<ul>
<li>companies table</li>
</ul>
<p>How could I go about setting something like this up? I've already created a companies post type, and made taxonomies for counties and cities.</p>
<p>I'm already able to see a taxomonie's own page, but it's not limited to a certain post type, which isn't what I need. I need to url to resemble something like what I showed here. </p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 229541,
"author": "Prashant Gupta",
"author_id": 96640,
"author_profile": "https://wordpress.stackexchange.com/users/96640",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, i have some basic ideas. \nYou can install a plugin called Redirection. And after that, you can make like and redirect to some other pages with you own data.</p>\n\n<p>but URL will change as the person redirect to the other specific page.</p>\n\n<p>Now if you want to them to land on the specific page... you need to make the folder into server directory under the main site and inside it file containing index.php or index.html. \nExample: Goto you Cpanel and goto file maneger>> created the folder name if you want like, for \"domain.com/companies/miami-dade/\" create folder \"companies\" then subfolder \"miami-dude\". Note each folder should contain index.html file or it will not work.\nNote: this trick won't copy you theme else u need to make an entire HTML page and save it as index.html</p>\n\n<p>Hope it might help you :-) </p>\n"
},
{
"answer_id": 229546,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 3,
"selected": true,
"text": "<p>You can accomplish this with <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\" rel=\"nofollow\"><code>add_rewrite_rule()</code></a>.</p>\n\n<p>I personally like to show this example in a class to make it copy/paste ready. You could throw this in a plugin or functions.php -- some place that loads this code before <code>query_vars</code>, <code>parse_request</code> and <code>init</code>.</p>\n\n<p>The goal is to add rewrite rules, make sure you can add custom properties to the main query, then replace the default template to be loaded with your custom template.</p>\n\n<pre><code>if (!class_exists('RentsAndCompaniesRewrite')):\n\n class RentsAndCompaniesRewrite\n {\n // WordPress hooks\n\n public function init()\n {\n add_filter('query_vars', array($this, 'add_query_vars'), 0);\n add_action('parse_request', array($this, 'sniff_requests'), 0);\n add_action('init', array($this, 'add_endpoint'), 0);\n }\n\n // Add public query vars\n\n public function add_query_vars($vars)\n {\n $vars[] = 'show_companies';\n $vars[] = 'show_rents';\n $vars[] = 'location';\n\n return $vars;\n }\n\n // Add API Endpoint\n\n public function add_endpoint()\n {\n add_rewrite_rule('^rents/([^/]*)/?', 'index.php?show_rents=1&location=$matches[1]', 'top');\n add_rewrite_rule('^companies/([^/]*)/?', 'index.php?show_companies=1&location=$matches[1]', 'top');\n\n flush_rewrite_rules(false); //// <---------- REMOVE THIS WHEN DONE TESTING\n }\n\n // Sniff Requests\n\n public function sniff_requests($wp_query) {\n global $wp;\n\n if ( isset( $wp->query_vars[ 'show_rents' ], $wp->query_vars[ 'location' ] ) ) {\n\n $this->handle_request_show_rents();\n\n } else if ( isset( $wp->query_vars[ 'show_companies' ], $wp->query_vars[ 'location' ] ) ) {\n\n $this->handle_request_show_companies();\n }\n }\n\n // Handle Requests\n\n protected function handle_request_show_rents()\n {\n add_filter('template_include', function ($original_template) {\n\n return get_stylesheet_directory() . '/templates/rents_by_location.php';\n });\n }\n\n protected function handle_request_show_companies()\n {\n add_filter('template_include', function ($original_template) {\n\n return get_stylesheet_directory() . '/templates/companies_by_location.php';\n });\n }\n }\n\n $wptept = new RentsAndCompaniesRewrite();\n $wptept->init();\n\nendif; // RentsAndCompaniesRewrite\n</code></pre>\n\n<p>In a directory within your theme, add the templates you will use when the request is handled.</p>\n\n<p><strong>/templates/companies_by_location.php</strong></p>\n\n<pre><code><?php\n\nglobal $wp;\n$location = $wp->query_vars[ 'location' ];\n\necho 'Companies in the ' . $location . ' area:';\n</code></pre>\n\n<p><strong>/templates/rents_by_location.php</strong></p>\n\n<pre><code><?php\n\nglobal $wp;\n$location = $wp->query_vars[ 'location' ];\n\necho 'Rents in the ' . $location . ' area:';\n</code></pre>\n"
}
] |
2016/06/12
|
[
"https://wordpress.stackexchange.com/questions/229530",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35549/"
] |
domain.com/rents/miami-dade/
domain.com/companies/miami-dade/
Then for, say rents/miami-dade/ I would loop through some different areas within miami, showing a list of rents for each area. For example:
domain.com/rents/miami-dade/
would render something like this by looping through the areas in Miami:
North Miami Beach
* rents table
Hialeah
* rents table
Cutler Ridge
* rents table
I'd need to mimic the exact same sequence for a different object, 'companies'.
domain.com/companies/miami-dade/
would render something like this by looping through the areas in Miami:
North Miami Beach
* companies table
Hialeah
* companies table
Cutler Ridge
* companies table
How could I go about setting something like this up? I've already created a companies post type, and made taxonomies for counties and cities.
I'm already able to see a taxomonie's own page, but it's not limited to a certain post type, which isn't what I need. I need to url to resemble something like what I showed here.
Thanks in advance!
|
You can accomplish this with [`add_rewrite_rule()`](https://codex.wordpress.org/Rewrite_API/add_rewrite_rule).
I personally like to show this example in a class to make it copy/paste ready. You could throw this in a plugin or functions.php -- some place that loads this code before `query_vars`, `parse_request` and `init`.
The goal is to add rewrite rules, make sure you can add custom properties to the main query, then replace the default template to be loaded with your custom template.
```
if (!class_exists('RentsAndCompaniesRewrite')):
class RentsAndCompaniesRewrite
{
// WordPress hooks
public function init()
{
add_filter('query_vars', array($this, 'add_query_vars'), 0);
add_action('parse_request', array($this, 'sniff_requests'), 0);
add_action('init', array($this, 'add_endpoint'), 0);
}
// Add public query vars
public function add_query_vars($vars)
{
$vars[] = 'show_companies';
$vars[] = 'show_rents';
$vars[] = 'location';
return $vars;
}
// Add API Endpoint
public function add_endpoint()
{
add_rewrite_rule('^rents/([^/]*)/?', 'index.php?show_rents=1&location=$matches[1]', 'top');
add_rewrite_rule('^companies/([^/]*)/?', 'index.php?show_companies=1&location=$matches[1]', 'top');
flush_rewrite_rules(false); //// <---------- REMOVE THIS WHEN DONE TESTING
}
// Sniff Requests
public function sniff_requests($wp_query) {
global $wp;
if ( isset( $wp->query_vars[ 'show_rents' ], $wp->query_vars[ 'location' ] ) ) {
$this->handle_request_show_rents();
} else if ( isset( $wp->query_vars[ 'show_companies' ], $wp->query_vars[ 'location' ] ) ) {
$this->handle_request_show_companies();
}
}
// Handle Requests
protected function handle_request_show_rents()
{
add_filter('template_include', function ($original_template) {
return get_stylesheet_directory() . '/templates/rents_by_location.php';
});
}
protected function handle_request_show_companies()
{
add_filter('template_include', function ($original_template) {
return get_stylesheet_directory() . '/templates/companies_by_location.php';
});
}
}
$wptept = new RentsAndCompaniesRewrite();
$wptept->init();
endif; // RentsAndCompaniesRewrite
```
In a directory within your theme, add the templates you will use when the request is handled.
**/templates/companies\_by\_location.php**
```
<?php
global $wp;
$location = $wp->query_vars[ 'location' ];
echo 'Companies in the ' . $location . ' area:';
```
**/templates/rents\_by\_location.php**
```
<?php
global $wp;
$location = $wp->query_vars[ 'location' ];
echo 'Rents in the ' . $location . ' area:';
```
|
229,556 |
<p>Is it possible to remove "nextpage" tag inside posts text depending of utm_campaign ?</p>
<p>Depending of where my visitors are comming from, I want to remove the </p>
<pre><code><!--nextpage-->
</code></pre>
<p>of my post.</p>
<p>I am using this </p>
<pre><code>if($_GET['utm_campaign']== 'nonextpagecampaign') {
</code></pre>
<p>directly in my template in order to display or not things depending of the campaign name but for the nextpage tag, it's not that easy.</p>
|
[
{
"answer_id": 229569,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 4,
"selected": true,
"text": "<p>You can use <code>the_post</code> hook to remove <code><!--nextpage--></code>. In this case:</p>\n\n<pre><code>add_action( 'the_post', 'campaign_remove_nextpage', 99);\n\nfunction campaign_remove_nextpage ( $post ) {\n if ( ($_GET['utm_campaign']== 'nonextpagecampaign') && (false !== strpos( $post->post_content, '<!--nextpage-->' )) ) \n {\n // Reset the global $pages:\n $GLOBALS['pages'] = [ $post->post_content ];\n\n // Reset the global $numpages:\n $GLOBALS['numpages'] = 0;\n\n // Reset the global $multipage:\n $GLOBALS['multipage'] = false;\n }\n};\n</code></pre>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/183582/how-to-ignore-or-disable-nextpage-tag\">Read more about this issue</a></p>\n\n<p>More in general, you may want to read <a href=\"https://wordpress.stackexchange.com/questions/87514/make-google-index-the-entire-post-if-it-is-separated-into-several-pages\">this warning</a> about SEO effects of using <code><!--nextpage--></code>.</p>\n"
},
{
"answer_id": 229589,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>We can use the <code>content_pagination</code><sup><a href=\"https://developer.wordpress.org/reference/hooks/content_pagination/\" rel=\"nofollow\">codex</a></sup> filter to modify the paginated content without modifying the globals directly:</p>\n\n<pre><code>add_filter( 'content_pagination', function( $pages )\n{\n // Target only the correct utm_campaign GET parameter \n if( 'nonextpagecampaign' !== filter_input( INPUT_GET, 'utm_campaign', FILTER_SANITIZE_STRING ) )\n return $pages;\n\n // Remove the content pagination, only if it's already paginated\n if( count( $pages ) > 1 )\n $pages = [ join( '', $pages ) ];\n\n return $pages;\n} );\n</code></pre>\n\n<p>where we return an array with the combined content when the correct <code>utm_campaign</code> GET paramter is detected. Hopefully you can adjust this further to your needs.</p>\n"
}
] |
2016/06/13
|
[
"https://wordpress.stackexchange.com/questions/229556",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57405/"
] |
Is it possible to remove "nextpage" tag inside posts text depending of utm\_campaign ?
Depending of where my visitors are comming from, I want to remove the
```
<!--nextpage-->
```
of my post.
I am using this
```
if($_GET['utm_campaign']== 'nonextpagecampaign') {
```
directly in my template in order to display or not things depending of the campaign name but for the nextpage tag, it's not that easy.
|
You can use `the_post` hook to remove `<!--nextpage-->`. In this case:
```
add_action( 'the_post', 'campaign_remove_nextpage', 99);
function campaign_remove_nextpage ( $post ) {
if ( ($_GET['utm_campaign']== 'nonextpagecampaign') && (false !== strpos( $post->post_content, '<!--nextpage-->' )) )
{
// Reset the global $pages:
$GLOBALS['pages'] = [ $post->post_content ];
// Reset the global $numpages:
$GLOBALS['numpages'] = 0;
// Reset the global $multipage:
$GLOBALS['multipage'] = false;
}
};
```
[Read more about this issue](https://wordpress.stackexchange.com/questions/183582/how-to-ignore-or-disable-nextpage-tag)
More in general, you may want to read [this warning](https://wordpress.stackexchange.com/questions/87514/make-google-index-the-entire-post-if-it-is-separated-into-several-pages) about SEO effects of using `<!--nextpage-->`.
|
229,575 |
<p>I remove some metaboxes using</p>
<pre><code>remove_meta_box('commentsdiv','page','normal'); // Comments.
remove_meta_box( 'commentsdiv','post','normal' ); // Comments.
</code></pre>
<p>It doesn't seem to apply to CPTs.
So to remove a metabox from all CPTs, is there an alternative to repeating the above but with the cpt name replacing page/post?</p>
|
[
{
"answer_id": 229579,
"author": "Jebble",
"author_id": 81939,
"author_profile": "https://wordpress.stackexchange.com/users/81939",
"pm_score": 0,
"selected": false,
"text": "<p>The standard meta boxes that are shown on Custom Post Types are determined by the support you've given to the post type in the <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow\">register_post_type()</a> function.</p>\n\n<p>The function has a <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#supports\" rel=\"nofollow\">supports</a> argument that takes an array as value. In this array simply remove 'comments' and it won't show the comments meta boxes.</p>\n"
},
{
"answer_id": 229580,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 2,
"selected": false,
"text": "<p>@Jeffrey's answer is correct is you are the one registering the post types, simply remove the support argument for <code>comments</code>.</p>\n\n<p>But if you want to remove it from <em>all</em> custom post types (that may be registered by plugins too) you can do:</p>\n\n<pre><code>$cptslugs = get_post_types( array('public'=>false, '_builtin' => false) , 'names', 'and');\nforeach ($cptslugs as $cpt) {\n remove_meta_box( 'commentsdiv', $cpt, 'normal' );\n}\n</code></pre>\n"
}
] |
2016/06/13
|
[
"https://wordpress.stackexchange.com/questions/229575",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63350/"
] |
I remove some metaboxes using
```
remove_meta_box('commentsdiv','page','normal'); // Comments.
remove_meta_box( 'commentsdiv','post','normal' ); // Comments.
```
It doesn't seem to apply to CPTs.
So to remove a metabox from all CPTs, is there an alternative to repeating the above but with the cpt name replacing page/post?
|
@Jeffrey's answer is correct is you are the one registering the post types, simply remove the support argument for `comments`.
But if you want to remove it from *all* custom post types (that may be registered by plugins too) you can do:
```
$cptslugs = get_post_types( array('public'=>false, '_builtin' => false) , 'names', 'and');
foreach ($cptslugs as $cpt) {
remove_meta_box( 'commentsdiv', $cpt, 'normal' );
}
```
|
229,594 |
<p>I have seen some questions which look similar, but they all ended up with <a href="http://codex.wordpress.org/Create_A_Network" rel="noreferrer">multisite</a>. For maintainability, performance and security, I don't want to use multisite. So please bear with me.</p>
<p>This is what I'm thinking about:</p>
<pre><code>.
|_____branch1 // for branch1.domain.com
| |_____themes
| |_____plugins
|
|_____branch2 // for branch2.domain.com
| |_____themes
| |_____plugins
|
|_____branch3 // for branch3.domain.com
| |_____themes
| |_____plugins
|
|_____index.php
|_____WordPress
|_____wp-config.php
</code></pre>
<p>As you can see, each domain has its own database and content directory but just one WordPress instance. Now, themes, plugins and databases become smaller and independent. Then, it would be much easier to maintain, scale...</p>
<p>But is it possible? If you have experienced the same problem before, please share your thoughts! I really appreciate your help. </p>
|
[
{
"answer_id": 229623,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 5,
"selected": true,
"text": "<p>As <a href=\"https://wordpress.stackexchange.com/users/736/tom-j-nowell\">@tom-j-nowell</a> said in comment to OP, multisite can make this easier.</p>\n\n<p>Performance and security are not really a problem for multisite (at least, not more than they are for regular installations), but I do agree that multisite can sometimes be a problem, because a lot of plugins (either custom or 3rd party) may not work properly on multisite, or maybe because you want to keep users of different websites completely separated.</p>\n\n<p>That said what you want to achieve is not that hard.</p>\n\n<p>What you need to change between installation is:</p>\n\n<ul>\n<li>plugins folder</li>\n<li>themes folder</li>\n<li>database settings</li>\n</ul>\n\n<p>Those configuration can be done using <a href=\"https://codex.wordpress.org/Editing_wp-config.php\" rel=\"nofollow noreferrer\">constants in <code>wp-config.php</code></a> your only problem is how to switch them based on URL.</p>\n\n<p>The server variable <code>'SERVER_NAME'</code> should work for you, at least if your webserver is configured properly.</p>\n\n<p>For example you can create a folder named <code>/conf</code> at the same level of <code>wp-config.php</code> file and <code>/WordPress</code> folder.</p>\n\n<p>In that folder you can add some files:</p>\n\n<ul>\n<li><code>branch1.domain.com.conf</code></li>\n<li><code>branch2.domain.com.conf</code></li>\n<li><code>branch3.domain.com.conf</code></li>\n</ul>\n\n<p>inside each of them you can do something like</p>\n\n<pre><code>$branch = 'branch1';\n$base_dir = dirname( __DIR__) . \"/{$branch}\";\n\ndefined( 'WP_CONTENT_DIR' ) or define( 'WP_CONTENT_DIR', $base_dir );\n\n// be sure WP understand URLs correctly\ndefined( 'DB_HOME' ) or define( 'DB_HOME', \"{$branch}.example.com\" );\ndefined('WP_SITEURL') or define('WP_SITEURL', \"{$branch}.example.com/WordPress\");\n\n// adjust DB settings as needed\ndefined( 'DB_NAME' ) or define( 'DB_NAME', $branch );\ndefined( 'DB_USER' ) or define( 'DB_USER', $branch );\ndefined( 'DB_PASSWORD' ) or define( 'DB_PASSWORD', '********' );\n\nunset( $base_dir, $branch );\n</code></pre>\n\n<p>This will change on each configuration file according to the \"branch\".</p>\n\n<p>After that, in your unique <code>wp-config.php</code> you can so something like:</p>\n\n<pre><code>$defaults_conf = [\n 'WP_CONTENT_DIR' => __DIR__ . '/branch1',\n 'DB_HOST' => 'localhost',\n 'DB_NAME' => 'branch1',\n 'DB_USER' => 'branch1',\n 'DB_PASSWORD' => '********',\n];\n\n$host = getenv('WORDPRESS_HOST') ?: $_SERVER['SERVER_NAME'];\n\nif ($host && file_exists(__DIR__.\"/conf/{$host}.conf\")) {\n require __DIR__.\"/conf/{$host}.conf\";\n}\n\narray_walk($defaults_conf, function($value, $name) {\n defined($name) or define($name, $value);\n});\n\nunset($defaults_conf, $host);\n</code></pre>\n\n<p>What happen above is that based on the server name you load a different configuration file (if found) and if the configuration file does not define any of the default configuration (or if the file is not found) configuration are set per default.</p>\n\n<p>Nice thing is that to add a new branch, you just need to create the branch folder and provide a <code>.conf</code> named after the new branch domain, and you are done, there's nothing to change on WP side.</p>\n\n<p>The line:</p>\n\n<pre><code> $host = getenv('WORDPRESS_HOST') ?: $_SERVER['SERVER_NAME'];\n</code></pre>\n\n<p>is where I get the domain name. As first option I'm using an environment variable, because there're chances <code>$_SERVER['SERVER_NAME']</code> will not work on a command line context, such us when using WP CLI. In those situations you can set an environment variable to force WP to use settings from a specific branch.</p>\n\n<p>Note that in branch-specific config files I'm changing the <code>WP_CONTENT_DIR</code> and that will automatically set plugins and themes folder to the related <code>/plugins</code> and <code>/themes</code> branch subfolders.</p>\n\n<p>A possible issue here is if you want to share the <code>/uploads</code> folder (where files get uploaded).</p>\n\n<p>By default that folder is a subfolder of content dir, so using workflow above it will be an <code>/uploads</code> subfolder of each branch root folder.</p>\n\n<p>If that is not a problem for you, than just go with it, otherwise the easiest solution would be to make <code>/uploads</code> in each branch folder a symlink to the <em>real</em> uploads folder you want to share.</p>\n"
},
{
"answer_id": 271266,
"author": "Cpyder",
"author_id": 106155,
"author_profile": "https://wordpress.stackexchange.com/users/106155",
"pm_score": 0,
"selected": false,
"text": "<p>This is possible with a symlinking and a bit of planning. I did some scouring on the net for the same thing. Finally, put together all the stuff and got it working.</p>\n\n<p>I have been running a few websites, they all share the same theme and plugin folder. Same folders work for multisite and single sites. But you have to be careful about certain plugins which can be Multi/Single site only and be quirky.</p>\n\n<p>I have made a directory like master-tnp/themes and master-tnp/plugins. Then symlink to your wordpress directory using ln -s command.</p>\n\n<p>Pitfalls are in server configurations as well. Ensure follow symlinks directive is set to allow.</p>\n\n<p>If you want to use a Single WordPress installation, I have put together a detailed guide as to how I did it at <a href=\"https://vaish.co/multiple-sites-single-wordpress-directory\" rel=\"nofollow noreferrer\">https://vaish.co/multiple-sites-single-wordpress-directory</a></p>\n"
}
] |
2016/06/13
|
[
"https://wordpress.stackexchange.com/questions/229594",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92212/"
] |
I have seen some questions which look similar, but they all ended up with [multisite](http://codex.wordpress.org/Create_A_Network). For maintainability, performance and security, I don't want to use multisite. So please bear with me.
This is what I'm thinking about:
```
.
|_____branch1 // for branch1.domain.com
| |_____themes
| |_____plugins
|
|_____branch2 // for branch2.domain.com
| |_____themes
| |_____plugins
|
|_____branch3 // for branch3.domain.com
| |_____themes
| |_____plugins
|
|_____index.php
|_____WordPress
|_____wp-config.php
```
As you can see, each domain has its own database and content directory but just one WordPress instance. Now, themes, plugins and databases become smaller and independent. Then, it would be much easier to maintain, scale...
But is it possible? If you have experienced the same problem before, please share your thoughts! I really appreciate your help.
|
As [@tom-j-nowell](https://wordpress.stackexchange.com/users/736/tom-j-nowell) said in comment to OP, multisite can make this easier.
Performance and security are not really a problem for multisite (at least, not more than they are for regular installations), but I do agree that multisite can sometimes be a problem, because a lot of plugins (either custom or 3rd party) may not work properly on multisite, or maybe because you want to keep users of different websites completely separated.
That said what you want to achieve is not that hard.
What you need to change between installation is:
* plugins folder
* themes folder
* database settings
Those configuration can be done using [constants in `wp-config.php`](https://codex.wordpress.org/Editing_wp-config.php) your only problem is how to switch them based on URL.
The server variable `'SERVER_NAME'` should work for you, at least if your webserver is configured properly.
For example you can create a folder named `/conf` at the same level of `wp-config.php` file and `/WordPress` folder.
In that folder you can add some files:
* `branch1.domain.com.conf`
* `branch2.domain.com.conf`
* `branch3.domain.com.conf`
inside each of them you can do something like
```
$branch = 'branch1';
$base_dir = dirname( __DIR__) . "/{$branch}";
defined( 'WP_CONTENT_DIR' ) or define( 'WP_CONTENT_DIR', $base_dir );
// be sure WP understand URLs correctly
defined( 'DB_HOME' ) or define( 'DB_HOME', "{$branch}.example.com" );
defined('WP_SITEURL') or define('WP_SITEURL', "{$branch}.example.com/WordPress");
// adjust DB settings as needed
defined( 'DB_NAME' ) or define( 'DB_NAME', $branch );
defined( 'DB_USER' ) or define( 'DB_USER', $branch );
defined( 'DB_PASSWORD' ) or define( 'DB_PASSWORD', '********' );
unset( $base_dir, $branch );
```
This will change on each configuration file according to the "branch".
After that, in your unique `wp-config.php` you can so something like:
```
$defaults_conf = [
'WP_CONTENT_DIR' => __DIR__ . '/branch1',
'DB_HOST' => 'localhost',
'DB_NAME' => 'branch1',
'DB_USER' => 'branch1',
'DB_PASSWORD' => '********',
];
$host = getenv('WORDPRESS_HOST') ?: $_SERVER['SERVER_NAME'];
if ($host && file_exists(__DIR__."/conf/{$host}.conf")) {
require __DIR__."/conf/{$host}.conf";
}
array_walk($defaults_conf, function($value, $name) {
defined($name) or define($name, $value);
});
unset($defaults_conf, $host);
```
What happen above is that based on the server name you load a different configuration file (if found) and if the configuration file does not define any of the default configuration (or if the file is not found) configuration are set per default.
Nice thing is that to add a new branch, you just need to create the branch folder and provide a `.conf` named after the new branch domain, and you are done, there's nothing to change on WP side.
The line:
```
$host = getenv('WORDPRESS_HOST') ?: $_SERVER['SERVER_NAME'];
```
is where I get the domain name. As first option I'm using an environment variable, because there're chances `$_SERVER['SERVER_NAME']` will not work on a command line context, such us when using WP CLI. In those situations you can set an environment variable to force WP to use settings from a specific branch.
Note that in branch-specific config files I'm changing the `WP_CONTENT_DIR` and that will automatically set plugins and themes folder to the related `/plugins` and `/themes` branch subfolders.
A possible issue here is if you want to share the `/uploads` folder (where files get uploaded).
By default that folder is a subfolder of content dir, so using workflow above it will be an `/uploads` subfolder of each branch root folder.
If that is not a problem for you, than just go with it, otherwise the easiest solution would be to make `/uploads` in each branch folder a symlink to the *real* uploads folder you want to share.
|
229,596 |
<p>The wordpress 'Help' and 'Screen Options' Buttons in the wordpress Admin Panels are not working when including bootstrap and specifically the bootstrap-css files.</p>
<p>It is caused because bootstraps css overides:</p>
<pre><code>.hidden {
display: none !important;
}
</code></pre>
<p>How can I make the buttons working again?</p>
<p>It is related to <a href="https://wordpress.stackexchange.com/questions/127179/how-to-fix-wordpress-dashboard-screen-option-help-button-its-not-working/">this Thread</a> but it is not linked to bootstrap therefore I answer it here again as a bootstrap specific problem.</p>
|
[
{
"answer_id": 229597,
"author": "sweisgerber.dev",
"author_id": 56540,
"author_profile": "https://wordpress.stackexchange.com/users/56540",
"pm_score": 2,
"selected": true,
"text": "<p>Check if you or a plugin include bootstrap and the bootstrap CSS / Theme files.</p>\n\n<p>Bootstraps <code>.hidden</code> class looks like:</p>\n\n<pre><code>.hidden {\n display: none !important;\n}\n</code></pre>\n\n<p>But overrides wordpress' definition of <code>.hidden</code>:</p>\n\n<pre><code>.hidden {\n display: none;\n}\n</code></pre>\n\n<p>The Top 'Help' & 'Screen Options' bars are displayed via inline style <code>display: block</code>, which is overridden by bootstraps <code>.hidden {display: none !important}</code> css class.</p>\n\n<p>This can be fixed by rewriting the Top Bars Css via Jquery / JS.</p>\n\n<p>Working example:</p>\n\n<pre><code>jQuery(document).ready(function ($) {\n $(\"#contextual-help-link\").click(function () {\n $(\"#contextual-help-wrap\").css(\"cssText\", \"display: block !important;\");\n });\n $(\"#show-settings-link\").click(function () {\n $(\"#screen-options-wrap\").css(\"cssText\", \"display: block !important;\");\n });\n});\n</code></pre>\n"
},
{
"answer_id": 232170,
"author": "Amay Kulkarni",
"author_id": 98265,
"author_profile": "https://wordpress.stackexchange.com/users/98265",
"pm_score": -1,
"selected": false,
"text": "<p>Add this in the CSS:</p>\n\n<pre><code>* {\n box-sizing: content-box;\n}\n</code></pre>\n"
}
] |
2016/06/13
|
[
"https://wordpress.stackexchange.com/questions/229596",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/56540/"
] |
The wordpress 'Help' and 'Screen Options' Buttons in the wordpress Admin Panels are not working when including bootstrap and specifically the bootstrap-css files.
It is caused because bootstraps css overides:
```
.hidden {
display: none !important;
}
```
How can I make the buttons working again?
It is related to [this Thread](https://wordpress.stackexchange.com/questions/127179/how-to-fix-wordpress-dashboard-screen-option-help-button-its-not-working/) but it is not linked to bootstrap therefore I answer it here again as a bootstrap specific problem.
|
Check if you or a plugin include bootstrap and the bootstrap CSS / Theme files.
Bootstraps `.hidden` class looks like:
```
.hidden {
display: none !important;
}
```
But overrides wordpress' definition of `.hidden`:
```
.hidden {
display: none;
}
```
The Top 'Help' & 'Screen Options' bars are displayed via inline style `display: block`, which is overridden by bootstraps `.hidden {display: none !important}` css class.
This can be fixed by rewriting the Top Bars Css via Jquery / JS.
Working example:
```
jQuery(document).ready(function ($) {
$("#contextual-help-link").click(function () {
$("#contextual-help-wrap").css("cssText", "display: block !important;");
});
$("#show-settings-link").click(function () {
$("#screen-options-wrap").css("cssText", "display: block !important;");
});
});
```
|
229,598 |
<p>I've created a new custom post type called MemberPost and want it to follow a slightly different template to my main index (which is where main news is kept). I've created a custom post type and inserted this into my <code>functions.php</code>.</p>
<pre><code>add_filter('excerpt_more', 'new_excerpt_more');
add_action( 'init', 'register_cpt_member_post' );
function register_cpt_member_post() {
$labels = array(
'name' => __( 'MemberPost', 'member-post' ),
'singular_name' => __( 'MemberPost', 'member-post' ),
'add_new' => __( 'Add New', 'member-post' ),
'add_new_item' => __( 'Add New MemberPost', 'member-post' ),
'edit_item' => __( 'Edit MemberPost', 'member-post' ),
'new_item' => __( 'New MemberPost', 'member-post' ),
'view_item' => __( 'View MemberPost', 'member-post' ),
'search_items' => __( 'Search MemberPost', 'member-post' ),
'not_found' => __( 'No memberpost found', 'member-post' ),
'not_found_in_trash' => __( 'No memberpost found in Trash', 'member-post' ),
'parent_item_colon' => __( 'Parent MemberPost:', 'member-post' ),
'menu_name' => __( 'MemberPost', 'member-post' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => false,
'description' => 'Post containing the months member content',
'supports' => array( 'editor', 'title', 'thumbnail'),
'public' => false,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_nav_menus' => true,
'publicly_queryable' => true,
'exclude_from_search' => true,
'has_archive' => true,
'query_var' => true,
'can_export' => true,
'rewrite' => array('slug' => 'member-post'),
'capability_type' => 'post'
);
register_post_type( 'member_post', $args );
flush_rewrite_rules();
}
</code></pre>
<p>I then created the single-memberPost.php but I can't get the theme to use this custom post template.</p>
|
[
{
"answer_id": 229601,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 2,
"selected": true,
"text": "<p>File should be <code>single-member_post.php</code> instead of <code>single-memberPost.php</code>.</p>\n\n<p>In <code>single-{posttype}</code> , <code>{post_type}</code> is the <code>$post_type</code> argument of the <code>register_post_type()</code> function.</p>\n\n<p>Never use <code>flush_rewrite_rules();</code> in <code>init</code> use it only on theme/plugin deactivate or activate.</p>\n\n<p>Since this is a theme you can use it on <code>after_switch_theme</code> hook.</p>\n\n<pre><code>add_action( 'init', 'my_cpt_init' );\nfunction register_cpt_member_post() {\n register_post_type( ... );\n}\n\nfunction my_rewrite_flush() {\n register_cpt_member_post();\n flush_rewrite_rules();\n}\nadd_action( 'after_switch_theme', 'my_rewrite_flush' );\n</code></pre>\n"
},
{
"answer_id": 229602,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>Your post type (<code>member_post</code>) doesn't match your template slug (<code>memberPost</code>). Whichever you choose, it must be all lower case.</p>\n"
}
] |
2016/06/13
|
[
"https://wordpress.stackexchange.com/questions/229598",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96680/"
] |
I've created a new custom post type called MemberPost and want it to follow a slightly different template to my main index (which is where main news is kept). I've created a custom post type and inserted this into my `functions.php`.
```
add_filter('excerpt_more', 'new_excerpt_more');
add_action( 'init', 'register_cpt_member_post' );
function register_cpt_member_post() {
$labels = array(
'name' => __( 'MemberPost', 'member-post' ),
'singular_name' => __( 'MemberPost', 'member-post' ),
'add_new' => __( 'Add New', 'member-post' ),
'add_new_item' => __( 'Add New MemberPost', 'member-post' ),
'edit_item' => __( 'Edit MemberPost', 'member-post' ),
'new_item' => __( 'New MemberPost', 'member-post' ),
'view_item' => __( 'View MemberPost', 'member-post' ),
'search_items' => __( 'Search MemberPost', 'member-post' ),
'not_found' => __( 'No memberpost found', 'member-post' ),
'not_found_in_trash' => __( 'No memberpost found in Trash', 'member-post' ),
'parent_item_colon' => __( 'Parent MemberPost:', 'member-post' ),
'menu_name' => __( 'MemberPost', 'member-post' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => false,
'description' => 'Post containing the months member content',
'supports' => array( 'editor', 'title', 'thumbnail'),
'public' => false,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_nav_menus' => true,
'publicly_queryable' => true,
'exclude_from_search' => true,
'has_archive' => true,
'query_var' => true,
'can_export' => true,
'rewrite' => array('slug' => 'member-post'),
'capability_type' => 'post'
);
register_post_type( 'member_post', $args );
flush_rewrite_rules();
}
```
I then created the single-memberPost.php but I can't get the theme to use this custom post template.
|
File should be `single-member_post.php` instead of `single-memberPost.php`.
In `single-{posttype}` , `{post_type}` is the `$post_type` argument of the `register_post_type()` function.
Never use `flush_rewrite_rules();` in `init` use it only on theme/plugin deactivate or activate.
Since this is a theme you can use it on `after_switch_theme` hook.
```
add_action( 'init', 'my_cpt_init' );
function register_cpt_member_post() {
register_post_type( ... );
}
function my_rewrite_flush() {
register_cpt_member_post();
flush_rewrite_rules();
}
add_action( 'after_switch_theme', 'my_rewrite_flush' );
```
|
229,621 |
<p>A search on this topic on this site throws up a lot of results claiming to have resolved this issue, but I am having a contrary experience after implementing these guidelines as outlined here:</p>
<ol>
<li><a href="https://wordpress.stackexchange.com/questions/120407/how-to-fix-pagination-for-custom-loops/120408#120408">How to fix pagination for custom loops?</a> </li>
<li><a href="https://wordpress.stackexchange.com/questions/203223/pagination-not-working-on-static-page">Pagination not working on static page</a></li>
<li><a href="https://stackoverflow.com/questions/14026467/pagination-on-static-front-page-wordpress">https://stackoverflow.com/questions/14026467/pagination-on-static-front-page-wordpress</a></li>
</ol>
<p>This is my code below:
<pre><code> // Get current page and append to custom query parameters array
$custom_query_args['paged'] = get_query_var( 'page' ) ? get_query_var( 'page' ) : 1;
// Define custom query parameters
$custom_query_args = array(
'post_type' => 'post',
'posts_per_page' => '4',
'paged' => $custom_query_args['paged'],
'post_status' => 'published',
'cat' => '1',
);
// Instantiate custom query
$blog_query = new WP_Query( $custom_query_args );
// Pagination fix
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $blog_query;
?>
<?php if ( $blog_query->have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( $blog_query->have_posts() ) : $blog_query->the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<?php endif; // end have_posts() check ?>
<?php // Reset postdata
wp_reset_postdata();
// Custom query loop pagination
previous_posts_link( 'Older Posts' );
next_posts_link( 'Newer Posts', $blog_query->max_num_pages );
// Reset main query object
$wp_query = NULL;
$wp_query = $temp_query;
?>
</code></pre>
<p>When I click on the pagination link displayed on the frontpage, a 404 Not Found response is shown. (The requested URL /kobopulse/page/2/ was not found on this server.)</p>
<p>I am using the latest version of wordpress. On the settings page my install is configured to display a static front page. Front-page.php is my custom page template for the frontpage</p>
<p>What do I need to do differently.</p>
<p>Thanks</p>
|
[
{
"answer_id": 229601,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 2,
"selected": true,
"text": "<p>File should be <code>single-member_post.php</code> instead of <code>single-memberPost.php</code>.</p>\n\n<p>In <code>single-{posttype}</code> , <code>{post_type}</code> is the <code>$post_type</code> argument of the <code>register_post_type()</code> function.</p>\n\n<p>Never use <code>flush_rewrite_rules();</code> in <code>init</code> use it only on theme/plugin deactivate or activate.</p>\n\n<p>Since this is a theme you can use it on <code>after_switch_theme</code> hook.</p>\n\n<pre><code>add_action( 'init', 'my_cpt_init' );\nfunction register_cpt_member_post() {\n register_post_type( ... );\n}\n\nfunction my_rewrite_flush() {\n register_cpt_member_post();\n flush_rewrite_rules();\n}\nadd_action( 'after_switch_theme', 'my_rewrite_flush' );\n</code></pre>\n"
},
{
"answer_id": 229602,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>Your post type (<code>member_post</code>) doesn't match your template slug (<code>memberPost</code>). Whichever you choose, it must be all lower case.</p>\n"
}
] |
2016/06/13
|
[
"https://wordpress.stackexchange.com/questions/229621",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96667/"
] |
A search on this topic on this site throws up a lot of results claiming to have resolved this issue, but I am having a contrary experience after implementing these guidelines as outlined here:
1. [How to fix pagination for custom loops?](https://wordpress.stackexchange.com/questions/120407/how-to-fix-pagination-for-custom-loops/120408#120408)
2. [Pagination not working on static page](https://wordpress.stackexchange.com/questions/203223/pagination-not-working-on-static-page)
3. <https://stackoverflow.com/questions/14026467/pagination-on-static-front-page-wordpress>
This is my code below:
```
// Get current page and append to custom query parameters array
$custom_query_args['paged'] = get_query_var( 'page' ) ? get_query_var( 'page' ) : 1;
// Define custom query parameters
$custom_query_args = array(
'post_type' => 'post',
'posts_per_page' => '4',
'paged' => $custom_query_args['paged'],
'post_status' => 'published',
'cat' => '1',
);
// Instantiate custom query
$blog_query = new WP_Query( $custom_query_args );
// Pagination fix
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $blog_query;
?>
<?php if ( $blog_query->have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( $blog_query->have_posts() ) : $blog_query->the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<?php endif; // end have_posts() check ?>
<?php // Reset postdata
wp_reset_postdata();
// Custom query loop pagination
previous_posts_link( 'Older Posts' );
next_posts_link( 'Newer Posts', $blog_query->max_num_pages );
// Reset main query object
$wp_query = NULL;
$wp_query = $temp_query;
?>
```
When I click on the pagination link displayed on the frontpage, a 404 Not Found response is shown. (The requested URL /kobopulse/page/2/ was not found on this server.)
I am using the latest version of wordpress. On the settings page my install is configured to display a static front page. Front-page.php is my custom page template for the frontpage
What do I need to do differently.
Thanks
|
File should be `single-member_post.php` instead of `single-memberPost.php`.
In `single-{posttype}` , `{post_type}` is the `$post_type` argument of the `register_post_type()` function.
Never use `flush_rewrite_rules();` in `init` use it only on theme/plugin deactivate or activate.
Since this is a theme you can use it on `after_switch_theme` hook.
```
add_action( 'init', 'my_cpt_init' );
function register_cpt_member_post() {
register_post_type( ... );
}
function my_rewrite_flush() {
register_cpt_member_post();
flush_rewrite_rules();
}
add_action( 'after_switch_theme', 'my_rewrite_flush' );
```
|
229,675 |
<p>Animated gifs are getting more popular on the web (again) and currently there is no good tool for resizing animated gifs. </p>
<p>So I want to disable resizing/generation of image sizes for the gif mimetype and just save the original gif.</p>
<p>Someone that can help me out with this? Which filter to use will be a good start.</p>
|
[
{
"answer_id": 229683,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>currently there is no good tool for resizing animated gifs</p>\n</blockquote>\n\n<p>Resizing of animated gifs is <a href=\"https://askubuntu.com/questions/257831/how-can-i-resize-an-animated-gif-file-using-imagemagick\">supported by ImageMagick</a>, which happens to be the default image library of WordPress. The only thing is WP doesn't support this filter in its default API to ImageMagick.</p>\n\n<p>Fortunately, it is possible to intercept <a href=\"http://codex.wordpress.org/Function_Reference/image_make_intermediate_size\" rel=\"nofollow noreferrer\"><code>image_make_intermediate_size</code></a>, the hook that produces the resized images. Here you could intercept gifs and have them handled in a different way. Perhaps you could take inspiration from <a href=\"https://wordpress.org/plugins/sharpen-resized-images/\" rel=\"nofollow noreferrer\">this image sharpening plugin</a> to see how to apply ImageMagick methods to your images.</p>\n"
},
{
"answer_id": 229724,
"author": "Lasse M. Tvedt",
"author_id": 40819,
"author_profile": "https://wordpress.stackexchange.com/users/40819",
"pm_score": 4,
"selected": true,
"text": "<p>image_make_intermediate_size was not the hook I was looking for, but intermediate_image_sizes_advanced. </p>\n\n<p>Here is a working code: </p>\n\n<pre><code>function disable_upload_sizes( $sizes, $metadata ) {\n\n // Get filetype data.\n $filetype = wp_check_filetype($metadata['file']);\n\n // Check if is gif. \n if($filetype['type'] == 'image/gif') {\n // Unset sizes if file is gif.\n $sizes = array();\n }\n\n // Return sizes you want to create from image (None if image is gif.)\n return $sizes;\n} \nadd_filter('intermediate_image_sizes_advanced', 'disable_upload_sizes', 10, 2); \n</code></pre>\n"
}
] |
2016/06/14
|
[
"https://wordpress.stackexchange.com/questions/229675",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40819/"
] |
Animated gifs are getting more popular on the web (again) and currently there is no good tool for resizing animated gifs.
So I want to disable resizing/generation of image sizes for the gif mimetype and just save the original gif.
Someone that can help me out with this? Which filter to use will be a good start.
|
image\_make\_intermediate\_size was not the hook I was looking for, but intermediate\_image\_sizes\_advanced.
Here is a working code:
```
function disable_upload_sizes( $sizes, $metadata ) {
// Get filetype data.
$filetype = wp_check_filetype($metadata['file']);
// Check if is gif.
if($filetype['type'] == 'image/gif') {
// Unset sizes if file is gif.
$sizes = array();
}
// Return sizes you want to create from image (None if image is gif.)
return $sizes;
}
add_filter('intermediate_image_sizes_advanced', 'disable_upload_sizes', 10, 2);
```
|
229,698 |
<p>On my blog I have a large number of categories >500, so I need to have some kind of checklist which categories are already selected to continue selecting.</p>
<p>For example, if we have cat1, cat2, cat3...cat50, and I selected cat3, cat5, cat7 and cat44, and need to select more of them, I need to have checklist what is already selected (something similar to tags, when you select tag, he is by automation checked and written below tag box).</p>
<p>I hope you understand what I am talking about.</p>
<p>So my question is - any kind of suggestion how to develop this (only suggestion, not whole code) or maybe there is some kind of plugin that I am not aware of?</p>
<p>Thank you</p>
<p><strong>EDIT:</strong></p>
<p><strong><em>I need this in WordPress admin (add new post) screen</em></strong></p>
|
[
{
"answer_id": 229702,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest way would be to add a meta box and use <code>get_the_category_list</code> to show the categories that already have been selected. This only works if you save your post, just like the tags are only shown in their own box after you confirmed them.</p>\n\n<p>If you want to do this on the fly, you will need javascript to fill your metabox. Put a selector on all checkboxes inside the <code>ul</code> that holds the list of categories and display the label in your metabox once the label in the category box is checked.</p>\n"
},
{
"answer_id": 229711,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 4,
"selected": true,
"text": "<p>Here's a script that you can enqueue into your admin panel. It will add a new tab to the category tabs called \"Active\". Whenever a checkbox is checked, it gets added to the \"Active\" tab list, you can also click links in the \"Active\" tab list to remove them ( uncheck them ).</p>\n\n<p><a href=\"https://i.stack.imgur.com/ZEC7W.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZEC7W.jpg\" alt=\"Category Metabox with Active Tab\"></a></p>\n\n<p>Add this as an external script, <code>custom-tabs.js</code> maybe:</p>\n\n<pre><code>jQuery( document ).ready( function( $ ) {\n\n /* Ensure that there are category metaboxes */\n if( $( 'ul.category-tabs' ).length ) {\n var taxonomies = [ 'category', 'tag' ]; /* Taxonomy Slugs ( category and tag are built-in ) */\n\n /* Loop through each category metabox and add a new tab */\n $.each( taxonomies, function( key, taxonomy ) {\n\n /* Add a checkbox listener */\n /* Whenever a checkbox is checked or unchecked, remove 'Active' tab list item */\n $( '#taxonomy-' + taxonomy + ' ul.categorychecklist input[type=\"checkbox\"]' ).change( function() {\n var label = $( this ).parent().text().trim(); /* Grab checkbox label */\n var value = $( this ).val(); /* Grab checkbox value */\n\n /* IF it is checked, add it to the 'Active' tab */\n if( $( this ).is( ':checked' ) ) {\n $( '#' + taxonomy + '-active ul' ).append( '<li data-val=\"' + value + '\"><a href=\"javascript:void(0);\"><span class=\"dashicons dashicons-no-alt\" style=\"font-size:18px;text-decoration:none;margin-right:4px;\"></span>' + label + '</a></li>' );\n\n /* IF it is unchecked, remove it from the 'Active' tab */\n } else {\n $( '#' + taxonomy + '-active li[data-val=\"' + value +'\"]' ).remove();\n }\n } );\n\n /* Add click listener to the newly added 'Active' tab links */\n $( 'div.inside' ).on( 'click', '#' + taxonomy + '-active a', function() {\n var value = $( this ).parent().attr( 'data-val' );\n\n /* Uncheck any values that have the clicked value */\n $( this ).parents( 'div.inside' ).find( 'input[value=\"' + value +'\"]' ).prop( 'checked', false );\n\n /* Remove 'Active' tab link */\n $( this ).parent().remove();\n } );\n\n /* Append an 'Active' tab */\n $( '#' + taxonomy + '-tabs' ).append( '<li><a href=\"#' + taxonomy + '-active\">Active</a></li>' );\n $parent = $( '#' + taxonomy + '-tabs' ).parents( 'div.inside' );\n\n /* Add the 'Active' tab panel and content - display none */\n $parent.find( 'div.tabs-panel:last' ).before( '<div id=\"' + taxonomy + '-active\" class=\"tabs-panel\" style=\"display: none;\"><ul></ul></div>' );\n\n /* IF there are any checked values on load, trigger change. */\n $parent.find( '#' + taxonomy + '-all input:checked' ).each( function() {\n $( this ).trigger( 'change' );\n } );\n\n } );\n\n }\n\n} );\n</code></pre>\n\n<p>Next we can enqueue it into our admin panel:</p>\n\n<pre><code>function load_custom_tabs_scripts() {\n wp_enqueue_script( 'custom_tabs', get_template_directory_uri() . '/scripts/custom-tabs.js' );\n}\nadd_action( 'admin_enqueue_scripts', 'load_custom_tabs_scripts' );\n</code></pre>\n\n<p>Let me know if you run into issues with it.</p>\n"
}
] |
2016/06/14
|
[
"https://wordpress.stackexchange.com/questions/229698",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31498/"
] |
On my blog I have a large number of categories >500, so I need to have some kind of checklist which categories are already selected to continue selecting.
For example, if we have cat1, cat2, cat3...cat50, and I selected cat3, cat5, cat7 and cat44, and need to select more of them, I need to have checklist what is already selected (something similar to tags, when you select tag, he is by automation checked and written below tag box).
I hope you understand what I am talking about.
So my question is - any kind of suggestion how to develop this (only suggestion, not whole code) or maybe there is some kind of plugin that I am not aware of?
Thank you
**EDIT:**
***I need this in WordPress admin (add new post) screen***
|
Here's a script that you can enqueue into your admin panel. It will add a new tab to the category tabs called "Active". Whenever a checkbox is checked, it gets added to the "Active" tab list, you can also click links in the "Active" tab list to remove them ( uncheck them ).
[](https://i.stack.imgur.com/ZEC7W.jpg)
Add this as an external script, `custom-tabs.js` maybe:
```
jQuery( document ).ready( function( $ ) {
/* Ensure that there are category metaboxes */
if( $( 'ul.category-tabs' ).length ) {
var taxonomies = [ 'category', 'tag' ]; /* Taxonomy Slugs ( category and tag are built-in ) */
/* Loop through each category metabox and add a new tab */
$.each( taxonomies, function( key, taxonomy ) {
/* Add a checkbox listener */
/* Whenever a checkbox is checked or unchecked, remove 'Active' tab list item */
$( '#taxonomy-' + taxonomy + ' ul.categorychecklist input[type="checkbox"]' ).change( function() {
var label = $( this ).parent().text().trim(); /* Grab checkbox label */
var value = $( this ).val(); /* Grab checkbox value */
/* IF it is checked, add it to the 'Active' tab */
if( $( this ).is( ':checked' ) ) {
$( '#' + taxonomy + '-active ul' ).append( '<li data-val="' + value + '"><a href="javascript:void(0);"><span class="dashicons dashicons-no-alt" style="font-size:18px;text-decoration:none;margin-right:4px;"></span>' + label + '</a></li>' );
/* IF it is unchecked, remove it from the 'Active' tab */
} else {
$( '#' + taxonomy + '-active li[data-val="' + value +'"]' ).remove();
}
} );
/* Add click listener to the newly added 'Active' tab links */
$( 'div.inside' ).on( 'click', '#' + taxonomy + '-active a', function() {
var value = $( this ).parent().attr( 'data-val' );
/* Uncheck any values that have the clicked value */
$( this ).parents( 'div.inside' ).find( 'input[value="' + value +'"]' ).prop( 'checked', false );
/* Remove 'Active' tab link */
$( this ).parent().remove();
} );
/* Append an 'Active' tab */
$( '#' + taxonomy + '-tabs' ).append( '<li><a href="#' + taxonomy + '-active">Active</a></li>' );
$parent = $( '#' + taxonomy + '-tabs' ).parents( 'div.inside' );
/* Add the 'Active' tab panel and content - display none */
$parent.find( 'div.tabs-panel:last' ).before( '<div id="' + taxonomy + '-active" class="tabs-panel" style="display: none;"><ul></ul></div>' );
/* IF there are any checked values on load, trigger change. */
$parent.find( '#' + taxonomy + '-all input:checked' ).each( function() {
$( this ).trigger( 'change' );
} );
} );
}
} );
```
Next we can enqueue it into our admin panel:
```
function load_custom_tabs_scripts() {
wp_enqueue_script( 'custom_tabs', get_template_directory_uri() . '/scripts/custom-tabs.js' );
}
add_action( 'admin_enqueue_scripts', 'load_custom_tabs_scripts' );
```
Let me know if you run into issues with it.
|
229,713 |
<p>There are few sites i have seen which does not use post id in their permalink structure. becuase of this their url becomes.,</p>
<pre><code>http://example.com/example-content/
</code></pre>
<p>so what happens when user adds new post with same title or slug ?</p>
<p>how does wordpress knows which post to show when both posts are having same url slug ?</p>
<p>which post gets shown when user goes to the link </p>
<pre><code>http://example.com/example-content/
</code></pre>
|
[
{
"answer_id": 229715,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": false,
"text": "<p>As far as I know, you can't have two posts with the same slug. Whenever you attempt to change a post slug to something that already exists, WordPress will append <code>-2</code> to the newest slug to differentiate the two. So, if you already have a post with the slug of <code>test</code> and attempt to create another post with the same slug, WordPress will instead give that slug <code>test-2</code>.</p>\n\n<p>As far as how WordPress knows which post to get... During load, WordPress uses the slug and runs the <a href=\"https://developer.wordpress.org/reference/functions/wp/\"><code>wp()</code></a> function to call a <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\"><code>WP_Query()</code></a> on the requested slug. If it exists then it populates the <a href=\"https://codex.wordpress.org/Function_Reference/$post\"><code>global $post</code></a> and shows content, otherwise it redirects to 404.</p>\n\n<p>That's my understanding on how WordPress loads. Maybe someone else has a better, more in-depth understanding.</p>\n"
},
{
"answer_id": 229716,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Whenever a post is saved WP calls the <a href=\"https://codex.wordpress.org/Function_Reference/wp_unique_post_slug\" rel=\"nofollow\"><code>wp_unique_post_slug</code></a> function that will compute a unique slug, based on the post title and a suffix like -2 if another post has the same title.</p>\n\n<p>However, you can <a href=\"https://developer.wordpress.org/reference/hooks/wp_unique_post_slug/\" rel=\"nofollow\">filter this function</a>, to generate your own slug. So, if you want to mess things up, that's possible.</p>\n"
},
{
"answer_id": 229725,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 3,
"selected": false,
"text": "<p>Extending <a href=\"https://wordpress.stackexchange.com/users/7355/howdy-mcgee\">@Howdy_McGee</a> answer.</p>\n\n<ol>\n<li>First you can not have two post with the same slug (Not title) which explained already in other answers.</li>\n<li>Second you can have page and post with same slug. But you will be able to access only page when your permalink structure is <code>/%postname%/</code>. And there is debate going on this <a href=\"https://core.trac.wordpress.org/ticket/13459\" rel=\"nofollow noreferrer\">ticket#13459</a> about this issue/feature since 6 years :P.</li>\n</ol>\n\n<p>When a request is made WordPress extract the request URI and match with the permalink structure in function <a href=\"https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/class-wp.php#L145\" rel=\"nofollow noreferrer\"><code>parse_request()</code></a>. If a match is found then <a href=\"https://codex.wordpress.org/WordPress_Query_Vars\" rel=\"nofollow noreferrer\"><code>query_vars</code></a> are filled and this information is passed to <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\"><code>WP_Query</code></a> class where actual SQL is prepared and perform to display the result.</p>\n\n<p><strong>In case of page</strong> If it is page WordPress uses <a href=\"https://developer.wordpress.org/reference/functions/get_page_by_path/\" rel=\"nofollow noreferrer\"><code>get_page_by_path</code></a> and retrieve the ID of page to use in SQL query.</p>\n\n<p><strong>In case of post</strong> If it is a post then WordPress uses <code>slug</code> of post in SQL.</p>\n\n<p>In short WordPress does not required post ID (Not in page) when permalink structure is set to <code>/%postname%/</code> it uses the post slug to query database. </p>\n\n<p>Therefore, with same slug of post/page a page is displayed first because with two matches WP check for page request first.</p>\n"
}
] |
2016/06/14
|
[
"https://wordpress.stackexchange.com/questions/229713",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
There are few sites i have seen which does not use post id in their permalink structure. becuase of this their url becomes.,
```
http://example.com/example-content/
```
so what happens when user adds new post with same title or slug ?
how does wordpress knows which post to show when both posts are having same url slug ?
which post gets shown when user goes to the link
```
http://example.com/example-content/
```
|
As far as I know, you can't have two posts with the same slug. Whenever you attempt to change a post slug to something that already exists, WordPress will append `-2` to the newest slug to differentiate the two. So, if you already have a post with the slug of `test` and attempt to create another post with the same slug, WordPress will instead give that slug `test-2`.
As far as how WordPress knows which post to get... During load, WordPress uses the slug and runs the [`wp()`](https://developer.wordpress.org/reference/functions/wp/) function to call a [`WP_Query()`](https://codex.wordpress.org/Class_Reference/WP_Query) on the requested slug. If it exists then it populates the [`global $post`](https://codex.wordpress.org/Function_Reference/$post) and shows content, otherwise it redirects to 404.
That's my understanding on how WordPress loads. Maybe someone else has a better, more in-depth understanding.
|
229,722 |
<p>I'm trying to use <a href="https://wordpress.org/plugins/wp-redis/" rel="nofollow">WP Redis</a> to cache entire <a href="https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/query.php" rel="nofollow">$wp_query</a> object with key is <a href="https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/query.php#L1286" rel="nofollow">$query_vars_hash</a>.</p>
<p>This is how <code>$wp_query</code> was added to <code>$wp_object_cache</code>:</p>
<pre><code>add_action('wp', function($wp)
{
if ( is_admin() ) return;
global $wp_query;
if ( !wp_cache_get($wp_query->query_vars_hash, 'globals') )
{
wp_cache_add($wp_query->query_vars_hash, $wp_query, 'globals');
}
});
</code></pre>
<p>Then, I need to check if a query has already cached before <code>WP_Query</code> can retrieve posts:</p>
<pre><code>add_action('pre_get_posts', function($query)
{
if ( is_admin() ) return;
$cached_query = wp_cache_get($query->query_vars_hash, 'globals');
if ($cached_query)
{
$GLOBALS['wp_query'] = &$cached_query;
return; // Return immediately to prevent retrieving posts again.
}
});
</code></pre>
<p><strong>Problem</strong>:</p>
<p><code>return</code> or <code>exit</code> doesn't work in this case. Then, <code>WP_Query</code> will still hit database to retrieve posts again.</p>
<p><strong>Question</strong>:</p>
<p>Regardless of the plugin, is it possible to completely stop <code>WP_Query</code> retrieving posts?</p>
|
[
{
"answer_id": 229740,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 2,
"selected": false,
"text": "<p>This is PHP question more than a WordPress question.</p>\n\n<p>As <a href=\"https://wordpress.stackexchange.com/users/23970/mark-kaplun\">@Mark</a> commented:</p>\n\n<blockquote>\n <p><em>returning from the action do not return by magic from the calling function</em></p>\n</blockquote>\n\n<p>That is true. Placing <code>return</code> in function mean exit the function and placing return in a PHP file mean exit the file. Do not get confused with PHP construct <code>exit()</code> :P (You might find a better answer on SO about PHP <code>return</code>).</p>\n\n<p>And to answer your question</p>\n\n<p>You can reduce the load of query by fetching a single column instead of full table. Like <a href=\"https://wordpress.stackexchange.com/users/26350/birgire\">@birgire</a> did here <a href=\"https://wordpress.stackexchange.com/a/226074/32475\">Remove the Homepage Query</a></p>\n\n<p>May be a better answer yet to come. I just shared that what I know :)</p>\n"
},
{
"answer_id": 229744,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 5,
"selected": true,
"text": "<p>At the moment, it is not possible.</p>\n\n<p>When <code>'pre_get_posts'</code> runs, is too late to stop <code>WP_Query</code> to perform a query.</p>\n\n<p>WordPress itself, when you try to query a taxonomy that does not exists, adds <code>AND (0 = 1)</code> to the <code>WHERE</code> clause of the SQL query, to ensure it returns no results very quickly...</p>\n\n<p>There's a <a href=\"https://core.trac.wordpress.org/ticket/36687\">trac ticket</a> with a patch that will probably lands in core with WP 4.6, that introduces a new filter: <code>'posts_pre_query'</code>. Returning an array on that filter will make <code>WP_Query</code> stop processing and use the array provided as its posts array.</p>\n\n<p>This could somehow helps you in implementing what you are trying to do.</p>\n\n<p>Waiting fot this, anything you could do is somehow <em>hackish</em>, the <em>trick</em> core itself uses is quite hackish as well.</p>\n\n<p>Recently, I'm starting using a <em>trick</em> when I want to stop WordPress to do things that I can't stop in a clean way: I throw an exception and catch it to continue application flow.</p>\n\n<p>I'll show you an example. Note all the code here is completely untested.</p>\n\n<p>First of all, let's write a custom exception:</p>\n\n<pre><code>class My_StopWpQueryException extends Exception {\n\n private $query;\n\n public static forQuery(WP_Query $query) {\n $instance = new static();\n $instance->query = $query;\n\n return $instance;\n }\n\n public function wpQuery() {\n return $this->query;\n }\n}\n</code></pre>\n\n<p>The exception is designed to act as a sort of <em>DTO</em> to transport a query object, so that in a <code>catch</code> block you can get and use it.</p>\n\n<p>Better explained with code:</p>\n\n<pre><code>function maybe_cached_query(WP_Query $query) {\n $cached_query = wp_cache_get($query->query_vars_hash, 'globals');\n if ($cached_query instanceof WP_Query)\n throw My_StopWpQueryException::forQuery($cached_query);\n}\n\nfunction cached_query_set(WP_Query $query) {\n $GLOBALS['wp_query'] = $query;\n $GLOBALS['wp_the_query'] = $query;\n // maybe some more fine-tuning here...\n}\n\nadd_action('pre_get_posts', function(WP_Query $query) {\n if ($query->is_main_query() && ! is_admin()) {\n try {\n maybe_cached_query($query);\n } catch(My_StopWpQueryException $e) {\n cached_query_set($e->wpQuery());\n }\n }\n});\n</code></pre>\n\n<p>This should more or less work, however, there are a lot of hooks that you are not going to fire, for example <code>\"the_posts\"</code> and much more... if you have code that use one of those hooks to trigger in, it will break.</p>\n\n<p>You can use the <code>cached_query_set</code> function to fire some of the hooks that your theme / plugins may require.</p>\n"
},
{
"answer_id": 229765,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>It will be made possible in 4.6 (assuming no changes till release) with the new <code>posts_pre_query</code> filter <a href=\"https://core.trac.wordpress.org/ticket/36687\" rel=\"nofollow\">https://core.trac.wordpress.org/ticket/36687</a></p>\n"
},
{
"answer_id": 230385,
"author": "OzTheGreat",
"author_id": 76899,
"author_profile": "https://wordpress.stackexchange.com/users/76899",
"pm_score": 2,
"selected": false,
"text": "<p>Yep it's possible depending on what you want to cache. I've done a similar thing to cache the main loop on our homepage. Essentially you can use the <code>posts_request</code> and <code>posts_results</code> to hijack the query and hit the cache instead then also use <code>found_posts</code> to correct the pagination.</p>\n\n<p>Really rough example pulled from our code (untested) but you should help you get the idea:</p>\n\n<pre><code><?php\n/**\n * Kill the query if we have the result in the cache\n * @var [type]\n */\nadd_filter( 'posts_request', function( $request, $query ) {\n if ( is_home() && $query->is_main_query() ) {\n\n $page = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;\n\n $key = 'homepage_query_cache_' . $page;\n\n if ( wp_cache_get( $key, 'cache_group' ) )\n $request = null;\n\n }\n\n return $request;\n}, 10, 2 );\n\n/**\n * Get the result from the cache and set it as the query result\n * Or add the query result to the cache if it's not there\n * @var [type]\n */\nadd_filter( 'posts_results', function( $posts, $query ) {\n\n if ( is_home() && $query->is_main_query() ) {\n\n $page = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;\n\n $key = 'homepage_query_cache_' . $page;\n\n if ( $cached_posts = wp_cache_get( $key, 'cache_group' ) ) {\n $posts = $cached_posts;\n } else {\n wp_cache_set( $key . '_found_posts', $query->found_posts, 'cache_group', HOUR_IN_SECONDS );\n wp_cache_set( $key, $posts, 'cache_group', HOUR_IN_SECONDS );\n }\n }\n\n return $posts;\n\n}, 10, 2 );\n\n/**\n * Correct the found posts number if we've hijacked the query results\n * @var [type]\n */\nadd_filter( 'found_posts', function( $num, $query ) {\n if ( is_home() && $query->is_main_query() ) {\n $page = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;\n\n $key = 'homepage_query_cache_' . $page;\n\n if ( $found_posts = wp_cache_get( $key . '_found_posts', 'cache_group' ) )\n $num = $found_posts;\n }\n\n return $num;\n}, 10, 2 );\n</code></pre>\n\n<p>More here: <a href=\"https://www.reddit.com/r/Wordpress/comments/19crcn/best_practice_for_hijacking_main_loop_and_caching/\" rel=\"nofollow\">https://www.reddit.com/r/Wordpress/comments/19crcn/best_practice_for_hijacking_main_loop_and_caching/</a></p>\n"
}
] |
2016/06/14
|
[
"https://wordpress.stackexchange.com/questions/229722",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92212/"
] |
I'm trying to use [WP Redis](https://wordpress.org/plugins/wp-redis/) to cache entire [$wp\_query](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/query.php) object with key is [$query\_vars\_hash](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/query.php#L1286).
This is how `$wp_query` was added to `$wp_object_cache`:
```
add_action('wp', function($wp)
{
if ( is_admin() ) return;
global $wp_query;
if ( !wp_cache_get($wp_query->query_vars_hash, 'globals') )
{
wp_cache_add($wp_query->query_vars_hash, $wp_query, 'globals');
}
});
```
Then, I need to check if a query has already cached before `WP_Query` can retrieve posts:
```
add_action('pre_get_posts', function($query)
{
if ( is_admin() ) return;
$cached_query = wp_cache_get($query->query_vars_hash, 'globals');
if ($cached_query)
{
$GLOBALS['wp_query'] = &$cached_query;
return; // Return immediately to prevent retrieving posts again.
}
});
```
**Problem**:
`return` or `exit` doesn't work in this case. Then, `WP_Query` will still hit database to retrieve posts again.
**Question**:
Regardless of the plugin, is it possible to completely stop `WP_Query` retrieving posts?
|
At the moment, it is not possible.
When `'pre_get_posts'` runs, is too late to stop `WP_Query` to perform a query.
WordPress itself, when you try to query a taxonomy that does not exists, adds `AND (0 = 1)` to the `WHERE` clause of the SQL query, to ensure it returns no results very quickly...
There's a [trac ticket](https://core.trac.wordpress.org/ticket/36687) with a patch that will probably lands in core with WP 4.6, that introduces a new filter: `'posts_pre_query'`. Returning an array on that filter will make `WP_Query` stop processing and use the array provided as its posts array.
This could somehow helps you in implementing what you are trying to do.
Waiting fot this, anything you could do is somehow *hackish*, the *trick* core itself uses is quite hackish as well.
Recently, I'm starting using a *trick* when I want to stop WordPress to do things that I can't stop in a clean way: I throw an exception and catch it to continue application flow.
I'll show you an example. Note all the code here is completely untested.
First of all, let's write a custom exception:
```
class My_StopWpQueryException extends Exception {
private $query;
public static forQuery(WP_Query $query) {
$instance = new static();
$instance->query = $query;
return $instance;
}
public function wpQuery() {
return $this->query;
}
}
```
The exception is designed to act as a sort of *DTO* to transport a query object, so that in a `catch` block you can get and use it.
Better explained with code:
```
function maybe_cached_query(WP_Query $query) {
$cached_query = wp_cache_get($query->query_vars_hash, 'globals');
if ($cached_query instanceof WP_Query)
throw My_StopWpQueryException::forQuery($cached_query);
}
function cached_query_set(WP_Query $query) {
$GLOBALS['wp_query'] = $query;
$GLOBALS['wp_the_query'] = $query;
// maybe some more fine-tuning here...
}
add_action('pre_get_posts', function(WP_Query $query) {
if ($query->is_main_query() && ! is_admin()) {
try {
maybe_cached_query($query);
} catch(My_StopWpQueryException $e) {
cached_query_set($e->wpQuery());
}
}
});
```
This should more or less work, however, there are a lot of hooks that you are not going to fire, for example `"the_posts"` and much more... if you have code that use one of those hooks to trigger in, it will break.
You can use the `cached_query_set` function to fire some of the hooks that your theme / plugins may require.
|
229,747 |
<p>I have code that wraps every 3 posts in a div (so that the posts will line up horizontally even if different heights). It closes the div after 3 posts, but the problem is the div is left open if there aren't any more posts left but it ended with 1 or 2 in that div row. How can I close the last div?</p>
<pre><code> <?php
if ( have_posts() ) : ?>
<?php $i=1; ?>
<?php
/* Start the Loop */
while ( have_posts() ) : the_post(); ?>
<?php if($i==1 || $i%3==1) echo '<div class="row">' ;?>
<div class="project">
</div> <!-- /.project -->
<?php if($i%3==0) echo '</div>' ;?>
<?php $i++;endwhile;
</code></pre>
|
[
{
"answer_id": 229749,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 0,
"selected": false,
"text": "<p>Something like this should work:</p>\n\n<pre><code><?php\nif ( have_posts() ) { \n\n $i = 1;\n // Always start the list with a div.row \n echo( '<div class=\"row\">' );\n /* Start the Loop */\n while ( have_posts() ) {\n the_post(); \n if( $i%3 == 0 && $i != 1 ) {\n echo '</div>' . PHP_EOL . '<div class=\"row\">';\n }\n ?>\n\n <div class=\"project\">\n </div> <!-- /.project -->\n\n<?php\n\n } // end of the while() loop\n // end the last div.row -- this will always execute if have_posts() is true\n echo( '</div>' ); \n} // end of the if( have_posts() ) conditional\n</code></pre>\n\n<p><strong>Note:</strong> I haven't tested this code.</p>\n"
},
{
"answer_id": 229750,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 1,
"selected": false,
"text": "<p>This is purely PHP which is considered to be Off-topic but this is my take:</p>\n\n<pre><code><?php if ( have_posts() ) : ?>\n\n <?php\n while ( have_posts() ) :\n the_post();\n $i = $wp_query->current_post;\n echo ( 0 == $i % 3 ) ? '<div class=\"row\">' : '';\n ?>\n\n <div class=\"project\">\n </div> <!-- /.project -->\n\n <?php\n echo ( $wp_query->post_count == $i || 2 == $i % 3 ) ? '</div>' : '';\n endwhile;\n ?>\n\n<?php endif; ?>\n</code></pre>\n\n<p>The <code>$wp_query->current_post</code> is a built-in query property that stats at 0 and holds the index of the posts array.</p>\n"
}
] |
2016/06/14
|
[
"https://wordpress.stackexchange.com/questions/229747",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69358/"
] |
I have code that wraps every 3 posts in a div (so that the posts will line up horizontally even if different heights). It closes the div after 3 posts, but the problem is the div is left open if there aren't any more posts left but it ended with 1 or 2 in that div row. How can I close the last div?
```
<?php
if ( have_posts() ) : ?>
<?php $i=1; ?>
<?php
/* Start the Loop */
while ( have_posts() ) : the_post(); ?>
<?php if($i==1 || $i%3==1) echo '<div class="row">' ;?>
<div class="project">
</div> <!-- /.project -->
<?php if($i%3==0) echo '</div>' ;?>
<?php $i++;endwhile;
```
|
This is purely PHP which is considered to be Off-topic but this is my take:
```
<?php if ( have_posts() ) : ?>
<?php
while ( have_posts() ) :
the_post();
$i = $wp_query->current_post;
echo ( 0 == $i % 3 ) ? '<div class="row">' : '';
?>
<div class="project">
</div> <!-- /.project -->
<?php
echo ( $wp_query->post_count == $i || 2 == $i % 3 ) ? '</div>' : '';
endwhile;
?>
<?php endif; ?>
```
The `$wp_query->current_post` is a built-in query property that stats at 0 and holds the index of the posts array.
|
229,755 |
<p>I am working on a WP plugin, and I need to be able to call a URL (specifically an AJAX function) using a button click, but the page refreshes after clicking it, which I think is preventing the AJAX request from finishing.</p>
<p>When the button click is registered, JS is meant to grab the value of an input, combine it to form a URL, then change an iFrame source to that URL (which I think calls it), but this is countermanded by the refreshing of the page.</p>
<p>Code is below:</p>
<pre><code>$intro = get_post_meta($post -> ID, $key = 'podcast_file', true);
?>
<div class="downloadHolder">
<h3>Download <?php echo $post->post_title ?> (<?php echo basename($intro, ".ftb") ?>)</h3>
<a href="<?php echo $intro;?>" download="<?php echo basename($intro) ?>" class="demoBtn">Download <?php echo basename($intro, ".ftb") ?> for PC</a>
<!--<a href="#" class="demoBtn">Demo</a>--><br>
<input type="text" name="emailValue" id="emailValue" placeholder="Email Address" class="emailInput" style="text-align: center;">
<button id="UniqueLevelEmailButton" class="downloadBtn" style="margin-top: 0px; width: 100%;">Email for Mobile</button>
<span>(We do NOT collect email addresses.)</span>
<span id="checkMe"></span>
<script>
jQuery(document).ready(function($){
$("#UniqueLevelEmailButton").click(function(e){
email = document.getElementById('emailValue').value;
downloadurl = '<?php admin_url('admin-ajax.php');?>?action=download_email_send&postId=<?php echo $post->ID; ?>&emailValue='+email;
document.getElementById('emailsendframe').src = downloadurl;
return false;
});
return false;
});
</script>
<!-- iframe for submitting to -->
<iframe name="emailsendframe" id="emailsendframe" src="javascript:void(0);" style="display:none;"></iframe>
</div>
<?php
return ob_get_clean();
}
add_shortcode('level', 'file_download');
/* AJAX */
add_action('wp_ajax_download_email_send','download_email_send');
add_action('wp_ajax_nopriv_download_email_send','download_email_send');
// note $_REQUEST will work with $_POST or $_GET methods
function download_email_send() {
$to = $_REQUEST['emailValue'];
// preferably add some email address format validation here
// $validate = some_email_validate_function($to);
// if ($validated) {$message = 'Please check your email for typos.';}
// else {
$post_id = $_REQUEST['postID'];
$page = get_post($post_id);
$postName = $page->post_title;
// ! you would need to redefine $intro here !
$intro = get_post_meta($post_id, $key = 'podcast_file', true);
$path = str_replace("http://example.com/wp-content","",$intro);
$subject = 'Download for '.$postName;
$msg = 'Your download for '.$postName.' ('.basename($intro).') is attached to this email.';
//Why am I unable to pass HTML in the message?
$headers = 'From: Example <[email protected]>' . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$mail_attachment = array(WP_CONTENT_DIR . $path);
$send = wp_mail($to, $subject, $msg, $headers, $mail_attachment);
if ($send) {$message = 'Success! Your download has been sent to your email address.';}
else {$message = 'Error: Mail sending failed. Please contact the website administrator using the contact page.';}
// }
// alert the user to the result
echo "<script>alert('".$message."');</script>";
exit;
}
</code></pre>
|
[
{
"answer_id": 229758,
"author": "C C",
"author_id": 83299,
"author_profile": "https://wordpress.stackexchange.com/users/83299",
"pm_score": 0,
"selected": false,
"text": "<p>I can't comment on the validity of the AJAX call; it's a different style than I have used -- but inside the <code>click(function(e) {</code> code, you might try trapping the default page action to prevent it from triggering the page refresh:</p>\n\n<pre><code> $(\"#myelement).click(function(e){\n e.preventDefault();\n</code></pre>\n"
},
{
"answer_id": 229759,
"author": "FaCE",
"author_id": 96768,
"author_profile": "https://wordpress.stackexchange.com/users/96768",
"pm_score": 2,
"selected": false,
"text": "<h1>Please do not put this code into production</h1>\n<p>OK. So there are many things wrong with the code that need fixing before we can even begin to answer your question.</p>\n<ol>\n<li><p>Firstly we're using <code>$_REQUEST</code> without good reason -- <code>$_REQUEST</code> gives us access to all of the information sent in the request, which means that <code>$_POST['foo']</code> <code>$_REQUEST['foo']</code> === <code>$_GET['foo']</code> <strong>and also</strong> <code>$_COOKIE['foo']</code>! That means that we are able to request ID's from your application simply by setting a cookie locally.</p>\n</li>\n<li><p>Secondly, we are taking <code>$post_id</code> and doing this with it:</p>\n<p>$post_id = $_REQUEST['postID'];\n...\n$page = get_post($post_id);</p>\n</li>\n</ol>\n<p>Which means that, once we scrutinise the code for <code>[get_post](https://developer.wordpress.org/reference/functions/get_post/)</code> and find that it does no checks for any access rights it means that you are now allowing the user (who you do not know) to get any single 'post' which you have on your website. As WordPress stores <strong>all</strong> post-like objects in the table <code>wp_posts</code> it means that if you use WordPress post types for any kind of protected information, then the user will be able to access this information (in theory) simply by requesting it.</p>\n<ol start=\"3\">\n<li><p>Thirdly, <strong>we are passing an unfiltered variable into a function</strong> <em>a la</em> <code>$intro = get_post_meta($post_id, $key = 'podcast_file', true);</code> – thankfully WordPress filters this input for us</p>\n</li>\n<li><p>Fourthly, we then send the return value of this, <strong>unchecked</strong> to create another variable <code>$path = str_replace("http://com.areonline.co.uk/wp-content","",$intro);</code></p>\n</li>\n<li><p>Fifthly we then use <em>this</em>(<code>$path</code>) variable and email it <strong>as an attachment</strong> to the sender!!!</p>\n</li>\n</ol>\n<hr />\n<p>Other than that, try sending your request using <a href=\"https://api.jquery.com/jquery.post/\" rel=\"nofollow noreferrer\">jQuery.post</a> and also consider creating localised variables using <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\">Localize Script</a> and <strong>(to answer the question)</strong> also use <code>event.preventDefault()</code> on whatever you don't want to happen.</p>\n<p>In this case:</p>\n<pre><code>$("#UniqueLevelEmailButton").click(function(e){\n e.preventDefault();\n // blah\n}\n</code></pre>\n<hr />\n"
}
] |
2016/06/14
|
[
"https://wordpress.stackexchange.com/questions/229755",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92901/"
] |
I am working on a WP plugin, and I need to be able to call a URL (specifically an AJAX function) using a button click, but the page refreshes after clicking it, which I think is preventing the AJAX request from finishing.
When the button click is registered, JS is meant to grab the value of an input, combine it to form a URL, then change an iFrame source to that URL (which I think calls it), but this is countermanded by the refreshing of the page.
Code is below:
```
$intro = get_post_meta($post -> ID, $key = 'podcast_file', true);
?>
<div class="downloadHolder">
<h3>Download <?php echo $post->post_title ?> (<?php echo basename($intro, ".ftb") ?>)</h3>
<a href="<?php echo $intro;?>" download="<?php echo basename($intro) ?>" class="demoBtn">Download <?php echo basename($intro, ".ftb") ?> for PC</a>
<!--<a href="#" class="demoBtn">Demo</a>--><br>
<input type="text" name="emailValue" id="emailValue" placeholder="Email Address" class="emailInput" style="text-align: center;">
<button id="UniqueLevelEmailButton" class="downloadBtn" style="margin-top: 0px; width: 100%;">Email for Mobile</button>
<span>(We do NOT collect email addresses.)</span>
<span id="checkMe"></span>
<script>
jQuery(document).ready(function($){
$("#UniqueLevelEmailButton").click(function(e){
email = document.getElementById('emailValue').value;
downloadurl = '<?php admin_url('admin-ajax.php');?>?action=download_email_send&postId=<?php echo $post->ID; ?>&emailValue='+email;
document.getElementById('emailsendframe').src = downloadurl;
return false;
});
return false;
});
</script>
<!-- iframe for submitting to -->
<iframe name="emailsendframe" id="emailsendframe" src="javascript:void(0);" style="display:none;"></iframe>
</div>
<?php
return ob_get_clean();
}
add_shortcode('level', 'file_download');
/* AJAX */
add_action('wp_ajax_download_email_send','download_email_send');
add_action('wp_ajax_nopriv_download_email_send','download_email_send');
// note $_REQUEST will work with $_POST or $_GET methods
function download_email_send() {
$to = $_REQUEST['emailValue'];
// preferably add some email address format validation here
// $validate = some_email_validate_function($to);
// if ($validated) {$message = 'Please check your email for typos.';}
// else {
$post_id = $_REQUEST['postID'];
$page = get_post($post_id);
$postName = $page->post_title;
// ! you would need to redefine $intro here !
$intro = get_post_meta($post_id, $key = 'podcast_file', true);
$path = str_replace("http://example.com/wp-content","",$intro);
$subject = 'Download for '.$postName;
$msg = 'Your download for '.$postName.' ('.basename($intro).') is attached to this email.';
//Why am I unable to pass HTML in the message?
$headers = 'From: Example <[email protected]>' . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$mail_attachment = array(WP_CONTENT_DIR . $path);
$send = wp_mail($to, $subject, $msg, $headers, $mail_attachment);
if ($send) {$message = 'Success! Your download has been sent to your email address.';}
else {$message = 'Error: Mail sending failed. Please contact the website administrator using the contact page.';}
// }
// alert the user to the result
echo "<script>alert('".$message."');</script>";
exit;
}
```
|
Please do not put this code into production
===========================================
OK. So there are many things wrong with the code that need fixing before we can even begin to answer your question.
1. Firstly we're using `$_REQUEST` without good reason -- `$_REQUEST` gives us access to all of the information sent in the request, which means that `$_POST['foo']` `$_REQUEST['foo']` === `$_GET['foo']` **and also** `$_COOKIE['foo']`! That means that we are able to request ID's from your application simply by setting a cookie locally.
2. Secondly, we are taking `$post_id` and doing this with it:
$post\_id = $\_REQUEST['postID'];
...
$page = get\_post($post\_id);
Which means that, once we scrutinise the code for `[get_post](https://developer.wordpress.org/reference/functions/get_post/)` and find that it does no checks for any access rights it means that you are now allowing the user (who you do not know) to get any single 'post' which you have on your website. As WordPress stores **all** post-like objects in the table `wp_posts` it means that if you use WordPress post types for any kind of protected information, then the user will be able to access this information (in theory) simply by requesting it.
3. Thirdly, **we are passing an unfiltered variable into a function** *a la* `$intro = get_post_meta($post_id, $key = 'podcast_file', true);` – thankfully WordPress filters this input for us
4. Fourthly, we then send the return value of this, **unchecked** to create another variable `$path = str_replace("http://com.areonline.co.uk/wp-content","",$intro);`
5. Fifthly we then use *this*(`$path`) variable and email it **as an attachment** to the sender!!!
---
Other than that, try sending your request using [jQuery.post](https://api.jquery.com/jquery.post/) and also consider creating localised variables using [Localize Script](https://codex.wordpress.org/Function_Reference/wp_localize_script) and **(to answer the question)** also use `event.preventDefault()` on whatever you don't want to happen.
In this case:
```
$("#UniqueLevelEmailButton").click(function(e){
e.preventDefault();
// blah
}
```
---
|
229,761 |
<p>i'm using code from the wordpress codex: (this is the generic version, my code is working though)</p>
<pre><code>$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => array( 'name' => 'bob', 'email' => '[email protected]' ),
'cookies' => array()
)
);
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
echo 'Response:<pre>';
print_r( $response );
echo '</pre>';
}
</code></pre>
<p>I'm trying to figure out how to have a form that users can input their name and email address and then it will submit to us to be added to a newsletter.</p>
<p>So basically i want to have the body entries be dynamic</p>
<p>I was thinking a form like this:</p>
<pre><code><form name="getUserInfo" action="NOT SURE WHAT GOES HERE" method="post">
<input type="text" name="name" />
<input type="email" name="email" />
<input type="submit" name="submit" value="submit"/>
</form>
</code></pre>
<p>but i don't know how to send that to the code</p>
<p>i believe it's along this method where i change this line:</p>
<pre><code>'body' => array( 'name' => 'bob', 'email' => '[email protected]' ),
</code></pre>
<p>to</p>
<pre><code>'body' => array( 'name' => '$namefromform', 'email' => '$emailfromform' ),
</code></pre>
<p>i know i'm missing something but i'm not sure.</p>
<p>Generally speaking i'd like this to run as a widget to make my newsletter signup in the footer of the site.</p>
<p>If anyone is wondering why i need an api for this, it is because the company i'm helping create the website for sends all their contacts to a larger 3rd party contact management system.</p>
|
[
{
"answer_id": 229758,
"author": "C C",
"author_id": 83299,
"author_profile": "https://wordpress.stackexchange.com/users/83299",
"pm_score": 0,
"selected": false,
"text": "<p>I can't comment on the validity of the AJAX call; it's a different style than I have used -- but inside the <code>click(function(e) {</code> code, you might try trapping the default page action to prevent it from triggering the page refresh:</p>\n\n<pre><code> $(\"#myelement).click(function(e){\n e.preventDefault();\n</code></pre>\n"
},
{
"answer_id": 229759,
"author": "FaCE",
"author_id": 96768,
"author_profile": "https://wordpress.stackexchange.com/users/96768",
"pm_score": 2,
"selected": false,
"text": "<h1>Please do not put this code into production</h1>\n<p>OK. So there are many things wrong with the code that need fixing before we can even begin to answer your question.</p>\n<ol>\n<li><p>Firstly we're using <code>$_REQUEST</code> without good reason -- <code>$_REQUEST</code> gives us access to all of the information sent in the request, which means that <code>$_POST['foo']</code> <code>$_REQUEST['foo']</code> === <code>$_GET['foo']</code> <strong>and also</strong> <code>$_COOKIE['foo']</code>! That means that we are able to request ID's from your application simply by setting a cookie locally.</p>\n</li>\n<li><p>Secondly, we are taking <code>$post_id</code> and doing this with it:</p>\n<p>$post_id = $_REQUEST['postID'];\n...\n$page = get_post($post_id);</p>\n</li>\n</ol>\n<p>Which means that, once we scrutinise the code for <code>[get_post](https://developer.wordpress.org/reference/functions/get_post/)</code> and find that it does no checks for any access rights it means that you are now allowing the user (who you do not know) to get any single 'post' which you have on your website. As WordPress stores <strong>all</strong> post-like objects in the table <code>wp_posts</code> it means that if you use WordPress post types for any kind of protected information, then the user will be able to access this information (in theory) simply by requesting it.</p>\n<ol start=\"3\">\n<li><p>Thirdly, <strong>we are passing an unfiltered variable into a function</strong> <em>a la</em> <code>$intro = get_post_meta($post_id, $key = 'podcast_file', true);</code> – thankfully WordPress filters this input for us</p>\n</li>\n<li><p>Fourthly, we then send the return value of this, <strong>unchecked</strong> to create another variable <code>$path = str_replace("http://com.areonline.co.uk/wp-content","",$intro);</code></p>\n</li>\n<li><p>Fifthly we then use <em>this</em>(<code>$path</code>) variable and email it <strong>as an attachment</strong> to the sender!!!</p>\n</li>\n</ol>\n<hr />\n<p>Other than that, try sending your request using <a href=\"https://api.jquery.com/jquery.post/\" rel=\"nofollow noreferrer\">jQuery.post</a> and also consider creating localised variables using <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\">Localize Script</a> and <strong>(to answer the question)</strong> also use <code>event.preventDefault()</code> on whatever you don't want to happen.</p>\n<p>In this case:</p>\n<pre><code>$("#UniqueLevelEmailButton").click(function(e){\n e.preventDefault();\n // blah\n}\n</code></pre>\n<hr />\n"
}
] |
2016/06/14
|
[
"https://wordpress.stackexchange.com/questions/229761",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77767/"
] |
i'm using code from the wordpress codex: (this is the generic version, my code is working though)
```
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => array( 'name' => 'bob', 'email' => '[email protected]' ),
'cookies' => array()
)
);
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
echo 'Response:<pre>';
print_r( $response );
echo '</pre>';
}
```
I'm trying to figure out how to have a form that users can input their name and email address and then it will submit to us to be added to a newsletter.
So basically i want to have the body entries be dynamic
I was thinking a form like this:
```
<form name="getUserInfo" action="NOT SURE WHAT GOES HERE" method="post">
<input type="text" name="name" />
<input type="email" name="email" />
<input type="submit" name="submit" value="submit"/>
</form>
```
but i don't know how to send that to the code
i believe it's along this method where i change this line:
```
'body' => array( 'name' => 'bob', 'email' => '[email protected]' ),
```
to
```
'body' => array( 'name' => '$namefromform', 'email' => '$emailfromform' ),
```
i know i'm missing something but i'm not sure.
Generally speaking i'd like this to run as a widget to make my newsletter signup in the footer of the site.
If anyone is wondering why i need an api for this, it is because the company i'm helping create the website for sends all their contacts to a larger 3rd party contact management system.
|
Please do not put this code into production
===========================================
OK. So there are many things wrong with the code that need fixing before we can even begin to answer your question.
1. Firstly we're using `$_REQUEST` without good reason -- `$_REQUEST` gives us access to all of the information sent in the request, which means that `$_POST['foo']` `$_REQUEST['foo']` === `$_GET['foo']` **and also** `$_COOKIE['foo']`! That means that we are able to request ID's from your application simply by setting a cookie locally.
2. Secondly, we are taking `$post_id` and doing this with it:
$post\_id = $\_REQUEST['postID'];
...
$page = get\_post($post\_id);
Which means that, once we scrutinise the code for `[get_post](https://developer.wordpress.org/reference/functions/get_post/)` and find that it does no checks for any access rights it means that you are now allowing the user (who you do not know) to get any single 'post' which you have on your website. As WordPress stores **all** post-like objects in the table `wp_posts` it means that if you use WordPress post types for any kind of protected information, then the user will be able to access this information (in theory) simply by requesting it.
3. Thirdly, **we are passing an unfiltered variable into a function** *a la* `$intro = get_post_meta($post_id, $key = 'podcast_file', true);` – thankfully WordPress filters this input for us
4. Fourthly, we then send the return value of this, **unchecked** to create another variable `$path = str_replace("http://com.areonline.co.uk/wp-content","",$intro);`
5. Fifthly we then use *this*(`$path`) variable and email it **as an attachment** to the sender!!!
---
Other than that, try sending your request using [jQuery.post](https://api.jquery.com/jquery.post/) and also consider creating localised variables using [Localize Script](https://codex.wordpress.org/Function_Reference/wp_localize_script) and **(to answer the question)** also use `event.preventDefault()` on whatever you don't want to happen.
In this case:
```
$("#UniqueLevelEmailButton").click(function(e){
e.preventDefault();
// blah
}
```
---
|
229,767 |
<p>I'm trying to show WooCommerce Product Categories, Post Categories, Product Tags, Post Tags and Custom Taxonomy posts count in main navigation using wp_nav_menu.</p>
<p>My WP_NAV_MENU code</p>
<pre><code> <?php if( has_nav_menu( 'primary_menu' ) ) : ?>
<?php
$primary_args = array(
'theme_location' => 'primary_menu',
'echo' => false,
'depth' => 3,
'container' => false,
'menu_class' => 'header-menu',
'menu_id' => 'header-menu'
);
wp_nav_menu( $primary_args );
?>
<?php endif; ?>
</code></pre>
<p>I added the following code into my child-theme functions.php</p>
<pre><code>apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
add_action( 'walker_nav_menu_start_el', 'menu_post_count', 10, 4 );
function menu_post_count( $output, $item, $depth, $args )
{
// Check $item and get the data you need
printf( '<pre>%s</pre>', var_export( $item, true ) );
// Then append whatever you need to the $output
$output .= '';
return $output;
}
</code></pre>
<p>This caused error on site showing the data of the category as following.</p>
<pre><code>WP_Post::__set_state(array(
'ID' => 153,
'post_author' => '1',
'post_date' => '2015-12-22 21:52:07',
'post_date_gmt' => '2015-12-22 19:52:07',
'post_content' => ' ',
'post_title' => '',
'post_excerpt' => '',
'post_status' => 'publish',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_password' => '',
'post_name' => '153',
'to_ping' => '',
'pinged' => '',
'post_modified' => '2015-12-29 08:47:30',
'post_modified_gmt' => '2015-12-29 06:47:30',
'post_content_filtered' => '',
'post_parent' => 0,
'guid' => 'http://domain.com/?p=153',
'menu_order' => 1,
'post_type' => 'nav_menu_item',
'post_mime_type' => '',
'comment_count' => '0',
'filter' => 'raw',
'db_id' => 153,
'menu_item_parent' => '0',
'object_id' => '39',
'object' => 'page',
'type' => 'post_type',
'type_label' => 'page',
'url' => 'http://domain.com/',
'title' => 'homepage',
'target' => '',
'attr_title' => '',
'description' => '',
'classes' =>
</code></pre>
|
[
{
"answer_id": 230512,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 2,
"selected": false,
"text": "<p>Alright so this isn't too difficult, first we will just check if the menu item is a taxonomy then get the count and display it!</p>\n\n<pre><code>function ggstyle_menu_item_count( $output, $item, $depth, $args ) {\n // Check if the item is a Category or Custom Taxonomy\n if( $item->type == 'taxonomy' ) {\n $object = get_term($item->object_id, $item->object);\n\n // Check count, if more than 0 display count\n if($object->count > 0)\n $output .= \"<span class='menu-item-count'>\".$object->count.\"</span>\";\n } \n\n return $output;\n}\nadd_action( 'walker_nav_menu_start_el', 'ggstyle_menu_item_count', 10, 4 );\n</code></pre>\n\n<h2>Edit</h2>\n\n<p>To get the Item count to output into the <code><a></code> of the menu item we will have to split up the $output and insert our content the put it back together.</p>\n\n<pre><code>function ggstyle_menu_item_count( $output, $item, $depth, $args ) {\n // Check if the item is a Category or Custom Taxonomy\n if( $item->type == 'taxonomy' ) {\n $object = get_term($item->object_id, $item->object);\n\n // Check count, if more than 0 display count\n if($object->count > 0) {\n $output_new = '';\n $output_split = str_split($output, strpos($output, '</a>') );\n $output_new .= $output_split[0] . \"<span class='menu-item-count'>\".$object->count.\"</span>\" . $output_split[1];\n $output = $output_new;\n }\n } \n\n return $output;\n}\nadd_action( 'walker_nav_menu_start_el', 'ggstyle_menu_item_count', 10, 4 );\n</code></pre>\n"
},
{
"answer_id": 409417,
"author": "Esterel WEB",
"author_id": 225706,
"author_profile": "https://wordpress.stackexchange.com/users/225706",
"pm_score": 0,
"selected": false,
"text": "<p>@ngearing\nThank you for the proposed solution, I would like to improve it a little :</p>\n<ul>\n<li>add brackets ( and ) before and after the count number</li>\n<li>be able to apply this code only to one of the menus (name Categories) of the site</li>\n</ul>\n<p>Would you be so kind as to propose an edit for these two ?</p>\n<p>Thanks a lot</p>\n"
}
] |
2016/06/15
|
[
"https://wordpress.stackexchange.com/questions/229767",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84518/"
] |
I'm trying to show WooCommerce Product Categories, Post Categories, Product Tags, Post Tags and Custom Taxonomy posts count in main navigation using wp\_nav\_menu.
My WP\_NAV\_MENU code
```
<?php if( has_nav_menu( 'primary_menu' ) ) : ?>
<?php
$primary_args = array(
'theme_location' => 'primary_menu',
'echo' => false,
'depth' => 3,
'container' => false,
'menu_class' => 'header-menu',
'menu_id' => 'header-menu'
);
wp_nav_menu( $primary_args );
?>
<?php endif; ?>
```
I added the following code into my child-theme functions.php
```
apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
add_action( 'walker_nav_menu_start_el', 'menu_post_count', 10, 4 );
function menu_post_count( $output, $item, $depth, $args )
{
// Check $item and get the data you need
printf( '<pre>%s</pre>', var_export( $item, true ) );
// Then append whatever you need to the $output
$output .= '';
return $output;
}
```
This caused error on site showing the data of the category as following.
```
WP_Post::__set_state(array(
'ID' => 153,
'post_author' => '1',
'post_date' => '2015-12-22 21:52:07',
'post_date_gmt' => '2015-12-22 19:52:07',
'post_content' => ' ',
'post_title' => '',
'post_excerpt' => '',
'post_status' => 'publish',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_password' => '',
'post_name' => '153',
'to_ping' => '',
'pinged' => '',
'post_modified' => '2015-12-29 08:47:30',
'post_modified_gmt' => '2015-12-29 06:47:30',
'post_content_filtered' => '',
'post_parent' => 0,
'guid' => 'http://domain.com/?p=153',
'menu_order' => 1,
'post_type' => 'nav_menu_item',
'post_mime_type' => '',
'comment_count' => '0',
'filter' => 'raw',
'db_id' => 153,
'menu_item_parent' => '0',
'object_id' => '39',
'object' => 'page',
'type' => 'post_type',
'type_label' => 'page',
'url' => 'http://domain.com/',
'title' => 'homepage',
'target' => '',
'attr_title' => '',
'description' => '',
'classes' =>
```
|
Alright so this isn't too difficult, first we will just check if the menu item is a taxonomy then get the count and display it!
```
function ggstyle_menu_item_count( $output, $item, $depth, $args ) {
// Check if the item is a Category or Custom Taxonomy
if( $item->type == 'taxonomy' ) {
$object = get_term($item->object_id, $item->object);
// Check count, if more than 0 display count
if($object->count > 0)
$output .= "<span class='menu-item-count'>".$object->count."</span>";
}
return $output;
}
add_action( 'walker_nav_menu_start_el', 'ggstyle_menu_item_count', 10, 4 );
```
Edit
----
To get the Item count to output into the `<a>` of the menu item we will have to split up the $output and insert our content the put it back together.
```
function ggstyle_menu_item_count( $output, $item, $depth, $args ) {
// Check if the item is a Category or Custom Taxonomy
if( $item->type == 'taxonomy' ) {
$object = get_term($item->object_id, $item->object);
// Check count, if more than 0 display count
if($object->count > 0) {
$output_new = '';
$output_split = str_split($output, strpos($output, '</a>') );
$output_new .= $output_split[0] . "<span class='menu-item-count'>".$object->count."</span>" . $output_split[1];
$output = $output_new;
}
}
return $output;
}
add_action( 'walker_nav_menu_start_el', 'ggstyle_menu_item_count', 10, 4 );
```
|
229,772 |
<p>I don't want to style the default widget with only CSS. I want to display the default 'Categories' widget content with my own HTML structure. </p>
<p>Is there available any filter or hook to do that?</p>
|
[
{
"answer_id": 229781,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 5,
"selected": true,
"text": "<p>To expand on Mark's answer, there's not much (generally) available in the way of filters in the default WordPress widgets (except for perhaps <code>widget_text</code>).</p>\n\n<p>But adding your own custom widget is easy - put this in your <code>functions.php</code>:</p>\n\n<pre><code>require_once(\"my_widget.php\");\nadd_action(\"widgets_init\", \"my_custom_widgets_init\");\n\nfunction my_custom_widgets_init(){\n register_widget(\"My_Custom_Widget_Class\");\n}\n</code></pre>\n\n<p>Then you simply want to copy the existing categories widget from <code>wp-includes/widgets/class-wp-widget-categories.php</code> to <code>my_widget.php</code> in your theme, and change the class name to the same name as that used in the call to <code>register_widget()</code> above.</p>\n\n<p>Then make whatever changes you like! I suggest changing the title too so you can distinguish it from the default Categories widget.</p>\n"
},
{
"answer_id": 229782,
"author": "Boris Kuzmanov",
"author_id": 68965,
"author_profile": "https://wordpress.stackexchange.com/users/68965",
"pm_score": 4,
"selected": false,
"text": "<p>You can override the default WordPress widgets by extending them. The code for the default Categories widget can be found on the following link: <a href=\"https://developer.wordpress.org/reference/classes/wp_widget_categories/widget/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/classes/wp_widget_categories/widget/</a></p>\n\n<p>and below is an example code how you can override the output of the widget.</p>\n\n<pre><code>Class My_Categories_Widget extends WP_Widget_Categories {\n function widget( $args, $instance ) {\n // your code here for overriding the output of the widget\n }\n}\n\nfunction my_categories_widget_register() {\n unregister_widget( 'WP_Widget_Categories' );\n register_widget( 'My_Categories_Widget' );\n}\nadd_action( 'widgets_init', 'my_categories_widget_register' );\n</code></pre>\n"
},
{
"answer_id": 229810,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": false,
"text": "<p>You do not need to create a complete new widget to do what you need to do. As I read your question, you are just interested in changing how the categories are displayed on the front end. There are two functions that displays the categories on the front end</p>\n<ul>\n<li><p><a href=\"https://developer.wordpress.org/reference/functions/wp_list_categories/\" rel=\"nofollow noreferrer\"><code>wp_list_categories()</code></a> which displays the categories in a list</p>\n</li>\n<li><p><a href=\"https://developer.wordpress.org/reference/functions/wp_dropdown_categories/\" rel=\"nofollow noreferrer\"><code>wp_dropdown_categories()</code></a> which displays categories in a dropdown list</p>\n</li>\n</ul>\n<p>This all depends on what option was selected in the backend</p>\n<p>Now, each of these two functions have a widget specific filter (<em><code>widget_categories_args</code> and <code>widget_categories_dropdown_args</code> respectively</em>) which you can use to alter the arguments that should be passed to these functions. You can use this to alter the behavior of the list/dropdown. However, this may not be sufficient to do what you want.</p>\n<p>Alternatively, each function has its own filter to completely alter the way how these functions should display their output.</p>\n<p>They respectively are</p>\n<ul>\n<li><p><a href=\"https://developer.wordpress.org/reference/hooks/wp_list_categories/\" rel=\"nofollow noreferrer\"><code>wp_list_categories</code></a></p>\n</li>\n<li><p><a href=\"https://developer.wordpress.org/reference/hooks/wp_dropdown_cats/\" rel=\"nofollow noreferrer\"><code>wp_dropdown_cats</code></a></p>\n</li>\n</ul>\n<p>We can use the <code>widget_title</code> filter to specifically target the widget only and not other instances of these functions.</p>\n<p>In short, you can try the following: (<em>TOTALLY UNTESTED</em>)</p>\n<pre><code>add_filter( 'widget_title', function( $title, $instance, $id_base )\n{\n // Target the categories base\n if( 'categories' === $id_base ) // Just make sure the base is correct, I'm not sure here\n add_filter( 'wp_list_categories', 'wpse_229772_categories', 11, 2 );\n //add_filter( 'wp_dropdown_cats', 'wpse_229772_categories', 11, 2 );\n return $title;\n}, 10, 3 );\n\nfunction wpse_229772_categories( $output, $args )\n{\n // Only run the filter once\n remove_filter( current_filter(), __FUNCTION__ );\n\n // Get all the categories\n $categories = get_categories( $args );\n\n $output = '';\n // Just an example of custom html\n $output .= '<div class="some class">';\n foreach ( $categories as $category ) {\n // Just an example of custom html\n $output .= '<div class="' . $category->term_id . '">';\n // You can add any other info here, like a link to the category\n $output .= $category->name;\n // etc ect, you get the drift\n $output .= '</div>';\n }\n $output .= '</div>';\n\n return $output;\n};\n \n</code></pre>\n"
}
] |
2016/06/15
|
[
"https://wordpress.stackexchange.com/questions/229772",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75264/"
] |
I don't want to style the default widget with only CSS. I want to display the default 'Categories' widget content with my own HTML structure.
Is there available any filter or hook to do that?
|
To expand on Mark's answer, there's not much (generally) available in the way of filters in the default WordPress widgets (except for perhaps `widget_text`).
But adding your own custom widget is easy - put this in your `functions.php`:
```
require_once("my_widget.php");
add_action("widgets_init", "my_custom_widgets_init");
function my_custom_widgets_init(){
register_widget("My_Custom_Widget_Class");
}
```
Then you simply want to copy the existing categories widget from `wp-includes/widgets/class-wp-widget-categories.php` to `my_widget.php` in your theme, and change the class name to the same name as that used in the call to `register_widget()` above.
Then make whatever changes you like! I suggest changing the title too so you can distinguish it from the default Categories widget.
|
229,841 |
<p>For example, if I'm building a list in a plugin that loops over an array to produce a list <code>ul</code> or <code>ol</code>. I typically see code as follows. </p>
<pre><code>foreach($list as $item) {
$output .= '<li>' . $item['value'] . '</li>';
}
</code></pre>
<p>I guess I'm looking to see if there is a comparable to such functions in the Drupal world such as <code>theme_list()</code> (<a href="https://api.drupal.org/api/drupal/includes!theme.inc/function/theme_item_list/7.x" rel="nofollow">reference</a>). I'm looking to give my list of items to a function and have it write the HTML block in a standardized way. </p>
|
[
{
"answer_id": 229848,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": true,
"text": "<p>There are specific functions like <a href=\"https://developer.wordpress.org/reference/functions/wp_list_categories/\" rel=\"nofollow\"><code>wp_list_categories()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/wp_list_pages/\" rel=\"nofollow\"><code>wp_list_pages()</code></a> along with <a href=\"https://developer.wordpress.org/?s=wp_list&post_type%5B%5D=wp-parser-function\" rel=\"nofollow\">some others</a> which will do this for you but for arbitrary arrays, WordPress doesn't have a function to neatly print it out into HTML for you. You could simply write your own functions for this purpose if you really need to I guess.</p>\n"
},
{
"answer_id": 229853,
"author": "diggy",
"author_id": 25765,
"author_profile": "https://wordpress.stackexchange.com/users/25765",
"pm_score": 2,
"selected": false,
"text": "<p>For tree-like structures (e.g. nested lists) you can extend the <code>Walker</code> class: <a href=\"https://codex.wordpress.org/Class_Reference/Walker\" rel=\"nofollow\">https://codex.wordpress.org/Class_Reference/Walker</a></p>\n"
}
] |
2016/06/15
|
[
"https://wordpress.stackexchange.com/questions/229841",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33401/"
] |
For example, if I'm building a list in a plugin that loops over an array to produce a list `ul` or `ol`. I typically see code as follows.
```
foreach($list as $item) {
$output .= '<li>' . $item['value'] . '</li>';
}
```
I guess I'm looking to see if there is a comparable to such functions in the Drupal world such as `theme_list()` ([reference](https://api.drupal.org/api/drupal/includes!theme.inc/function/theme_item_list/7.x)). I'm looking to give my list of items to a function and have it write the HTML block in a standardized way.
|
There are specific functions like [`wp_list_categories()`](https://developer.wordpress.org/reference/functions/wp_list_categories/) and [`wp_list_pages()`](https://developer.wordpress.org/reference/functions/wp_list_pages/) along with [some others](https://developer.wordpress.org/?s=wp_list&post_type%5B%5D=wp-parser-function) which will do this for you but for arbitrary arrays, WordPress doesn't have a function to neatly print it out into HTML for you. You could simply write your own functions for this purpose if you really need to I guess.
|
229,867 |
<p>I'm using this function right now in my theme to show each project's custom taxonomy. In this case, the custom taxonomy is <code>tipo_de_tarea</code>:</p>
<pre><code>echo get_the_term_list( $post->ID, 'tipo_de_tarea' );
</code></pre>
<p>I have various tipo_de_tareas. I would like the function to display a shorter name, instead of the complete name of each taxonomy, for example:</p>
<ul>
<li>Apuntes => AP</li>
<li>Ejercicios => EJ</li>
</ul>
<p>As I show in this example, the left side has the current design, and the right has the wished:</p>
<p><a href="https://i.stack.imgur.com/xsQuD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xsQuD.png" alt="enter image description here"></a></p>
<p>I guess that I need to add <code>if</code> conditions for each tipo de tarea and the wished name, but how can I do this? I don't know the code for this.</p>
<p>Also, I would like each one to have a different class that can be assigned a different background color for each one.</p>
|
[
{
"answer_id": 229872,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 1,
"selected": false,
"text": "<p>You could use <code>get_terms()</code> and loop through it - using the term description as the \"short name\" and slug as the specific class ( or you could use an array of colors of your choice ). Let's look at a quick example:</p>\n\n<pre><code><?php\n $terms = wp_get_post_terms( $post_id, 'category' );\n\n if( ! empty( $terms ) ) : ?>\n\n <?php foreach( $terms as $term ) : ?>\n\n <div class=\"<?php echo $term->slug; ?>\"><?php echo $term->description; ?></div>\n\n <?php endforeach; ?>\n\n<?php\n endif;\n?>\n</code></pre>\n\n<p>If you wanted to make a list out of it or <a href=\"https://developer.wordpress.org/reference/functions/get_term_link/\" rel=\"nofollow\">link from it</a> you have full control over the HTML - let me know if you have questions about the markup.</p>\n"
},
{
"answer_id": 230033,
"author": "David13_13",
"author_id": 96838,
"author_profile": "https://wordpress.stackexchange.com/users/96838",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for your help. I found finally help in another place and I'm now using these functions in functions.php:</p>\n\n<pre><code> // A callback function to add a custom field to our \"presenters\" taxonomy \nfunction presenters_taxonomy_custom_fields($tag) { \n // Check for existing taxonomy meta for the term you're editing \n $t_id = $tag->term_id; // Get the ID of the term you're editing \n $term_meta = get_option( \"taxonomy_term_$t_id\" ); // Do the check \n?> \n\n<tr class=\"form-field\"> \n <th scope=\"row\" valign=\"top\"> \n <label for=\"abreviatura\"><?php _e('Abreviatura'); ?></label> \n </th> \n <td> \n <input type=\"text\" name=\"term_meta[abreviatura]\" id=\"term_meta[abreviatura]\" size=\"25\" style=\"width:60%;\" value=\"<?php echo $term_meta['abreviatura'] ? $term_meta['abreviatura'] : ''; ?>\"><br /> \n <span class=\"description\"><?php _e('Abreviatura del tipo de tarea'); ?></span> \n </td> \n</tr> \n\n<?php \n} \n\n// A callback function to save our extra taxonomy field(s) \nfunction save_taxonomy_custom_fields( $term_id ) { \n if ( isset( $_POST['term_meta'] ) ) { \n $t_id = $term_id; \n $term_meta = get_option( \"taxonomy_term_$t_id\" ); \n $cat_keys = array_keys( $_POST['term_meta'] ); \n foreach ( $cat_keys as $key ){ \n if ( isset( $_POST['term_meta'][$key] ) ){ \n $term_meta[$key] = $_POST['term_meta'][$key]; \n } \n } \n //save the option array \n update_option( \"taxonomy_term_$t_id\", $term_meta ); \n } \n} \n\n// Add the fields to the \"presenters\" taxonomy, using our callback function \nadd_action( 'tipo_de_tarea_edit_form_fields', 'presenters_taxonomy_custom_fields', 10, 2 ); \n\n// Save the changes made on the \"presenters\" taxonomy, using our callback function \nadd_action( 'edited_tipo_de_tarea', 'save_taxonomy_custom_fields', 10, 2 ); \n</code></pre>\n\n<p>And I call the code with:</p>\n\n<pre><code> <?php\n$terms = get_the_terms( $post->ID, 'tipo_de_tarea' );\nif ($terms && !is_wp_error($terms)): \n foreach($terms as $term): ?>\n <a href=\"<?php echo get_term_link( $term->slug, 'tipo_de_tarea'); ?>\" rel=\"tag\" class=\"<?php echo $term->slug; ?>\" title=\"<?php echo $term->name; ?>\"><?php echo $term->abreviatura; ?></a>\n <?php\n endforeach;\nendif; \n?>\n</code></pre>\n\n<p>But there is some problem with the functions and I only see a blank column...</p>\n\n<p>Anyone knows where is the problem?</p>\n\n<p>Thanks!</p>\n"
}
] |
2016/06/15
|
[
"https://wordpress.stackexchange.com/questions/229867",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96838/"
] |
I'm using this function right now in my theme to show each project's custom taxonomy. In this case, the custom taxonomy is `tipo_de_tarea`:
```
echo get_the_term_list( $post->ID, 'tipo_de_tarea' );
```
I have various tipo\_de\_tareas. I would like the function to display a shorter name, instead of the complete name of each taxonomy, for example:
* Apuntes => AP
* Ejercicios => EJ
As I show in this example, the left side has the current design, and the right has the wished:
[](https://i.stack.imgur.com/xsQuD.png)
I guess that I need to add `if` conditions for each tipo de tarea and the wished name, but how can I do this? I don't know the code for this.
Also, I would like each one to have a different class that can be assigned a different background color for each one.
|
You could use `get_terms()` and loop through it - using the term description as the "short name" and slug as the specific class ( or you could use an array of colors of your choice ). Let's look at a quick example:
```
<?php
$terms = wp_get_post_terms( $post_id, 'category' );
if( ! empty( $terms ) ) : ?>
<?php foreach( $terms as $term ) : ?>
<div class="<?php echo $term->slug; ?>"><?php echo $term->description; ?></div>
<?php endforeach; ?>
<?php
endif;
?>
```
If you wanted to make a list out of it or [link from it](https://developer.wordpress.org/reference/functions/get_term_link/) you have full control over the HTML - let me know if you have questions about the markup.
|
229,905 |
<p>I enabled <a href="https://codex.wordpress.org/Function_Reference/add_theme_support#Custom_Logo"><code>custom-logo</code></a> for my theme and have it printed with <code><?php the_custom_logo(); ?></code> into the header. Is there any chance to simply add some more classes to this image directly? Per default it only comes with <code>custom-logo</code>.</p>
|
[
{
"answer_id": 229909,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 2,
"selected": false,
"text": "<p>I think I found one answer. But I really wonder if this is the right way? It feels a little bit dirty somehow: I simply copied the logo related parts from wp-includes/general-template.php into my theme's functions.php and renamed the functions with some custom classes added:</p>\n\n<pre><code>function FOOBAR_get_custom_logo( $blog_id = 0 ) {\n $html = '';\n\n if ( is_multisite() && (int) $blog_id !== get_current_blog_id() ) {\n switch_to_blog( $blog_id );\n }\n\n $custom_logo_id = get_theme_mod( 'custom_logo' );\n\n if ( $custom_logo_id ) {\n $html = sprintf( '<a href=\"%1$s\" class=\"custom-logo-link\" rel=\"home\" itemprop=\"url\">%2$s</a>',\n esc_url( home_url( '/' ) ),\n wp_get_attachment_image( $custom_logo_id, 'full', false, array(\n 'class' => 'custom-logo FOO-BAR FOO BAR', // added classes here\n 'itemprop' => 'logo',\n ) )\n );\n }\n\n elseif ( is_customize_preview() ) {\n $html = sprintf( '<a href=\"%1$s\" class=\"custom-logo-link\" style=\"display:none;\"><img class=\"custom-logo\"/></a>',\n esc_url( home_url( '/' ) )\n );\n }\n\n if ( is_multisite() && ms_is_switched() ) {\n restore_current_blog();\n }\n\n return apply_filters( 'FOOBAR_get_custom_logo', $html );\n}\n\nfunction FOOBAR_the_custom_logo( $blog_id = 0 ) {\n echo FOOBAR_get_custom_logo( $blog_id );\n}\n</code></pre>\n"
},
{
"answer_id": 229910,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": false,
"text": "<p>As you found yourself <code>the_custom_logo</code> relies on <a href=\"https://developer.wordpress.org/reference/functions/get_custom_logo/\"><code>get_custom_logo</code></a>, which itself calls <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image/\"><code>wp_get_attachment_image</code></a> to add the <code>custom-logo</code> class. The latter function has a filter, <a href=\"https://developer.wordpress.org/reference/hooks/wp_get_attachment_image_attributes/\"><code>wp_get_attachment_image_attributes</code></a> which you can use to manipulate the image attributes.</p>\n\n<p>So what you could do is build a filter that checks if the <code>custom-logo</code> class is there and if yes add more classes.</p>\n"
},
{
"answer_id": 229911,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": false,
"text": "<p>Here's one suggestion how we might try to add classes through the <code>wp_get_attachment_image_attributes</code> filter (untested):</p>\n\n<pre><code>add_filter( 'wp_get_attachment_image_attributes', function( $attr )\n{\n if( isset( $attr['class'] ) && 'custom-logo' === $attr['class'] )\n $attr['class'] = 'custom-logo foo-bar foo bar';\n\n return $attr;\n} );\n</code></pre>\n\n<p>where you adjust the classes to your needs.</p>\n"
},
{
"answer_id": 230089,
"author": "Dhinju Divakaran",
"author_id": 96981,
"author_profile": "https://wordpress.stackexchange.com/users/96981",
"pm_score": 6,
"selected": true,
"text": "<p>WordPress provide a filter hook to custom logo customization. The hook <code>get_custom_logo</code> is the filter. To change logo class, this code may help you.</p>\n\n<pre><code>add_filter( 'get_custom_logo', 'change_logo_class' );\n\n\nfunction change_logo_class( $html ) {\n\n $html = str_replace( 'custom-logo', 'your-custom-class', $html );\n $html = str_replace( 'custom-logo-link', 'your-custom-class', $html );\n\n return $html;\n}\n</code></pre>\n\n<p>Reference: <a href=\"http://www.mavengang.com/2016/06/02/change-wordpress-custom-logo-class/\" rel=\"noreferrer\">How to change wordpress custom logo and logo link class</a></p>\n"
},
{
"answer_id": 341522,
"author": "Fred Bradley",
"author_id": 39079,
"author_profile": "https://wordpress.stackexchange.com/users/39079",
"pm_score": 2,
"selected": false,
"text": "<p>Just for anyone else that's looking for solutions. <a href=\"https://wordpress.org/support/topic/how-to-change-logo-url-of-twentysixteen-theme/#post-9535770\" rel=\"nofollow noreferrer\">I found this</a>, which I find much clearer than the accepted answer. </p>\n\n<p>Plus it gives simple ways to change the URL on the link as well! Just a little more detailed than the accepted answer. </p>\n\n<pre><code>add_filter( 'get_custom_logo', 'add_custom_logo_url' );\nfunction add_custom_logo_url() {\n $custom_logo_id = get_theme_mod( 'custom_logo' );\n $html = sprintf( '<a href=\"%1$s\" class=\"custom-logo-link\" rel=\"home\" itemprop=\"url\">%2$s</a>',\n esc_url( 'www.somewhere.com' ),\n wp_get_attachment_image( $custom_logo_id, 'full', false, array(\n 'class' => 'custom-logo',\n ) )\n );\n return $html; \n} \n</code></pre>\n"
},
{
"answer_id": 405031,
"author": "Maidul",
"author_id": 21142,
"author_profile": "https://wordpress.stackexchange.com/users/21142",
"pm_score": 0,
"selected": false,
"text": "<p>You can use get_custom_logo_image_attributes filter</p>\n<pre><code>add_filter( 'get_custom_logo_image_attributes', function( \n$custom_logo_attr, $custom_logo_id, $blog_id )\n{\n $custom_logo_attr['class'] = 'your-custom-class';\n\n return $custom_logo_attr;\n} ,10,3);\n</code></pre>\n"
}
] |
2016/06/16
|
[
"https://wordpress.stackexchange.com/questions/229905",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/30597/"
] |
I enabled [`custom-logo`](https://codex.wordpress.org/Function_Reference/add_theme_support#Custom_Logo) for my theme and have it printed with `<?php the_custom_logo(); ?>` into the header. Is there any chance to simply add some more classes to this image directly? Per default it only comes with `custom-logo`.
|
WordPress provide a filter hook to custom logo customization. The hook `get_custom_logo` is the filter. To change logo class, this code may help you.
```
add_filter( 'get_custom_logo', 'change_logo_class' );
function change_logo_class( $html ) {
$html = str_replace( 'custom-logo', 'your-custom-class', $html );
$html = str_replace( 'custom-logo-link', 'your-custom-class', $html );
return $html;
}
```
Reference: [How to change wordpress custom logo and logo link class](http://www.mavengang.com/2016/06/02/change-wordpress-custom-logo-class/)
|
229,921 |
<p>Please help. Anyone knows of the proper way how to change the background color for a custom post type template only? Using chrome's inspect, I saw that my theme uses the ID of "#main" for all the page's background color so if I try changing it, all pages got affected. Just looking for a way on how only the CPT template will get affected. If it helps, below is a snapshot of the theme.</p>
<p><a href="https://i.stack.imgur.com/L2Guq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L2Guq.png" alt="New attachment"></a></p>
|
[
{
"answer_id": 229909,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 2,
"selected": false,
"text": "<p>I think I found one answer. But I really wonder if this is the right way? It feels a little bit dirty somehow: I simply copied the logo related parts from wp-includes/general-template.php into my theme's functions.php and renamed the functions with some custom classes added:</p>\n\n<pre><code>function FOOBAR_get_custom_logo( $blog_id = 0 ) {\n $html = '';\n\n if ( is_multisite() && (int) $blog_id !== get_current_blog_id() ) {\n switch_to_blog( $blog_id );\n }\n\n $custom_logo_id = get_theme_mod( 'custom_logo' );\n\n if ( $custom_logo_id ) {\n $html = sprintf( '<a href=\"%1$s\" class=\"custom-logo-link\" rel=\"home\" itemprop=\"url\">%2$s</a>',\n esc_url( home_url( '/' ) ),\n wp_get_attachment_image( $custom_logo_id, 'full', false, array(\n 'class' => 'custom-logo FOO-BAR FOO BAR', // added classes here\n 'itemprop' => 'logo',\n ) )\n );\n }\n\n elseif ( is_customize_preview() ) {\n $html = sprintf( '<a href=\"%1$s\" class=\"custom-logo-link\" style=\"display:none;\"><img class=\"custom-logo\"/></a>',\n esc_url( home_url( '/' ) )\n );\n }\n\n if ( is_multisite() && ms_is_switched() ) {\n restore_current_blog();\n }\n\n return apply_filters( 'FOOBAR_get_custom_logo', $html );\n}\n\nfunction FOOBAR_the_custom_logo( $blog_id = 0 ) {\n echo FOOBAR_get_custom_logo( $blog_id );\n}\n</code></pre>\n"
},
{
"answer_id": 229910,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": false,
"text": "<p>As you found yourself <code>the_custom_logo</code> relies on <a href=\"https://developer.wordpress.org/reference/functions/get_custom_logo/\"><code>get_custom_logo</code></a>, which itself calls <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image/\"><code>wp_get_attachment_image</code></a> to add the <code>custom-logo</code> class. The latter function has a filter, <a href=\"https://developer.wordpress.org/reference/hooks/wp_get_attachment_image_attributes/\"><code>wp_get_attachment_image_attributes</code></a> which you can use to manipulate the image attributes.</p>\n\n<p>So what you could do is build a filter that checks if the <code>custom-logo</code> class is there and if yes add more classes.</p>\n"
},
{
"answer_id": 229911,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": false,
"text": "<p>Here's one suggestion how we might try to add classes through the <code>wp_get_attachment_image_attributes</code> filter (untested):</p>\n\n<pre><code>add_filter( 'wp_get_attachment_image_attributes', function( $attr )\n{\n if( isset( $attr['class'] ) && 'custom-logo' === $attr['class'] )\n $attr['class'] = 'custom-logo foo-bar foo bar';\n\n return $attr;\n} );\n</code></pre>\n\n<p>where you adjust the classes to your needs.</p>\n"
},
{
"answer_id": 230089,
"author": "Dhinju Divakaran",
"author_id": 96981,
"author_profile": "https://wordpress.stackexchange.com/users/96981",
"pm_score": 6,
"selected": true,
"text": "<p>WordPress provide a filter hook to custom logo customization. The hook <code>get_custom_logo</code> is the filter. To change logo class, this code may help you.</p>\n\n<pre><code>add_filter( 'get_custom_logo', 'change_logo_class' );\n\n\nfunction change_logo_class( $html ) {\n\n $html = str_replace( 'custom-logo', 'your-custom-class', $html );\n $html = str_replace( 'custom-logo-link', 'your-custom-class', $html );\n\n return $html;\n}\n</code></pre>\n\n<p>Reference: <a href=\"http://www.mavengang.com/2016/06/02/change-wordpress-custom-logo-class/\" rel=\"noreferrer\">How to change wordpress custom logo and logo link class</a></p>\n"
},
{
"answer_id": 341522,
"author": "Fred Bradley",
"author_id": 39079,
"author_profile": "https://wordpress.stackexchange.com/users/39079",
"pm_score": 2,
"selected": false,
"text": "<p>Just for anyone else that's looking for solutions. <a href=\"https://wordpress.org/support/topic/how-to-change-logo-url-of-twentysixteen-theme/#post-9535770\" rel=\"nofollow noreferrer\">I found this</a>, which I find much clearer than the accepted answer. </p>\n\n<p>Plus it gives simple ways to change the URL on the link as well! Just a little more detailed than the accepted answer. </p>\n\n<pre><code>add_filter( 'get_custom_logo', 'add_custom_logo_url' );\nfunction add_custom_logo_url() {\n $custom_logo_id = get_theme_mod( 'custom_logo' );\n $html = sprintf( '<a href=\"%1$s\" class=\"custom-logo-link\" rel=\"home\" itemprop=\"url\">%2$s</a>',\n esc_url( 'www.somewhere.com' ),\n wp_get_attachment_image( $custom_logo_id, 'full', false, array(\n 'class' => 'custom-logo',\n ) )\n );\n return $html; \n} \n</code></pre>\n"
},
{
"answer_id": 405031,
"author": "Maidul",
"author_id": 21142,
"author_profile": "https://wordpress.stackexchange.com/users/21142",
"pm_score": 0,
"selected": false,
"text": "<p>You can use get_custom_logo_image_attributes filter</p>\n<pre><code>add_filter( 'get_custom_logo_image_attributes', function( \n$custom_logo_attr, $custom_logo_id, $blog_id )\n{\n $custom_logo_attr['class'] = 'your-custom-class';\n\n return $custom_logo_attr;\n} ,10,3);\n</code></pre>\n"
}
] |
2016/06/16
|
[
"https://wordpress.stackexchange.com/questions/229921",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96830/"
] |
Please help. Anyone knows of the proper way how to change the background color for a custom post type template only? Using chrome's inspect, I saw that my theme uses the ID of "#main" for all the page's background color so if I try changing it, all pages got affected. Just looking for a way on how only the CPT template will get affected. If it helps, below is a snapshot of the theme.
[](https://i.stack.imgur.com/L2Guq.png)
|
WordPress provide a filter hook to custom logo customization. The hook `get_custom_logo` is the filter. To change logo class, this code may help you.
```
add_filter( 'get_custom_logo', 'change_logo_class' );
function change_logo_class( $html ) {
$html = str_replace( 'custom-logo', 'your-custom-class', $html );
$html = str_replace( 'custom-logo-link', 'your-custom-class', $html );
return $html;
}
```
Reference: [How to change wordpress custom logo and logo link class](http://www.mavengang.com/2016/06/02/change-wordpress-custom-logo-class/)
|
229,955 |
<p>I have a custom post type for a simple schedule list and using the meta box plugin i have two meta boxes assigned to custom post type. 1 for an image and 1 for an array of date times .</p>
<p><a href="https://i.stack.imgur.com/OlDUy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OlDUy.png" alt="enter image description here"></a></p>
<p>In my functions.php file I have created a shortcode to retrieve and display the info. HOWEVER it is only showing the post once and where i display the date time it says "array". I want to show the post 3 times based on the fact that I have stored 3 date times with the meta box. I'm not sure how to adjust my query or loop to make the post show 3 times in order of date. Below is my shortcode from my functions.php file. Any help would be greatly appreciated.</p>
<pre><code>// SCHEDULE LIST
add_shortcode( 'schedule', 'display_schedule' );
function display_schedule(){
global $paged;
$args = array(
'post_type' => 'tbschedule',
'post_status' => 'publish',
'paged' => $paged,
'posts_per_page' => 10
);
$string = '';
$query = new WP_Query( $args );
if( $query->have_posts() ){
$string .= '<span class="schedules">';
while( $query->have_posts() ){
$query->the_post();
$schedule_image = "";
$schedule_image_url = "";
$images = rwmb_meta( 'tbf_scheduleimage', 'type=image&size=full');
foreach ( $images as $image ){
$schedule_image = "<img src='{$image['url']}' class='first' alt='{$image['alt']}' title='{$image['title']}' />";
$schedule_image_url = $image['url'];
}
if($schedule_image_url == ""){
$string .= '<div class="schedule"><span class="scheduletitle"><a href="'.get_permalink().'">' . get_the_title() . '<span class="scheduleDate">schedule date: '.rwmb_meta('tbf_scheduledatetime').'</span></a></span></div>';
}else{
$string .= '<div class="schedule">
<a href="'.get_permalink().'"><span class="scheduleimage" style="background-image: url('. $schedule_image_url .');background-repeat: no-repeat;background-position: center center;background-size: contain;"></span></a>
<span class="newstitle"><p style="height: 122px;"><a href="'.get_permalink().'">' . get_the_title() . '<span class="scheduleDate">schedule date: '.rwmb_meta('tbf_scheduledatetime').'</span></a></p></span>
</div>';
}
}
}
$string .= '</span>';
// Paging
$q = $query;
$big = 999999999; // need an unlikely integer
$string .= '<p>&nbsp;</p>'.paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $q->max_num_pages //$q is your custom query
) );
wp_reset_postdata();
return $string;
}
// END SCHEDULE LIST
</code></pre>
|
[
{
"answer_id": 229909,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 2,
"selected": false,
"text": "<p>I think I found one answer. But I really wonder if this is the right way? It feels a little bit dirty somehow: I simply copied the logo related parts from wp-includes/general-template.php into my theme's functions.php and renamed the functions with some custom classes added:</p>\n\n<pre><code>function FOOBAR_get_custom_logo( $blog_id = 0 ) {\n $html = '';\n\n if ( is_multisite() && (int) $blog_id !== get_current_blog_id() ) {\n switch_to_blog( $blog_id );\n }\n\n $custom_logo_id = get_theme_mod( 'custom_logo' );\n\n if ( $custom_logo_id ) {\n $html = sprintf( '<a href=\"%1$s\" class=\"custom-logo-link\" rel=\"home\" itemprop=\"url\">%2$s</a>',\n esc_url( home_url( '/' ) ),\n wp_get_attachment_image( $custom_logo_id, 'full', false, array(\n 'class' => 'custom-logo FOO-BAR FOO BAR', // added classes here\n 'itemprop' => 'logo',\n ) )\n );\n }\n\n elseif ( is_customize_preview() ) {\n $html = sprintf( '<a href=\"%1$s\" class=\"custom-logo-link\" style=\"display:none;\"><img class=\"custom-logo\"/></a>',\n esc_url( home_url( '/' ) )\n );\n }\n\n if ( is_multisite() && ms_is_switched() ) {\n restore_current_blog();\n }\n\n return apply_filters( 'FOOBAR_get_custom_logo', $html );\n}\n\nfunction FOOBAR_the_custom_logo( $blog_id = 0 ) {\n echo FOOBAR_get_custom_logo( $blog_id );\n}\n</code></pre>\n"
},
{
"answer_id": 229910,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": false,
"text": "<p>As you found yourself <code>the_custom_logo</code> relies on <a href=\"https://developer.wordpress.org/reference/functions/get_custom_logo/\"><code>get_custom_logo</code></a>, which itself calls <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image/\"><code>wp_get_attachment_image</code></a> to add the <code>custom-logo</code> class. The latter function has a filter, <a href=\"https://developer.wordpress.org/reference/hooks/wp_get_attachment_image_attributes/\"><code>wp_get_attachment_image_attributes</code></a> which you can use to manipulate the image attributes.</p>\n\n<p>So what you could do is build a filter that checks if the <code>custom-logo</code> class is there and if yes add more classes.</p>\n"
},
{
"answer_id": 229911,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": false,
"text": "<p>Here's one suggestion how we might try to add classes through the <code>wp_get_attachment_image_attributes</code> filter (untested):</p>\n\n<pre><code>add_filter( 'wp_get_attachment_image_attributes', function( $attr )\n{\n if( isset( $attr['class'] ) && 'custom-logo' === $attr['class'] )\n $attr['class'] = 'custom-logo foo-bar foo bar';\n\n return $attr;\n} );\n</code></pre>\n\n<p>where you adjust the classes to your needs.</p>\n"
},
{
"answer_id": 230089,
"author": "Dhinju Divakaran",
"author_id": 96981,
"author_profile": "https://wordpress.stackexchange.com/users/96981",
"pm_score": 6,
"selected": true,
"text": "<p>WordPress provide a filter hook to custom logo customization. The hook <code>get_custom_logo</code> is the filter. To change logo class, this code may help you.</p>\n\n<pre><code>add_filter( 'get_custom_logo', 'change_logo_class' );\n\n\nfunction change_logo_class( $html ) {\n\n $html = str_replace( 'custom-logo', 'your-custom-class', $html );\n $html = str_replace( 'custom-logo-link', 'your-custom-class', $html );\n\n return $html;\n}\n</code></pre>\n\n<p>Reference: <a href=\"http://www.mavengang.com/2016/06/02/change-wordpress-custom-logo-class/\" rel=\"noreferrer\">How to change wordpress custom logo and logo link class</a></p>\n"
},
{
"answer_id": 341522,
"author": "Fred Bradley",
"author_id": 39079,
"author_profile": "https://wordpress.stackexchange.com/users/39079",
"pm_score": 2,
"selected": false,
"text": "<p>Just for anyone else that's looking for solutions. <a href=\"https://wordpress.org/support/topic/how-to-change-logo-url-of-twentysixteen-theme/#post-9535770\" rel=\"nofollow noreferrer\">I found this</a>, which I find much clearer than the accepted answer. </p>\n\n<p>Plus it gives simple ways to change the URL on the link as well! Just a little more detailed than the accepted answer. </p>\n\n<pre><code>add_filter( 'get_custom_logo', 'add_custom_logo_url' );\nfunction add_custom_logo_url() {\n $custom_logo_id = get_theme_mod( 'custom_logo' );\n $html = sprintf( '<a href=\"%1$s\" class=\"custom-logo-link\" rel=\"home\" itemprop=\"url\">%2$s</a>',\n esc_url( 'www.somewhere.com' ),\n wp_get_attachment_image( $custom_logo_id, 'full', false, array(\n 'class' => 'custom-logo',\n ) )\n );\n return $html; \n} \n</code></pre>\n"
},
{
"answer_id": 405031,
"author": "Maidul",
"author_id": 21142,
"author_profile": "https://wordpress.stackexchange.com/users/21142",
"pm_score": 0,
"selected": false,
"text": "<p>You can use get_custom_logo_image_attributes filter</p>\n<pre><code>add_filter( 'get_custom_logo_image_attributes', function( \n$custom_logo_attr, $custom_logo_id, $blog_id )\n{\n $custom_logo_attr['class'] = 'your-custom-class';\n\n return $custom_logo_attr;\n} ,10,3);\n</code></pre>\n"
}
] |
2016/06/16
|
[
"https://wordpress.stackexchange.com/questions/229955",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96889/"
] |
I have a custom post type for a simple schedule list and using the meta box plugin i have two meta boxes assigned to custom post type. 1 for an image and 1 for an array of date times .
[](https://i.stack.imgur.com/OlDUy.png)
In my functions.php file I have created a shortcode to retrieve and display the info. HOWEVER it is only showing the post once and where i display the date time it says "array". I want to show the post 3 times based on the fact that I have stored 3 date times with the meta box. I'm not sure how to adjust my query or loop to make the post show 3 times in order of date. Below is my shortcode from my functions.php file. Any help would be greatly appreciated.
```
// SCHEDULE LIST
add_shortcode( 'schedule', 'display_schedule' );
function display_schedule(){
global $paged;
$args = array(
'post_type' => 'tbschedule',
'post_status' => 'publish',
'paged' => $paged,
'posts_per_page' => 10
);
$string = '';
$query = new WP_Query( $args );
if( $query->have_posts() ){
$string .= '<span class="schedules">';
while( $query->have_posts() ){
$query->the_post();
$schedule_image = "";
$schedule_image_url = "";
$images = rwmb_meta( 'tbf_scheduleimage', 'type=image&size=full');
foreach ( $images as $image ){
$schedule_image = "<img src='{$image['url']}' class='first' alt='{$image['alt']}' title='{$image['title']}' />";
$schedule_image_url = $image['url'];
}
if($schedule_image_url == ""){
$string .= '<div class="schedule"><span class="scheduletitle"><a href="'.get_permalink().'">' . get_the_title() . '<span class="scheduleDate">schedule date: '.rwmb_meta('tbf_scheduledatetime').'</span></a></span></div>';
}else{
$string .= '<div class="schedule">
<a href="'.get_permalink().'"><span class="scheduleimage" style="background-image: url('. $schedule_image_url .');background-repeat: no-repeat;background-position: center center;background-size: contain;"></span></a>
<span class="newstitle"><p style="height: 122px;"><a href="'.get_permalink().'">' . get_the_title() . '<span class="scheduleDate">schedule date: '.rwmb_meta('tbf_scheduledatetime').'</span></a></p></span>
</div>';
}
}
}
$string .= '</span>';
// Paging
$q = $query;
$big = 999999999; // need an unlikely integer
$string .= '<p> </p>'.paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $q->max_num_pages //$q is your custom query
) );
wp_reset_postdata();
return $string;
}
// END SCHEDULE LIST
```
|
WordPress provide a filter hook to custom logo customization. The hook `get_custom_logo` is the filter. To change logo class, this code may help you.
```
add_filter( 'get_custom_logo', 'change_logo_class' );
function change_logo_class( $html ) {
$html = str_replace( 'custom-logo', 'your-custom-class', $html );
$html = str_replace( 'custom-logo-link', 'your-custom-class', $html );
return $html;
}
```
Reference: [How to change wordpress custom logo and logo link class](http://www.mavengang.com/2016/06/02/change-wordpress-custom-logo-class/)
|
230,015 |
<p>I need to use Bootstrap CSS for better UI in wp-admin but if I enqueue the <code>bootstrap.css</code>, it's affecting the admin default UI by changing background colors, etc.</p>
<p>How can I use <code>bootstrap.css</code> inside wp-admin? </p>
|
[
{
"answer_id": 229909,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": 2,
"selected": false,
"text": "<p>I think I found one answer. But I really wonder if this is the right way? It feels a little bit dirty somehow: I simply copied the logo related parts from wp-includes/general-template.php into my theme's functions.php and renamed the functions with some custom classes added:</p>\n\n<pre><code>function FOOBAR_get_custom_logo( $blog_id = 0 ) {\n $html = '';\n\n if ( is_multisite() && (int) $blog_id !== get_current_blog_id() ) {\n switch_to_blog( $blog_id );\n }\n\n $custom_logo_id = get_theme_mod( 'custom_logo' );\n\n if ( $custom_logo_id ) {\n $html = sprintf( '<a href=\"%1$s\" class=\"custom-logo-link\" rel=\"home\" itemprop=\"url\">%2$s</a>',\n esc_url( home_url( '/' ) ),\n wp_get_attachment_image( $custom_logo_id, 'full', false, array(\n 'class' => 'custom-logo FOO-BAR FOO BAR', // added classes here\n 'itemprop' => 'logo',\n ) )\n );\n }\n\n elseif ( is_customize_preview() ) {\n $html = sprintf( '<a href=\"%1$s\" class=\"custom-logo-link\" style=\"display:none;\"><img class=\"custom-logo\"/></a>',\n esc_url( home_url( '/' ) )\n );\n }\n\n if ( is_multisite() && ms_is_switched() ) {\n restore_current_blog();\n }\n\n return apply_filters( 'FOOBAR_get_custom_logo', $html );\n}\n\nfunction FOOBAR_the_custom_logo( $blog_id = 0 ) {\n echo FOOBAR_get_custom_logo( $blog_id );\n}\n</code></pre>\n"
},
{
"answer_id": 229910,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": false,
"text": "<p>As you found yourself <code>the_custom_logo</code> relies on <a href=\"https://developer.wordpress.org/reference/functions/get_custom_logo/\"><code>get_custom_logo</code></a>, which itself calls <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image/\"><code>wp_get_attachment_image</code></a> to add the <code>custom-logo</code> class. The latter function has a filter, <a href=\"https://developer.wordpress.org/reference/hooks/wp_get_attachment_image_attributes/\"><code>wp_get_attachment_image_attributes</code></a> which you can use to manipulate the image attributes.</p>\n\n<p>So what you could do is build a filter that checks if the <code>custom-logo</code> class is there and if yes add more classes.</p>\n"
},
{
"answer_id": 229911,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": false,
"text": "<p>Here's one suggestion how we might try to add classes through the <code>wp_get_attachment_image_attributes</code> filter (untested):</p>\n\n<pre><code>add_filter( 'wp_get_attachment_image_attributes', function( $attr )\n{\n if( isset( $attr['class'] ) && 'custom-logo' === $attr['class'] )\n $attr['class'] = 'custom-logo foo-bar foo bar';\n\n return $attr;\n} );\n</code></pre>\n\n<p>where you adjust the classes to your needs.</p>\n"
},
{
"answer_id": 230089,
"author": "Dhinju Divakaran",
"author_id": 96981,
"author_profile": "https://wordpress.stackexchange.com/users/96981",
"pm_score": 6,
"selected": true,
"text": "<p>WordPress provide a filter hook to custom logo customization. The hook <code>get_custom_logo</code> is the filter. To change logo class, this code may help you.</p>\n\n<pre><code>add_filter( 'get_custom_logo', 'change_logo_class' );\n\n\nfunction change_logo_class( $html ) {\n\n $html = str_replace( 'custom-logo', 'your-custom-class', $html );\n $html = str_replace( 'custom-logo-link', 'your-custom-class', $html );\n\n return $html;\n}\n</code></pre>\n\n<p>Reference: <a href=\"http://www.mavengang.com/2016/06/02/change-wordpress-custom-logo-class/\" rel=\"noreferrer\">How to change wordpress custom logo and logo link class</a></p>\n"
},
{
"answer_id": 341522,
"author": "Fred Bradley",
"author_id": 39079,
"author_profile": "https://wordpress.stackexchange.com/users/39079",
"pm_score": 2,
"selected": false,
"text": "<p>Just for anyone else that's looking for solutions. <a href=\"https://wordpress.org/support/topic/how-to-change-logo-url-of-twentysixteen-theme/#post-9535770\" rel=\"nofollow noreferrer\">I found this</a>, which I find much clearer than the accepted answer. </p>\n\n<p>Plus it gives simple ways to change the URL on the link as well! Just a little more detailed than the accepted answer. </p>\n\n<pre><code>add_filter( 'get_custom_logo', 'add_custom_logo_url' );\nfunction add_custom_logo_url() {\n $custom_logo_id = get_theme_mod( 'custom_logo' );\n $html = sprintf( '<a href=\"%1$s\" class=\"custom-logo-link\" rel=\"home\" itemprop=\"url\">%2$s</a>',\n esc_url( 'www.somewhere.com' ),\n wp_get_attachment_image( $custom_logo_id, 'full', false, array(\n 'class' => 'custom-logo',\n ) )\n );\n return $html; \n} \n</code></pre>\n"
},
{
"answer_id": 405031,
"author": "Maidul",
"author_id": 21142,
"author_profile": "https://wordpress.stackexchange.com/users/21142",
"pm_score": 0,
"selected": false,
"text": "<p>You can use get_custom_logo_image_attributes filter</p>\n<pre><code>add_filter( 'get_custom_logo_image_attributes', function( \n$custom_logo_attr, $custom_logo_id, $blog_id )\n{\n $custom_logo_attr['class'] = 'your-custom-class';\n\n return $custom_logo_attr;\n} ,10,3);\n</code></pre>\n"
}
] |
2016/06/17
|
[
"https://wordpress.stackexchange.com/questions/230015",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90760/"
] |
I need to use Bootstrap CSS for better UI in wp-admin but if I enqueue the `bootstrap.css`, it's affecting the admin default UI by changing background colors, etc.
How can I use `bootstrap.css` inside wp-admin?
|
WordPress provide a filter hook to custom logo customization. The hook `get_custom_logo` is the filter. To change logo class, this code may help you.
```
add_filter( 'get_custom_logo', 'change_logo_class' );
function change_logo_class( $html ) {
$html = str_replace( 'custom-logo', 'your-custom-class', $html );
$html = str_replace( 'custom-logo-link', 'your-custom-class', $html );
return $html;
}
```
Reference: [How to change wordpress custom logo and logo link class](http://www.mavengang.com/2016/06/02/change-wordpress-custom-logo-class/)
|
230,032 |
<p>I've created a custom taxonomy:</p>
<pre><code>add_action( 'init', 'create_collection_taxonomies', 0 );
function create_collection_taxonomies() {
$labels = array(
'name' => _x( 'Collection Tags', 'taxonomy general name' ),
'singular_name' => _x( 'Collection Tag', 'taxonomy singular name' ),
'search_items' => __( 'Search Collection Tags' ),
'popular_items' => __( 'Popular Collection Tags' ),
'all_items' => __( 'All Collection Tags' ),
'parent_item' => __( 'Parent Collection Tag' ),
'parent_item_colon' => __( 'Parent Collection Tag' ),
'edit_item' => __( 'Edit Collection Tag' ),
'update_item' => __( 'Update Collection Tag' ),
'add_new_item' => __( 'Add New Collection Tag' ),
'new_item_name' => __( 'New Collection Tag Name' ),
'menu_name' => __( 'Collections Tags' ),
);
$args = array(
'description' => 'Used to select promo/video for display in app.',
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'CollectionTag' ),
);
register_taxonomy( 'CollectionTag', array('collection', 'videos', 'promos'), $args );
}
</code></pre>
<p>I added the <code>description</code> argument thinking it would appear in the taxonomy metabox in the WP admin; however, that doesn't seem to be the case.</p>
<p>I did find <a href="https://wordpress.stackexchange.com/questions/12434/custom-taxonomy-admin-description">this post from 2011</a>, saying I would have to use jQuery to get a description added to the box, but it seems odd we can define a description without being able to use it.</p>
<p>Am I misunderstanding the purpose of this argument from what I'm reading in the <a href="http://codex.wordpress.org/Function_Reference/register_taxonomy" rel="nofollow noreferrer">Codex</a>? How do I get this description to appear within the meta box for this taxonomy?</p>
|
[
{
"answer_id": 230043,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 4,
"selected": true,
"text": "<p>Looking at the files that create the metabox, there isn't anything to really hook into that will allow us to add the description so we'll need to use jQuery. Since the script is extremely small, I've opted not to put it into an external file but instead use the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_footer\" rel=\"noreferrer\"><code>admin_footer</code></a> hook:</p>\n\n<pre><code>/**\n * Prepend taxonomy descriptions to taxonomy metaboxes\n */\nfunction append_taxonomy_descriptions_metabox() {\n $post_types = array( 'page' ); // Array of Accepted Post Types\n $screen = get_current_screen(); // Get current user screen\n\n if( 'edit' !== $screen->parent_base ) { // IF we're not on an edit page - just return\n return;\n }\n\n // IF the current post type is in our array\n if( in_array( $screen->post_type, $post_types ) ) {\n $taxonomies = get_object_taxonomies( $screen->post_type, 'objects' ); // Grab all taxonomies for that post type\n\n // Ensure taxonomies are not empty\n if( ! empty( $taxonomies ) ) : ?>\n\n <script type=\"text/javascript\">\n\n <?php foreach( $taxonomies as $taxonomy ) : ?>\n\n var tax_slug = '<?php echo $taxonomy->name; ?>';\n var tax_desc = '<?php echo $taxonomy->description; ?>';\n\n // Add the description via jQuery\n jQuery( '#' + tax_slug + 'div div.inside' ).prepend( '<p>' + tax_desc + '</p>' );\n\n <?php endforeach; ?>\n\n </script>\n\n <?php endif;\n }\n}\nadd_action( 'admin_footer', 'append_taxonomy_descriptions_metabox' );\n</code></pre>\n\n<p>We have a <code>$post_types</code> array to test against so we don't add this to <em>every</em> post type or <em>every</em> page but only certain pages. We could do the same for taxonomies but I have not in this scenario.</p>\n\n<hr>\n\n<p><strong>BONUS MATERIAL</strong></p>\n\n<p>The below will add the description to the Admin taxonomy page ( where you add new terms ). We use a much easier hook <code>add_action( '{$taxonomy}_pre_add_form' )</code>:</p>\n\n<pre><code>/**\n * Prepend taxonomy description to Add New Term form\n */\nfunction CollectionTag_admin_edit_description( $tax_slug ) {\n\n // Grab the Taxonomy Object\n $tax_obj = get_taxonomy( $tax_slug );\n\n // IF the description is set on our object\n if( property_exists( $tax_obj, 'description' ) ) {\n echo '<h2>Description</h2>';\n echo apply_filters( 'the_content', $tax_obj->description );\n }\n}\nadd_action( 'CollectionTag_pre_add_form', 'CollectionTag_admin_edit_description' );\n</code></pre>\n"
},
{
"answer_id": 402376,
"author": "Christopher S.",
"author_id": 127679,
"author_profile": "https://wordpress.stackexchange.com/users/127679",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Dynamic versions of the accepted answers:</strong></p>\n<p>To add the description to each of your public taxonomies with a dynamic version of Howdy's {$taxonomy}_pre_add_form\naction dynamically without coding one for each of your taxonomies use the following:</p>\n<pre><code>/**\n * Prepend taxonomy description to Add New Term form for each taxonomy\n */\nadd_action('init', 'MCMLXV_add_taxonomy_decriptions');\nfunction MCMLXV_add_taxonomy_decriptions()\n{\n $args = array(\n 'public' => true,\n '_builtin' => false\n );\n $taxonomies = get_taxonomies($args, 'names', 'and');\n foreach ($taxonomies as $key => $taxonomy) {\n // Create a dynamic anonymous function foreach of our taxonomies \n // and pass the taxonomy name variable to the anonymous function\n add_action($taxonomy . '_pre_add_form', function ($taxonomy) {\n // Grab the Taxonomy Object\n $tax_obj = get_taxonomy($taxonomy);\n\n // IF the description is set on our object\n if (property_exists($tax_obj, 'description')) {\n echo '<h2>Description</h2>';\n echo apply_filters('the_content', $tax_obj->description);\n }\n });\n }\n}\n</code></pre>\n<p>To combine the above answers by <a href=\"https://wordpress.stackexchange.com/a/230043/127679\">Howdy_McGee</a> and <a href=\"https://wordpress.stackexchange.com/questions/230032/add-description-to-custom-taxonomy-admin-metabox#comment447031_230043\">Davey</a> to be dynamic based on if the taxonomy hierarchal is set to false (ie tags or custom tag taxonomies) and to make the js variables unique I used the following:</p>\n<pre><code><script type="text/javascript" id="mythemehere_taxonomy_metabox_description">\n <?php foreach ($taxonomies as $taxonomy) { ?>\n <?php if ($taxonomy->hierarchical == false) { ?>\n\n // Unique variables per tax\n var tax_slug_<?php echo $taxonomy->name; ?> = '<?php echo $taxonomy->name; ?>';\n var tax_desc_<?php echo $taxonomy->name; ?> = '<?php echo $taxonomy->description; ?>';\n\n // jQuery targeting of hierarchal false taxonomies (tags)\n jQuery('#tagsdiv-' + tax_slug_<?php echo $taxonomy->name; ?> + ' div.inside').prepend('<p>' + tax_desc_<?php echo $taxonomy->description; ?> + '</p>');\n\n <?php } else { ?>\n\n // Unique variables per tax\n var tax_slug_<?php echo $taxonomy->name; ?> = '<?php echo $taxonomy->name; ?>';\n var tax_desc_<?php echo $taxonomy->name; ?> = '<?php echo $taxonomy->description; ?>';\n\n // jQuery targeting of hierarchal true taxonomies (categories)\n jQuery('#' + tax_slug_<?php echo $taxonomy->name; ?> + 'div div.inside').prepend('<p>' + tax_desc_<?php echo $taxonomy->name; ?> + '</p>');\n\n <?php } ?>\n <?php } ?>\n</script>\n</code></pre>\n<p>This will output something like the following:</p>\n<pre><code>\n<script type="text/javascript" id="mythemehere_taxonomy_metabox_description">\n var tax_slug_portfolio_category = 'portfolio_category';\n var tax_desc_portfolio_category = 'this is your unique description';\n // Add the description via jQuery\n jQuery('#' + tax_slug_portfolio_category + 'div div.inside').prepend('<p>' + tax_desc_portfolio_category + '</p>');\n \n var tax_slug_portfolio_tag = 'portfolio_tag';\n var tax_desc_portfolio_tag = 'this is your unique description';\n // Add the description via jQuery\n jQuery('#tagsdiv-' + tax_slug_portfolio_tag + ' div.inside').prepend('<p>' + tax_desc_portfolio_tag + '</p>');\n</code></pre>\n<p>All the answers above and in my code above also assumes you have set the description and hierarchal in your register_taxonomy($args). Leaving out all the unnecessary arguments for this example:</p>\n<pre><code> $args = array(\n 'hierarchical' => true,\n 'description' => 'this is your unique description',\n );\n register_taxonomy('portfolio_category', array('portfolio'), $args);\n</code></pre>\n"
}
] |
2016/06/17
|
[
"https://wordpress.stackexchange.com/questions/230032",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/18984/"
] |
I've created a custom taxonomy:
```
add_action( 'init', 'create_collection_taxonomies', 0 );
function create_collection_taxonomies() {
$labels = array(
'name' => _x( 'Collection Tags', 'taxonomy general name' ),
'singular_name' => _x( 'Collection Tag', 'taxonomy singular name' ),
'search_items' => __( 'Search Collection Tags' ),
'popular_items' => __( 'Popular Collection Tags' ),
'all_items' => __( 'All Collection Tags' ),
'parent_item' => __( 'Parent Collection Tag' ),
'parent_item_colon' => __( 'Parent Collection Tag' ),
'edit_item' => __( 'Edit Collection Tag' ),
'update_item' => __( 'Update Collection Tag' ),
'add_new_item' => __( 'Add New Collection Tag' ),
'new_item_name' => __( 'New Collection Tag Name' ),
'menu_name' => __( 'Collections Tags' ),
);
$args = array(
'description' => 'Used to select promo/video for display in app.',
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'CollectionTag' ),
);
register_taxonomy( 'CollectionTag', array('collection', 'videos', 'promos'), $args );
}
```
I added the `description` argument thinking it would appear in the taxonomy metabox in the WP admin; however, that doesn't seem to be the case.
I did find [this post from 2011](https://wordpress.stackexchange.com/questions/12434/custom-taxonomy-admin-description), saying I would have to use jQuery to get a description added to the box, but it seems odd we can define a description without being able to use it.
Am I misunderstanding the purpose of this argument from what I'm reading in the [Codex](http://codex.wordpress.org/Function_Reference/register_taxonomy)? How do I get this description to appear within the meta box for this taxonomy?
|
Looking at the files that create the metabox, there isn't anything to really hook into that will allow us to add the description so we'll need to use jQuery. Since the script is extremely small, I've opted not to put it into an external file but instead use the [`admin_footer`](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_footer) hook:
```
/**
* Prepend taxonomy descriptions to taxonomy metaboxes
*/
function append_taxonomy_descriptions_metabox() {
$post_types = array( 'page' ); // Array of Accepted Post Types
$screen = get_current_screen(); // Get current user screen
if( 'edit' !== $screen->parent_base ) { // IF we're not on an edit page - just return
return;
}
// IF the current post type is in our array
if( in_array( $screen->post_type, $post_types ) ) {
$taxonomies = get_object_taxonomies( $screen->post_type, 'objects' ); // Grab all taxonomies for that post type
// Ensure taxonomies are not empty
if( ! empty( $taxonomies ) ) : ?>
<script type="text/javascript">
<?php foreach( $taxonomies as $taxonomy ) : ?>
var tax_slug = '<?php echo $taxonomy->name; ?>';
var tax_desc = '<?php echo $taxonomy->description; ?>';
// Add the description via jQuery
jQuery( '#' + tax_slug + 'div div.inside' ).prepend( '<p>' + tax_desc + '</p>' );
<?php endforeach; ?>
</script>
<?php endif;
}
}
add_action( 'admin_footer', 'append_taxonomy_descriptions_metabox' );
```
We have a `$post_types` array to test against so we don't add this to *every* post type or *every* page but only certain pages. We could do the same for taxonomies but I have not in this scenario.
---
**BONUS MATERIAL**
The below will add the description to the Admin taxonomy page ( where you add new terms ). We use a much easier hook `add_action( '{$taxonomy}_pre_add_form' )`:
```
/**
* Prepend taxonomy description to Add New Term form
*/
function CollectionTag_admin_edit_description( $tax_slug ) {
// Grab the Taxonomy Object
$tax_obj = get_taxonomy( $tax_slug );
// IF the description is set on our object
if( property_exists( $tax_obj, 'description' ) ) {
echo '<h2>Description</h2>';
echo apply_filters( 'the_content', $tax_obj->description );
}
}
add_action( 'CollectionTag_pre_add_form', 'CollectionTag_admin_edit_description' );
```
|
230,085 |
<p>The problem I am having is that the get_template_directory_uri is pointing to the parent theme like <code>site/wp-content/themes/twentythirteen/myGallery/gallery_functions_include.php</code></p>
<p>but I want it to point to my child theme which should be <code>site/wp-content/themes/child-twentythirteen/myGallery/gallery_functions_include.php</code></p>
<p>what I am using is <code>include (TEMPLATEPATH . '/myGallery/gallery_functions_include.php');</code> </p>
|
[
{
"answer_id": 230086,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 8,
"selected": true,
"text": "<p><code>get_template_directory_uri()</code> will always return the URI of the current parent theme.</p>\n\n<p>To get the child theme URI instead, you need to use <code>get_stylesheet_directory_uri()</code>.</p>\n\n<p>You can find these <a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri\">in the documentation</a>, along with a list of other useful functions for getting various theme directory locations.</p>\n\n<hr>\n\n<p>If you prefer to use a constant, then <code>TEMPLATEPATH</code> is akin to calling <code>get_template_directory()</code> (i.e. the parent theme), and <code>STYLESHEETPATH</code> is akin to calling <code>get_stylesheet_directory()</code> (i.e. the child theme).</p>\n\n<p>These constants are set by WordPress core in <code>wp-includes/default-constants.php</code> and basically look like this:</p>\n\n<pre><code>define('TEMPLATEPATH', get_template_directory());\n...\ndefine('STYLESHEETPATH', get_stylesheet_directory());\n</code></pre>\n\n<p>If there is no child theme, then both the 'template' <em>and</em> 'stylesheet' functions will return the parent theme location.</p>\n\n<p>Note the difference between these functions and the functions ending in <code>_uri</code> - these will return the absolute server path (eg. <code>/home/example/public_html/wp-content/yourtheme</code>), whereas the <code>_uri</code> functions will return the public address (aka URL) - eg. <code>http://example.com/wp-content/themes/yourtheme</code>.</p>\n"
},
{
"answer_id": 305463,
"author": "Gregory Bologna",
"author_id": 141840,
"author_profile": "https://wordpress.stackexchange.com/users/141840",
"pm_score": 0,
"selected": false,
"text": "<p>You should move your custom templates, those that are not controlled by the active theme, to a child folder. </p>\n\n<p>Keep the theme separate from all customized files this way the theme can be updated without losing your custom work.</p>\n\n<pre>Your out-of-the-box theme lives here\n------------------------------------\n\\\\Site\\wp-content\\themes\\some_theme</pre>\n\n<pre>Your child theme lives here\n---------------------------\n\\\\Site\\wp-content\\themes\\some_theme-child</pre>\n\n<p>Your custom styles and templates and all your includes (things like custom javascript, images that are not saved to WP, custom fonts, json data files, and any plugins that you might enqueue) should be moved to child folder OUTSIDE of theme.</p>\n\n<pre>\n\\themes\\some_theme\n\\themes\\some_theme-child\\ (all your custom php template files here)\n\\themes\\some_theme-child\\images\n\\themes\\some_theme-child\\includes \n\\themes\\some_theme-child\\languages\n\\themes\\some_theme-child\\json \n\\themes\\some_theme-child\\style\n</pre>\n\n<p>For your custom style pages (<em>not the theme's overridden style.css</em>) enqueue with\nwp_enqueue_style( 'some-css', <a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory?\" rel=\"nofollow noreferrer\">get_stylesheet_directory()</a> . '/style/some.css' , false, '0.0.1', 'all');</p>\n\n<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri?\" rel=\"nofollow noreferrer\">get_stylesheet_directory_uri()</a> with your xhr calls, etc.</p>\n"
},
{
"answer_id": 377195,
"author": "D.Y.",
"author_id": 159763,
"author_profile": "https://wordpress.stackexchange.com/users/159763",
"pm_score": 0,
"selected": false,
"text": "<p>Replace</p>\n<blockquote>\n<p><code>include (TEMPLATEPATH . '/path-to/my-file.php');</code></p>\n</blockquote>\n<p>with</p>\n<blockquote>\n<p><code>include dirname( __FILE__ ) . '/path-to/my-file.php';</code></p>\n</blockquote>\n<p>this should work for most common issues</p>\n"
}
] |
2016/06/18
|
[
"https://wordpress.stackexchange.com/questions/230085",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88483/"
] |
The problem I am having is that the get\_template\_directory\_uri is pointing to the parent theme like `site/wp-content/themes/twentythirteen/myGallery/gallery_functions_include.php`
but I want it to point to my child theme which should be `site/wp-content/themes/child-twentythirteen/myGallery/gallery_functions_include.php`
what I am using is `include (TEMPLATEPATH . '/myGallery/gallery_functions_include.php');`
|
`get_template_directory_uri()` will always return the URI of the current parent theme.
To get the child theme URI instead, you need to use `get_stylesheet_directory_uri()`.
You can find these [in the documentation](https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri), along with a list of other useful functions for getting various theme directory locations.
---
If you prefer to use a constant, then `TEMPLATEPATH` is akin to calling `get_template_directory()` (i.e. the parent theme), and `STYLESHEETPATH` is akin to calling `get_stylesheet_directory()` (i.e. the child theme).
These constants are set by WordPress core in `wp-includes/default-constants.php` and basically look like this:
```
define('TEMPLATEPATH', get_template_directory());
...
define('STYLESHEETPATH', get_stylesheet_directory());
```
If there is no child theme, then both the 'template' *and* 'stylesheet' functions will return the parent theme location.
Note the difference between these functions and the functions ending in `_uri` - these will return the absolute server path (eg. `/home/example/public_html/wp-content/yourtheme`), whereas the `_uri` functions will return the public address (aka URL) - eg. `http://example.com/wp-content/themes/yourtheme`.
|
230,107 |
<p>I have two translatable strings as follows in my 404.php file</p>
<pre><code>esc_html_e( 'I couldn't find the page you were looking for.', 'themename' );
esc_html_e( 'Try a search or one of the links below.', 'themename' );
</code></pre>
<p>At its present form, the first string does not get translated. Escaping the single quote with a backslash does not help either.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 230108,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>Anyone with a login can access the admin area, even if they're just a subscriber that can read posts and nothing more.</p>\n\n<p>The crucial difference is not in the login, but in what parts of the admin one gets access to. A subscriber will only be able to see his personal profile, for instance. And admin gets access to everything. Others get something inbetween.</p>\n\n<p>If you build a new user role, you can determine exactly what he or she gets acces to, by assigning one or more of the <a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"nofollow\">58 capabilities</a> to that role.</p>\n\n<p>The general syntax to add a new role is like this: <code>add_role( $role, $display_name, $capabilities )</code>, where the last variable is an array of the capabilities you want to assign to this role. Only these capabilities will be available to those users in the admin area.</p>\n"
},
{
"answer_id": 336397,
"author": "Eduardo Marcolino",
"author_id": 124309,
"author_profile": "https://wordpress.stackexchange.com/users/124309",
"pm_score": 2,
"selected": false,
"text": "<p>You must add the <code>read</code> capability.</p>\n"
},
{
"answer_id": 395374,
"author": "Albin",
"author_id": 164299,
"author_profile": "https://wordpress.stackexchange.com/users/164299",
"pm_score": 1,
"selected": false,
"text": "<p>In Woocommerce you will also need one of these</p>\n<ul>\n<li>manage_woocommerce</li>\n<li>view_admin_dashboard</li>\n<li>edit_others_shop_orders</li>\n</ul>\n"
}
] |
2016/06/18
|
[
"https://wordpress.stackexchange.com/questions/230107",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68715/"
] |
I have two translatable strings as follows in my 404.php file
```
esc_html_e( 'I couldn't find the page you were looking for.', 'themename' );
esc_html_e( 'Try a search or one of the links below.', 'themename' );
```
At its present form, the first string does not get translated. Escaping the single quote with a backslash does not help either.
Any ideas?
|
Anyone with a login can access the admin area, even if they're just a subscriber that can read posts and nothing more.
The crucial difference is not in the login, but in what parts of the admin one gets access to. A subscriber will only be able to see his personal profile, for instance. And admin gets access to everything. Others get something inbetween.
If you build a new user role, you can determine exactly what he or she gets acces to, by assigning one or more of the [58 capabilities](https://codex.wordpress.org/Roles_and_Capabilities) to that role.
The general syntax to add a new role is like this: `add_role( $role, $display_name, $capabilities )`, where the last variable is an array of the capabilities you want to assign to this role. Only these capabilities will be available to those users in the admin area.
|
230,129 |
<p>I'm new to PHP, but I've noticed just about every PHP file has a security snippet, "Die if not accessed in the correct manner" script at the beginning; <strong>my question</strong>, does a child-theme <code>functions.php</code> need something like this as well to make it secure?</p>
<p><strong>PHP:</strong></p>
<pre><code>if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct Access Not Permitted' );
}
</code></pre>
|
[
{
"answer_id": 230130,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 2,
"selected": false,
"text": "<p>Most of the times there is no need to check for <code>defined( 'ABSPATH' )</code> in the child theme.</p>\n"
},
{
"answer_id": 230131,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>No, <code>functions.php</code> would generate PHP fatals if loaded directly as it uses the WordPress API.</p>\n\n<p>If <code>functions.php</code> tried to bootstrap and load WordPress however, then yes, it would be necessary, but if you've done that then something has gone <strong>horribly wrong</strong> and you need to start from scratch</p>\n"
},
{
"answer_id": 230133,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 4,
"selected": true,
"text": "<p>Does it <em>need</em> it? Probably not (other than <a href=\"https://wordpress.stackexchange.com/a/63004/43098\">this edge case</a>, props @bravokeyl). Should you add it? In my opinion, yes:</p>\n\n<ol>\n<li>From a coding/architecture POV, you're declaring \"this file needs WordPress\".</li>\n<li>Any direct hit to one of your theme's files (curious users, bots, \"script kiddies\" etc.) has the potential to leak a little bit of info (most likely filesystem) and/or litter your error logs (e.g. <code>Undefined function get_header in /bada/bing/bada/boom</code>)</li>\n<li>Reiterating 1), it's just good practice.</li>\n</ol>\n\n<p><strong>However</strong>, I absolutely <em>hate</em> this:</p>\n\n<pre><code>die( 'Direct Access Not Permitted' );\n</code></pre>\n\n<p>IMO it should simply be:</p>\n\n<pre><code>if ( ! defined( 'ABSPATH' ) )\n exit;\n</code></pre>\n\n<p>There is just no point in having that \"message\". And I'm a big fan of <code>exit</code>. It communicates the fact that this is an <em>expected</em> possible scenario, and in that scenario, I simply wish to quit. I use <code>die</code> for \"unexpected\" scenarios, like filesystem write errors, database errors etc.</p>\n"
},
{
"answer_id": 230136,
"author": "Liam Bailey",
"author_id": 2911,
"author_profile": "https://wordpress.stackexchange.com/users/2911",
"pm_score": 0,
"selected": false,
"text": "<p>Loading almost any (if not all) WordPress files directly will give nothing more than a white screen of death if you have your error reporting set properly. This is because it will trigger a fatal PHP error stopping the execution, and the correct public settings for error display is to not show them. However, if you are trying to mask that you are using WordPress or at least go to as great a lengths possible to do so, then you might want to make that check but inside the if trigger a 404 response code.</p>\n"
}
] |
2016/06/18
|
[
"https://wordpress.stackexchange.com/questions/230129",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93185/"
] |
I'm new to PHP, but I've noticed just about every PHP file has a security snippet, "Die if not accessed in the correct manner" script at the beginning; **my question**, does a child-theme `functions.php` need something like this as well to make it secure?
**PHP:**
```
if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct Access Not Permitted' );
}
```
|
Does it *need* it? Probably not (other than [this edge case](https://wordpress.stackexchange.com/a/63004/43098), props @bravokeyl). Should you add it? In my opinion, yes:
1. From a coding/architecture POV, you're declaring "this file needs WordPress".
2. Any direct hit to one of your theme's files (curious users, bots, "script kiddies" etc.) has the potential to leak a little bit of info (most likely filesystem) and/or litter your error logs (e.g. `Undefined function get_header in /bada/bing/bada/boom`)
3. Reiterating 1), it's just good practice.
**However**, I absolutely *hate* this:
```
die( 'Direct Access Not Permitted' );
```
IMO it should simply be:
```
if ( ! defined( 'ABSPATH' ) )
exit;
```
There is just no point in having that "message". And I'm a big fan of `exit`. It communicates the fact that this is an *expected* possible scenario, and in that scenario, I simply wish to quit. I use `die` for "unexpected" scenarios, like filesystem write errors, database errors etc.
|
230,150 |
<p>I'm in Wordpress 4.5.2 on Windows 10 and I'm trying to register and enqueue my stylesheet in Wordpress, but it just isn't working. I'm having the same problem with jQuery.</p>
<p>I have this code in a plugin, and I am displaying a dashboard widget, which is working just fine:</p>
<pre><code><?php
/*
* Plugin Name: TEST PLUGIN
*/
/* register styles and scripts
* register dash widgets
*
*/
function register_styles() {
wp_register_script( 'wildstyle', plugins_url('css/wildstyle.css', __FILE__ ) );
wp_enqueue_script( 'wildstyle' );
}
function register_dash_widget() {
wp_add_dashboard_widget(
'test-widget',
'Test Widget',
'display_callback'
);
}
/* add all the actions
*
*
*/
add_action( 'wp_enqueue_scripts', 'register_styles' );
add_action( 'wp_dashboard_setup', 'register_dash_widget' );
/* display callback for dashboard metabox
*
*
*/
function display_callback() {
echo '<p>Testing, testing...</p>';
}
</code></pre>
<p>Here is the little bit of css that I'm using for the test:</p>
<pre><code>p {
color: red;
}
</code></pre>
<p>Why is my text not red?</p>
|
[
{
"answer_id": 230152,
"author": "Gregcta",
"author_id": 94533,
"author_profile": "https://wordpress.stackexchange.com/users/94533",
"pm_score": 3,
"selected": true,
"text": "<p>You can add stylesheet in back-office, but you need for that use the <code>admin_enqueue_scripts</code> action.</p>\n\n<p>See Codex reference : <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts</a></p>\n"
},
{
"answer_id": 230162,
"author": "JayDeep Nimavat",
"author_id": 50714,
"author_profile": "https://wordpress.stackexchange.com/users/50714",
"pm_score": 0,
"selected": false,
"text": "<p>Just change both lines: </p>\n\n<pre><code>wp_register_script( 'wildstyle', plugins_url('css/wildstyle.css', __FILE__ ) );\nwp_enqueue_script( 'wildstyle' );\n</code></pre>\n\n<p>to</p>\n\n<pre><code>wp_register_style( 'wildstyle', plugins_url('css/wildstyle.css', __FILE__ ) );\nwp_enqueue_style( 'wildstyle' );\n</code></pre>\n"
}
] |
2016/06/18
|
[
"https://wordpress.stackexchange.com/questions/230150",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67424/"
] |
I'm in Wordpress 4.5.2 on Windows 10 and I'm trying to register and enqueue my stylesheet in Wordpress, but it just isn't working. I'm having the same problem with jQuery.
I have this code in a plugin, and I am displaying a dashboard widget, which is working just fine:
```
<?php
/*
* Plugin Name: TEST PLUGIN
*/
/* register styles and scripts
* register dash widgets
*
*/
function register_styles() {
wp_register_script( 'wildstyle', plugins_url('css/wildstyle.css', __FILE__ ) );
wp_enqueue_script( 'wildstyle' );
}
function register_dash_widget() {
wp_add_dashboard_widget(
'test-widget',
'Test Widget',
'display_callback'
);
}
/* add all the actions
*
*
*/
add_action( 'wp_enqueue_scripts', 'register_styles' );
add_action( 'wp_dashboard_setup', 'register_dash_widget' );
/* display callback for dashboard metabox
*
*
*/
function display_callback() {
echo '<p>Testing, testing...</p>';
}
```
Here is the little bit of css that I'm using for the test:
```
p {
color: red;
}
```
Why is my text not red?
|
You can add stylesheet in back-office, but you need for that use the `admin_enqueue_scripts` action.
See Codex reference : <https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts>
|
230,208 |
<p>I would like show a list of tags assigned to the current post, but exclude one by tag id.</p>
<p>I tried excluding it from the array of objects returned from <code>wp_get_post_tags</code>, something like this:</p>
<pre><code>$tags = wp_get_post_tags($post->ID, array(
'exclude' => 13
)
);
</code></pre>
<p>But it doesn't looks like the <code>wp_get_post_tags</code> function supports exclude.</p>
<p>Am I wrong, or is there a better function to use in this case?</p>
|
[
{
"answer_id": 230152,
"author": "Gregcta",
"author_id": 94533,
"author_profile": "https://wordpress.stackexchange.com/users/94533",
"pm_score": 3,
"selected": true,
"text": "<p>You can add stylesheet in back-office, but you need for that use the <code>admin_enqueue_scripts</code> action.</p>\n\n<p>See Codex reference : <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts</a></p>\n"
},
{
"answer_id": 230162,
"author": "JayDeep Nimavat",
"author_id": 50714,
"author_profile": "https://wordpress.stackexchange.com/users/50714",
"pm_score": 0,
"selected": false,
"text": "<p>Just change both lines: </p>\n\n<pre><code>wp_register_script( 'wildstyle', plugins_url('css/wildstyle.css', __FILE__ ) );\nwp_enqueue_script( 'wildstyle' );\n</code></pre>\n\n<p>to</p>\n\n<pre><code>wp_register_style( 'wildstyle', plugins_url('css/wildstyle.css', __FILE__ ) );\nwp_enqueue_style( 'wildstyle' );\n</code></pre>\n"
}
] |
2016/06/20
|
[
"https://wordpress.stackexchange.com/questions/230208",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96462/"
] |
I would like show a list of tags assigned to the current post, but exclude one by tag id.
I tried excluding it from the array of objects returned from `wp_get_post_tags`, something like this:
```
$tags = wp_get_post_tags($post->ID, array(
'exclude' => 13
)
);
```
But it doesn't looks like the `wp_get_post_tags` function supports exclude.
Am I wrong, or is there a better function to use in this case?
|
You can add stylesheet in back-office, but you need for that use the `admin_enqueue_scripts` action.
See Codex reference : <https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts>
|
230,348 |
<p>How to remove the:</p>
<pre><code> {site} / Proudly powered by WordPress
</code></pre>
<p>in bottom of generated pages using twentysixteen (2016) theme on version 4.5.2?</p>
<p>Would prefer if this change was not affected by later updates to the theme.</p>
<p>Note, that I could not make the previous answers work, for example through modification of <code>style.css</code> by addition of:</p>
<pre><code>#site-generator {
display: none;
}
</code></pre>
|
[
{
"answer_id": 230152,
"author": "Gregcta",
"author_id": 94533,
"author_profile": "https://wordpress.stackexchange.com/users/94533",
"pm_score": 3,
"selected": true,
"text": "<p>You can add stylesheet in back-office, but you need for that use the <code>admin_enqueue_scripts</code> action.</p>\n\n<p>See Codex reference : <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts</a></p>\n"
},
{
"answer_id": 230162,
"author": "JayDeep Nimavat",
"author_id": 50714,
"author_profile": "https://wordpress.stackexchange.com/users/50714",
"pm_score": 0,
"selected": false,
"text": "<p>Just change both lines: </p>\n\n<pre><code>wp_register_script( 'wildstyle', plugins_url('css/wildstyle.css', __FILE__ ) );\nwp_enqueue_script( 'wildstyle' );\n</code></pre>\n\n<p>to</p>\n\n<pre><code>wp_register_style( 'wildstyle', plugins_url('css/wildstyle.css', __FILE__ ) );\nwp_enqueue_style( 'wildstyle' );\n</code></pre>\n"
}
] |
2016/06/21
|
[
"https://wordpress.stackexchange.com/questions/230348",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97136/"
] |
How to remove the:
```
{site} / Proudly powered by WordPress
```
in bottom of generated pages using twentysixteen (2016) theme on version 4.5.2?
Would prefer if this change was not affected by later updates to the theme.
Note, that I could not make the previous answers work, for example through modification of `style.css` by addition of:
```
#site-generator {
display: none;
}
```
|
You can add stylesheet in back-office, but you need for that use the `admin_enqueue_scripts` action.
See Codex reference : <https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts>
|
230,394 |
<p>I'm kind of new to WordPress development and I'm trying to make a plugin so I can show all the categories I have in a list.</p>
<p>The Idea is to customise the default view</p>
<p>Instead of the <a href="http://image.prntscr.com/image/a1f48a1cc67041e4b3e22753e5619f9a.png" rel="nofollow noreferrer">default list</a> I would like something like <a href="http://image.prntscr.com/image/c1940fab77ee4271916efa4cc1a0816d.png" rel="nofollow noreferrer">this</a>.</p>
<p>I hope you understand and can help me.</p>
|
[
{
"answer_id": 230468,
"author": "Howard E",
"author_id": 57589,
"author_profile": "https://wordpress.stackexchange.com/users/57589",
"pm_score": 1,
"selected": true,
"text": "<p>If you create your own shortcode based on the product category shortcode</p>\n\n<pre><code>function duck_product_categories( $atts ) {\n global $woocommerce_loop;\n\n $atts = shortcode_atts( array(\n 'number' => null,\n 'orderby' => 'name',\n 'order' => 'ASC',\n 'columns' => '4',\n 'hide_empty' => 1,\n 'parent' => '',\n 'ids' => ''\n ), $atts );\n\n if ( isset( $atts['ids'] ) ) {\n $ids = explode( ',', $atts['ids'] );\n $ids = array_map( 'trim', $ids );\n } else {\n $ids = array();\n }\n\n $hide_empty = ( $atts['hide_empty'] == true || $atts['hide_empty'] == 1 ) ? 1 : 0;\n\n // get terms and workaround WP bug with parents/pad counts\n $args = array(\n 'orderby' => $atts['orderby'],\n 'order' => $atts['order'],\n 'hide_empty' => $hide_empty,\n 'include' => $ids,\n 'pad_counts' => true,\n 'child_of' => $atts['parent']\n );\n\n $product_categories = get_terms( 'product_cat', $args );\n\n if ( '' !== $atts['parent'] ) {\n $product_categories = wp_list_filter( $product_categories, array( 'parent' => $atts['parent'] ) );\n }\n\n if ( $hide_empty ) {\n foreach ( $product_categories as $key => $category ) {\n if ( $category->count == 0 ) {\n unset( $product_categories[ $key ] );\n }\n }\n }\n\n if ( $atts['number'] ) {\n $product_categories = array_slice( $product_categories, 0, $atts['number'] );\n }\n\n $columns = absint( $atts['columns'] );\n $woocommerce_loop['columns'] = $columns;\n\n ob_start();\n\n if ( $product_categories ) {\n ?>\n <div class=\"woocommerce columns-<?php echo $columns;?>\">\n <ul class=\"products alternating-list\">\n <?php\n foreach ( $product_categories as $category ) {\n ?>\n <li class=\"product-category product first\">\n <a href=\"<?php echo get_category_link($category); ?>\">\n <?php\n $thumbnail_id = get_woocommerce_term_meta( $category->term_id, 'thumbnail_id', true );\n $image = wp_get_attachment_url( $thumbnail_id );\n if ( $image ) {\n echo '<img src=\"' . $image . '\" alt=\"\" />';\n }\n ?>\n </a>\n </li>\n <li class=\"product-category product last\"> \n <?php echo $category->name; \n echo '<div class=\"shop_cat_desc\">'.$category->description.'</div>';\n ?>\n </li> \n <?php\n }\n\n woocommerce_product_loop_end();\n }\n\n woocommerce_reset_loop();\n\n return '<div class=\"woocommerce columns-' . $columns . '\">' . ob_get_clean() . '</div>';\n }\nadd_shortcode('dd_product_categories', 'duck_product_categories');\n</code></pre>\n\n<p>Then add this CSS:</p>\n\n<pre><code>.alternating-list li:nth-child(4n+3) {\n float: right !important;\n}\n</code></pre>\n\n<p>When you call the shortcode</p>\n\n<p>[dd_product_categories number=\"12\" parent=\"0\" columns=\"2\"]</p>\n\n<p>put columns=\"2\" or you can just hard code it into there if that's what you're going with.</p>\n\n<p>This includes a category description under the title on the side of the image. Like this <a href=\"https://snag.gy/YVIBCl.jpg\" rel=\"nofollow\">https://snag.gy/YVIBCl.jpg</a> </p>\n"
},
{
"answer_id": 269844,
"author": "purnendu sarkar",
"author_id": 121019,
"author_profile": "https://wordpress.stackexchange.com/users/121019",
"pm_score": -1,
"selected": false,
"text": "<pre><code><?php\n $args = array( 'post_type' => 'services_type', 'posts_per_page' => 4, 'services_cat' => 'regenerative-sports-spine-and-spa', 'orderby' => 'date', 'order' =>'ASC');\n $loop = new WP_Query( $args );\n while ( $loop->have_posts() ) : $loop->the_post() ;global $product; \n $sliderurl = get_the_post_thumbnail_url( get_the_ID(), 'full' );\n ?>\n\n <div class=\"box\">\n <h4><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></h4>\n <div class=\"img\"><img src=\"<?php echo $sliderurl;?>\"></div>\n <p><?php the_excerpt(); ?></p>\n <h5><a href=\"<?php the_permalink(); ?>\">Schedule Appointment Now</a></h5>\n </div>\n\n <?php endwhile; ?>\n <?php wp_reset_query(); ?>\n</code></pre>\n"
}
] |
2016/06/21
|
[
"https://wordpress.stackexchange.com/questions/230394",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97165/"
] |
I'm kind of new to WordPress development and I'm trying to make a plugin so I can show all the categories I have in a list.
The Idea is to customise the default view
Instead of the [default list](http://image.prntscr.com/image/a1f48a1cc67041e4b3e22753e5619f9a.png) I would like something like [this](http://image.prntscr.com/image/c1940fab77ee4271916efa4cc1a0816d.png).
I hope you understand and can help me.
|
If you create your own shortcode based on the product category shortcode
```
function duck_product_categories( $atts ) {
global $woocommerce_loop;
$atts = shortcode_atts( array(
'number' => null,
'orderby' => 'name',
'order' => 'ASC',
'columns' => '4',
'hide_empty' => 1,
'parent' => '',
'ids' => ''
), $atts );
if ( isset( $atts['ids'] ) ) {
$ids = explode( ',', $atts['ids'] );
$ids = array_map( 'trim', $ids );
} else {
$ids = array();
}
$hide_empty = ( $atts['hide_empty'] == true || $atts['hide_empty'] == 1 ) ? 1 : 0;
// get terms and workaround WP bug with parents/pad counts
$args = array(
'orderby' => $atts['orderby'],
'order' => $atts['order'],
'hide_empty' => $hide_empty,
'include' => $ids,
'pad_counts' => true,
'child_of' => $atts['parent']
);
$product_categories = get_terms( 'product_cat', $args );
if ( '' !== $atts['parent'] ) {
$product_categories = wp_list_filter( $product_categories, array( 'parent' => $atts['parent'] ) );
}
if ( $hide_empty ) {
foreach ( $product_categories as $key => $category ) {
if ( $category->count == 0 ) {
unset( $product_categories[ $key ] );
}
}
}
if ( $atts['number'] ) {
$product_categories = array_slice( $product_categories, 0, $atts['number'] );
}
$columns = absint( $atts['columns'] );
$woocommerce_loop['columns'] = $columns;
ob_start();
if ( $product_categories ) {
?>
<div class="woocommerce columns-<?php echo $columns;?>">
<ul class="products alternating-list">
<?php
foreach ( $product_categories as $category ) {
?>
<li class="product-category product first">
<a href="<?php echo get_category_link($category); ?>">
<?php
$thumbnail_id = get_woocommerce_term_meta( $category->term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
if ( $image ) {
echo '<img src="' . $image . '" alt="" />';
}
?>
</a>
</li>
<li class="product-category product last">
<?php echo $category->name;
echo '<div class="shop_cat_desc">'.$category->description.'</div>';
?>
</li>
<?php
}
woocommerce_product_loop_end();
}
woocommerce_reset_loop();
return '<div class="woocommerce columns-' . $columns . '">' . ob_get_clean() . '</div>';
}
add_shortcode('dd_product_categories', 'duck_product_categories');
```
Then add this CSS:
```
.alternating-list li:nth-child(4n+3) {
float: right !important;
}
```
When you call the shortcode
[dd\_product\_categories number="12" parent="0" columns="2"]
put columns="2" or you can just hard code it into there if that's what you're going with.
This includes a category description under the title on the side of the image. Like this <https://snag.gy/YVIBCl.jpg>
|
230,417 |
<p>When adding a link in the WP visual post editor you have to click the settings after adding the link and then click the <strong>Open link in a new tab</strong> to have it add a link with a target in a new window/tab.</p>
<p>I am looking for a way to have this automatically checked by default. Is there a filter or JavaScript code to do this?</p>
<p><a href="https://i.stack.imgur.com/lBs1O.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lBs1O.png" alt="enter image description here"></a></p>
|
[
{
"answer_id": 230435,
"author": "BlueSuiter",
"author_id": 92665,
"author_profile": "https://wordpress.stackexchange.com/users/92665",
"pm_score": 3,
"selected": true,
"text": "<p>Add this function in your theme's functions.php</p>\n\n<pre><code>function my_enqueue($hook) {\n if ('post.php' != $hook ) {\n return;\n }\n wp_enqueue_script('my_custom_script', get_template_directory_uri() . '/js/myscript.js');\n}\n\nadd_action('admin_enqueue_scripts', 'my_enqueue');`\n</code></pre>\n\n<p>In myscript.js place this code</p>\n\n<pre><code>jQuery(document).ready(function(){\n jQuery('#wp-link-target').prop(\"checked\", true);\n})\n</code></pre>\n\n<p>It worked for me.</p>\n"
},
{
"answer_id": 402316,
"author": "Pierre Gimond",
"author_id": 218884,
"author_profile": "https://wordpress.stackexchange.com/users/218884",
"pm_score": 0,
"selected": false,
"text": "<p>The accepted answer didn't work for me so i digged a bit and found an event that is triggered when the link popin is displayed. Keep the PHP and replace the JS with this.</p>\n<pre><code> $(document).on('wplink-open', function() {\n if ($('#wp-link-url').val() === '') {\n $('#wp-link-target').prop("checked", true);\n }\n });\n</code></pre>\n<p>I didn't find a way to check if the link is new or edited. So i added a check for the URL, if it's empty we can safely assume it's a new link.\nHope that help someone.</p>\n"
}
] |
2016/06/22
|
[
"https://wordpress.stackexchange.com/questions/230417",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8668/"
] |
When adding a link in the WP visual post editor you have to click the settings after adding the link and then click the **Open link in a new tab** to have it add a link with a target in a new window/tab.
I am looking for a way to have this automatically checked by default. Is there a filter or JavaScript code to do this?
[](https://i.stack.imgur.com/lBs1O.png)
|
Add this function in your theme's functions.php
```
function my_enqueue($hook) {
if ('post.php' != $hook ) {
return;
}
wp_enqueue_script('my_custom_script', get_template_directory_uri() . '/js/myscript.js');
}
add_action('admin_enqueue_scripts', 'my_enqueue');`
```
In myscript.js place this code
```
jQuery(document).ready(function(){
jQuery('#wp-link-target').prop("checked", true);
})
```
It worked for me.
|
230,421 |
<p>I originally posted this in the stackoverflow, but I believe it is better posted here as I am using wordpress and a wordpress function. I am trying to add the jquery cycle plugin (<a href="http://jquery.malsup.com/cycle/" rel="nofollow">http://jquery.malsup.com/cycle/</a>) to my wordpress site, so I enqueued it in my functions.php, and then added a script right before the /body tag. When I load the page, I get the error in the console: Uncaught TypeError: $(...).cycle is not a function. When I open the source file, the cycle plugin script is also not there. I am not sure what I am doing incorrectly.</p>
<p>To break down what I did, I downloaded the jquery.cycle.all.js file and put in in my child theme (lets call it TestChild) in the directory like so TestChild/assets/scripts/jquery.cycle.all.js. I then declared the wp_enqueue_script function in my functions.php. I then added the script before my /body tag. I would appreciate any help as this has been causing me hours of frustration.</p>
<p>This is my code:</p>
<pre><code> function theme_add_cycle_slide (){
wp_enqueue_script('jquery');
wp_enqueue_script('cycleall', get_stylesheet_directory_uri() . '/assets/scripts/jquery.cycle.all.js', array ('jquery'), null, true);
}
add_action ('wp_enqueue_script', 'theme_add_cycle_slide' );
<div id="slideshow">
<div style="width:250px; height:150px; background:red;"></div>
<div style="width:250px; height:150px; background:blue;"></div>
<div style="width:250px; height:150px; background:green;"></div>
<div style="width:250px; height:150px; background:yellow;"></div>
<div id="prev" style="float:left;">PREV</div>
<div id="next" style="float:right;">NEXT</div>
</div>
<script language="javascript">
jQuery(document).ready(function($) {
$('#slideshow').cycle({
fx: 'fade',
pause: 1
});
});
</script>
</code></pre>
|
[
{
"answer_id": 230424,
"author": "LearntoExcel",
"author_id": 97108,
"author_profile": "https://wordpress.stackexchange.com/users/97108",
"pm_score": 2,
"selected": true,
"text": "<p>Problem was a simple misspelling.</p>\n\n<p>The add_action should be</p>\n\n<p>add_action ('wp_enqueue_scripts', 'theme_add_cycle_slide' );</p>\n\n<p>I wrote 'script'</p>\n"
},
{
"answer_id": 230428,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Try This one : </p>\n\n<pre><code> wp_register_script('cycleall', plugins_url('/assets/scripts/jquery.cycle.all.js', __FILE__), array('jquery'),'1.1', true);\n wp_enqueue_script('cycleall');\n</code></pre>\n\n<p>change script to scripts in <code>add_action()</code> should be</p>\n\n<pre><code>add_action ('wp_enqueue_scripts', 'theme_add_cycle_slide' );\n</code></pre>\n"
}
] |
2016/06/22
|
[
"https://wordpress.stackexchange.com/questions/230421",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97108/"
] |
I originally posted this in the stackoverflow, but I believe it is better posted here as I am using wordpress and a wordpress function. I am trying to add the jquery cycle plugin (<http://jquery.malsup.com/cycle/>) to my wordpress site, so I enqueued it in my functions.php, and then added a script right before the /body tag. When I load the page, I get the error in the console: Uncaught TypeError: $(...).cycle is not a function. When I open the source file, the cycle plugin script is also not there. I am not sure what I am doing incorrectly.
To break down what I did, I downloaded the jquery.cycle.all.js file and put in in my child theme (lets call it TestChild) in the directory like so TestChild/assets/scripts/jquery.cycle.all.js. I then declared the wp\_enqueue\_script function in my functions.php. I then added the script before my /body tag. I would appreciate any help as this has been causing me hours of frustration.
This is my code:
```
function theme_add_cycle_slide (){
wp_enqueue_script('jquery');
wp_enqueue_script('cycleall', get_stylesheet_directory_uri() . '/assets/scripts/jquery.cycle.all.js', array ('jquery'), null, true);
}
add_action ('wp_enqueue_script', 'theme_add_cycle_slide' );
<div id="slideshow">
<div style="width:250px; height:150px; background:red;"></div>
<div style="width:250px; height:150px; background:blue;"></div>
<div style="width:250px; height:150px; background:green;"></div>
<div style="width:250px; height:150px; background:yellow;"></div>
<div id="prev" style="float:left;">PREV</div>
<div id="next" style="float:right;">NEXT</div>
</div>
<script language="javascript">
jQuery(document).ready(function($) {
$('#slideshow').cycle({
fx: 'fade',
pause: 1
});
});
</script>
```
|
Problem was a simple misspelling.
The add\_action should be
add\_action ('wp\_enqueue\_scripts', 'theme\_add\_cycle\_slide' );
I wrote 'script'
|
230,426 |
<p>OK so - we need a solid .htaccess rule to make the following happen:</p>
<p>Deny ALL from visiting the site (they are taken to 'down for maintenance' page, but ALLOW for me and our developer. </p>
<p>Yes, there is a WordPress Plugin but we had a terrible time with it.</p>
<p>Here's our propsed .htaccess rule</p>
<pre><code>RewriteEngine On
RewriteBase /
RewriteCond %{REMOTE_ADDR} !^11\.111\.111\.111
RewriteCond %{REQUEST_URI} !^/maintenance\.html$
RewriteRule ^(.*)$ http://domain.com/maintenance.html [R=307,L]
</code></pre>
<p>First question please! How do we add a second IP address that is allowed to see the site in development?</p>
<p>Second question is - should this rule go FIRST above any other .htaccess rules in WordPress? WordPress does create its' own .htaccess so hence my question.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 230424,
"author": "LearntoExcel",
"author_id": 97108,
"author_profile": "https://wordpress.stackexchange.com/users/97108",
"pm_score": 2,
"selected": true,
"text": "<p>Problem was a simple misspelling.</p>\n\n<p>The add_action should be</p>\n\n<p>add_action ('wp_enqueue_scripts', 'theme_add_cycle_slide' );</p>\n\n<p>I wrote 'script'</p>\n"
},
{
"answer_id": 230428,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Try This one : </p>\n\n<pre><code> wp_register_script('cycleall', plugins_url('/assets/scripts/jquery.cycle.all.js', __FILE__), array('jquery'),'1.1', true);\n wp_enqueue_script('cycleall');\n</code></pre>\n\n<p>change script to scripts in <code>add_action()</code> should be</p>\n\n<pre><code>add_action ('wp_enqueue_scripts', 'theme_add_cycle_slide' );\n</code></pre>\n"
}
] |
2016/06/22
|
[
"https://wordpress.stackexchange.com/questions/230426",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93691/"
] |
OK so - we need a solid .htaccess rule to make the following happen:
Deny ALL from visiting the site (they are taken to 'down for maintenance' page, but ALLOW for me and our developer.
Yes, there is a WordPress Plugin but we had a terrible time with it.
Here's our propsed .htaccess rule
```
RewriteEngine On
RewriteBase /
RewriteCond %{REMOTE_ADDR} !^11\.111\.111\.111
RewriteCond %{REQUEST_URI} !^/maintenance\.html$
RewriteRule ^(.*)$ http://domain.com/maintenance.html [R=307,L]
```
First question please! How do we add a second IP address that is allowed to see the site in development?
Second question is - should this rule go FIRST above any other .htaccess rules in WordPress? WordPress does create its' own .htaccess so hence my question.
Thanks!
|
Problem was a simple misspelling.
The add\_action should be
add\_action ('wp\_enqueue\_scripts', 'theme\_add\_cycle\_slide' );
I wrote 'script'
|
230,480 |
<p>I've been wrestling with some code cobbled together for a function I found, first published circa 2009 and my inexperience with PHP has me at a loss.</p>
<p>The function is designed to count episodes in a podcast category, thus:</p>
<pre><code>function Get_Post_Number($postID){
$temp_query = $wp_query;
$postNumberQuery = new WP_Query(array (
'orderby' => 'date',
'order' => 'ASC',
'post_type' => 'any',
'category_name' =>'podcast-episodes',
'posts_per_page' => '-1'
));
$counter = 1;
$postCount = 0;
if($postNumberQuery->have_posts()) :
while ($postNumberQuery->have_posts()) : $postNumberQuery->the_post();
if ($postID == get_the_ID()){
$postCount = $counter;
} else {
$counter++;
}
endwhile; endif;
wp_reset_query();
$wp_query = $temp_query;
return $postCount;
}
</code></pre>
<p>As far as I can tell, this works fine. I created a shortcode to return the value in the query, which then resulted in the excerpt not showing. I then created a filter to do the same and the result was the same. No excerpt. Here I'll just post the shortcode:</p>
<pre><code>/**
* Create shortcode to display Episode count.
*/
function episodeNo() {
$epID = get_the_ID();
$epNumber = Get_Post_Number($epID);
echo 'Episode ' . $epNumber;
}
add_shortcode('episode','episodeNo');
</code></pre>
<p>Here is my query:</p>
<pre><code>$args = array(
'posts_per_page' => 3,
'category_name' => 'podcast-episodes'
);
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts()){
echo '<ul class="entries">';
while ( $query->have_posts() ) {
$query->the_post();
echo '<div class="entries-post">';
echo '<a href="' . get_permalink() . '">';
echo '<h1 class="entries-title">' . get_the_title() . '</h1>';
echo '</a>';
do_shortcode('[episode]');
echo '<div class="entries-excerpt">';
the_excerpt();
echo '</div>';
echo '</div>';
}
}
echo '</ul>';
}
/* Restore original Post Data */
wp_reset_postdata();
</code></pre>
<p>Now, if the shortcode runs <em>before</em> the_excerpt, it correctly displays the episode number but no excerpt.</p>
<p><strong>Title</strong></p>
<p>Episode 11</p>
<p><strong>Title</strong></p>
<p>Episode 10</p>
<p><strong>Title</strong></p>
<p>Episode 9</p>
<p>If it runs <em>after</em> the the_excerpt, it correctly displays the excerpt and the episode number:</p>
<p><strong>Title</strong></p>
<p>This week I cry into my coffee</p>
<p>Episode 11</p>
<p><strong>Title</strong></p>
<p>This week I approach a new design project</p>
<p>Episode 10</p>
<p><strong>Title</strong></p>
<p>This week I mostly play video games</p>
<p>Episode 9</p>
<p>Unfortunately, the design is such that episode must be displayed before excerpt.</p>
<p>The exact same occurs were I to use a filter that performed the same duty as the shortcode.</p>
<p>Does anyone have any idea why the_excerpt fails to display if called after this shortcode? I'm certain it's the way in which the episode number is calculated or returned, but know too little to correct it myself. Believe me, I have attempted to. At length.</p>
|
[
{
"answer_id": 230456,
"author": "J. Davis",
"author_id": 97201,
"author_profile": "https://wordpress.stackexchange.com/users/97201",
"pm_score": -1,
"selected": false,
"text": "<p>Wordpress is generally fine as long as you change the siteurl and homeurl in the database.</p>\n"
},
{
"answer_id": 230464,
"author": "tillinberlin",
"author_id": 26059,
"author_profile": "https://wordpress.stackexchange.com/users/26059",
"pm_score": 3,
"selected": false,
"text": "<p>While this might be not the easiest task for a beginner, it is very well possible – with a little help from some plugins. </p>\n\n<p>In a similar scenario I would usually install WordPress under a subdomain. When everything is looking ok to launch, I would recommend to first (always!) <strong>make a backup</strong> of everything. You can then change the base url (domain) either through the admin area in WordPress, which can be a bit tricky because once you switch you will get an error message. And you're logged out. But that only means that the domain was switched. I actually prefer to change the domain name via phpMyAdmin directly inside the options table instead.</p>\n\n<p>Finally there is one important step to take: WordPress writes all the links (inline page links and image urls) <strong>including</strong> the domain. So your site may first look a bit terrible, since no images are found – and inline links point to the old (sub-)domain. Using a plugin like <a href=\"https://wordpress.org/plugins/better-search-replace/\">Better Search Replace</a> can be of great help to find and replace the corrupt urls. You simply have to replace the old url string (e.g. \"<a href=\"http://subdomain.example.org\">http://subdomain.example.org</a>\") with the new url string (e.g. \"<a href=\"http://example.org\">http://example.org</a>\"). That should do.</p>\n"
},
{
"answer_id": 230506,
"author": "David",
"author_id": 31323,
"author_profile": "https://wordpress.stackexchange.com/users/31323",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming your domain is <code>mydomain.org</code>. Instead of installing WordPress under a different domain (<code>wordpress.mydomain.org</code>) you could install WordPress on your local machine (using <a href=\"https://www.apachefriends.org/index.html\" rel=\"nofollow\">XAMPP</a> <a href=\"https://www.mamp.info/en/\" rel=\"nofollow\">MAMP</a> or a virtual box) and resolving the original domain to your local computer by editing your systems <a href=\"https://en.wikipedia.org/wiki/Hosts_(file)\" rel=\"nofollow\">host file</a> and add the following line:</p>\n\n<pre><code>127.0.0.1 mydomain.org\n</code></pre>\n\n<p>Now every request to <code>mydomain.org</code> (from your computer) will be resolved to your local host (everyone else will still see the original static page, of course). This way you can configure WordPress as you want without the necessity to perform search and replace on the database once you switched to live.</p>\n\n<p>The last step would be to set up WordPress (copy the files, setup <code>wp-config.php</code>) and migrate the database dump to your web host and remove the entry from you hosts file.</p>\n"
},
{
"answer_id": 230666,
"author": "Forza",
"author_id": 33143,
"author_profile": "https://wordpress.stackexchange.com/users/33143",
"pm_score": 0,
"selected": false,
"text": "<p>If you are a beginner in WordPress, your best option would be to use a plugin like <a href=\"https://nl.wordpress.org/plugins/duplicator/\" rel=\"nofollow\">Duplicator</a>. This allows you to move your entire site to the new location and change all URL's at once. Please avoid manually changing URL's in your database as that can be tricky, and it's easy to overlook some of them.</p>\n\n<p>Duplicator will take care of everything. Here's a <a href=\"https://www.youtube.com/watch?v=tdP3quWLM0Q\" rel=\"nofollow\">good tutorial</a> video if you need one.</p>\n\n<p>In case Duplicator doesn't work on your server, you can also try a similar plugin: <a href=\"https://nl.wordpress.org/plugins/all-in-one-wp-migration/\" rel=\"nofollow\">All in One WP Migration</a></p>\n\n<p>With these plugins, you can create your site on your own system or another (sub)domain. Then once it's finished you can make the transfer.</p>\n"
},
{
"answer_id": 230926,
"author": "Sabbir H",
"author_id": 22673,
"author_profile": "https://wordpress.stackexchange.com/users/22673",
"pm_score": 0,
"selected": false,
"text": "<p>I love WordPress, It is easy to use and gives me a lot of flexibility to play around codes. You know, All codes are opensource. So I can learn, make changes as I like. Even a newbie WordPress can be easy to use. If you keep using WordPress for a few days you will find that you are in love with WordPress as well!</p>\n\n<p>I personally follow following steps for static site to WordPress conversion....</p>\n\n<ol>\n<li>Do a Google with this.... site:domain.com</li>\n<li>I get all the URL that indexed by google and I make a xl sheet</li>\n<li>I install WordPress on a directory like this domain.com/wp</li>\n<li>I make sure the new WP installation is search block from here Settings >> Reading >> Discourage Search Engines</li>\n<li>I develop the site there.</li>\n<li>I use 301 redirect plugin to move old URL to new URL</li>\n<li>I make the site live by changing Site URL and Home page URL from here settings >> general settings</li>\n<li>I move all the files from \"wp\" directory to root and keep a backup for all the root fils</li>\n<li>I use better search and replace to replace this url domain.com/wp to domain.com</li>\n<li>Now I need to enable search engine to index your new WordPress site</li>\n<li>I double check all the 301 redirect is done correctly. It is really important if you do not want to loose any SEO ranking for your static site.</li>\n<li>Finally I am done</li>\n</ol>\n\n<p>It is fairly easy for me and I believe most of the developers love this procedure. but if I would not recommend you to follow my steps if you are not familiar with FTP and basic WordPress usages. </p>\n\n<p>Hope this helps.</p>\n\n<p>Sabbir H</p>\n"
}
] |
2016/06/22
|
[
"https://wordpress.stackexchange.com/questions/230480",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94803/"
] |
I've been wrestling with some code cobbled together for a function I found, first published circa 2009 and my inexperience with PHP has me at a loss.
The function is designed to count episodes in a podcast category, thus:
```
function Get_Post_Number($postID){
$temp_query = $wp_query;
$postNumberQuery = new WP_Query(array (
'orderby' => 'date',
'order' => 'ASC',
'post_type' => 'any',
'category_name' =>'podcast-episodes',
'posts_per_page' => '-1'
));
$counter = 1;
$postCount = 0;
if($postNumberQuery->have_posts()) :
while ($postNumberQuery->have_posts()) : $postNumberQuery->the_post();
if ($postID == get_the_ID()){
$postCount = $counter;
} else {
$counter++;
}
endwhile; endif;
wp_reset_query();
$wp_query = $temp_query;
return $postCount;
}
```
As far as I can tell, this works fine. I created a shortcode to return the value in the query, which then resulted in the excerpt not showing. I then created a filter to do the same and the result was the same. No excerpt. Here I'll just post the shortcode:
```
/**
* Create shortcode to display Episode count.
*/
function episodeNo() {
$epID = get_the_ID();
$epNumber = Get_Post_Number($epID);
echo 'Episode ' . $epNumber;
}
add_shortcode('episode','episodeNo');
```
Here is my query:
```
$args = array(
'posts_per_page' => 3,
'category_name' => 'podcast-episodes'
);
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts()){
echo '<ul class="entries">';
while ( $query->have_posts() ) {
$query->the_post();
echo '<div class="entries-post">';
echo '<a href="' . get_permalink() . '">';
echo '<h1 class="entries-title">' . get_the_title() . '</h1>';
echo '</a>';
do_shortcode('[episode]');
echo '<div class="entries-excerpt">';
the_excerpt();
echo '</div>';
echo '</div>';
}
}
echo '</ul>';
}
/* Restore original Post Data */
wp_reset_postdata();
```
Now, if the shortcode runs *before* the\_excerpt, it correctly displays the episode number but no excerpt.
**Title**
Episode 11
**Title**
Episode 10
**Title**
Episode 9
If it runs *after* the the\_excerpt, it correctly displays the excerpt and the episode number:
**Title**
This week I cry into my coffee
Episode 11
**Title**
This week I approach a new design project
Episode 10
**Title**
This week I mostly play video games
Episode 9
Unfortunately, the design is such that episode must be displayed before excerpt.
The exact same occurs were I to use a filter that performed the same duty as the shortcode.
Does anyone have any idea why the\_excerpt fails to display if called after this shortcode? I'm certain it's the way in which the episode number is calculated or returned, but know too little to correct it myself. Believe me, I have attempted to. At length.
|
While this might be not the easiest task for a beginner, it is very well possible – with a little help from some plugins.
In a similar scenario I would usually install WordPress under a subdomain. When everything is looking ok to launch, I would recommend to first (always!) **make a backup** of everything. You can then change the base url (domain) either through the admin area in WordPress, which can be a bit tricky because once you switch you will get an error message. And you're logged out. But that only means that the domain was switched. I actually prefer to change the domain name via phpMyAdmin directly inside the options table instead.
Finally there is one important step to take: WordPress writes all the links (inline page links and image urls) **including** the domain. So your site may first look a bit terrible, since no images are found – and inline links point to the old (sub-)domain. Using a plugin like [Better Search Replace](https://wordpress.org/plugins/better-search-replace/) can be of great help to find and replace the corrupt urls. You simply have to replace the old url string (e.g. "<http://subdomain.example.org>") with the new url string (e.g. "<http://example.org>"). That should do.
|
230,552 |
<p>As we see in <a href="https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/link-template.php#L2179" rel="nofollow">the source</a>, we can apply filters for <code>$attr</code>.</p>
<p>So I create something like this</p>
<pre><code>function asdff(){
return 'class="iamclass"';
}
add_filter('get_next_posts_link', 'asdff',10,2);
</code></pre>
<p>or</p>
<pre><code>function asdff($attr){
$attr .= "class='iamclass'";
return $attr;
}
add_filter('get_next_posts_link', 'asdff',10,2);
</code></pre>
<p>It should be like this at front end <code><a href="#nextpage" class='iamclass'></code>, but it doesnt work. My class doesnt appear. How to achive that, did i miss something at <code>add_filter</code> ?</p>
|
[
{
"answer_id": 230456,
"author": "J. Davis",
"author_id": 97201,
"author_profile": "https://wordpress.stackexchange.com/users/97201",
"pm_score": -1,
"selected": false,
"text": "<p>Wordpress is generally fine as long as you change the siteurl and homeurl in the database.</p>\n"
},
{
"answer_id": 230464,
"author": "tillinberlin",
"author_id": 26059,
"author_profile": "https://wordpress.stackexchange.com/users/26059",
"pm_score": 3,
"selected": false,
"text": "<p>While this might be not the easiest task for a beginner, it is very well possible – with a little help from some plugins. </p>\n\n<p>In a similar scenario I would usually install WordPress under a subdomain. When everything is looking ok to launch, I would recommend to first (always!) <strong>make a backup</strong> of everything. You can then change the base url (domain) either through the admin area in WordPress, which can be a bit tricky because once you switch you will get an error message. And you're logged out. But that only means that the domain was switched. I actually prefer to change the domain name via phpMyAdmin directly inside the options table instead.</p>\n\n<p>Finally there is one important step to take: WordPress writes all the links (inline page links and image urls) <strong>including</strong> the domain. So your site may first look a bit terrible, since no images are found – and inline links point to the old (sub-)domain. Using a plugin like <a href=\"https://wordpress.org/plugins/better-search-replace/\">Better Search Replace</a> can be of great help to find and replace the corrupt urls. You simply have to replace the old url string (e.g. \"<a href=\"http://subdomain.example.org\">http://subdomain.example.org</a>\") with the new url string (e.g. \"<a href=\"http://example.org\">http://example.org</a>\"). That should do.</p>\n"
},
{
"answer_id": 230506,
"author": "David",
"author_id": 31323,
"author_profile": "https://wordpress.stackexchange.com/users/31323",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming your domain is <code>mydomain.org</code>. Instead of installing WordPress under a different domain (<code>wordpress.mydomain.org</code>) you could install WordPress on your local machine (using <a href=\"https://www.apachefriends.org/index.html\" rel=\"nofollow\">XAMPP</a> <a href=\"https://www.mamp.info/en/\" rel=\"nofollow\">MAMP</a> or a virtual box) and resolving the original domain to your local computer by editing your systems <a href=\"https://en.wikipedia.org/wiki/Hosts_(file)\" rel=\"nofollow\">host file</a> and add the following line:</p>\n\n<pre><code>127.0.0.1 mydomain.org\n</code></pre>\n\n<p>Now every request to <code>mydomain.org</code> (from your computer) will be resolved to your local host (everyone else will still see the original static page, of course). This way you can configure WordPress as you want without the necessity to perform search and replace on the database once you switched to live.</p>\n\n<p>The last step would be to set up WordPress (copy the files, setup <code>wp-config.php</code>) and migrate the database dump to your web host and remove the entry from you hosts file.</p>\n"
},
{
"answer_id": 230666,
"author": "Forza",
"author_id": 33143,
"author_profile": "https://wordpress.stackexchange.com/users/33143",
"pm_score": 0,
"selected": false,
"text": "<p>If you are a beginner in WordPress, your best option would be to use a plugin like <a href=\"https://nl.wordpress.org/plugins/duplicator/\" rel=\"nofollow\">Duplicator</a>. This allows you to move your entire site to the new location and change all URL's at once. Please avoid manually changing URL's in your database as that can be tricky, and it's easy to overlook some of them.</p>\n\n<p>Duplicator will take care of everything. Here's a <a href=\"https://www.youtube.com/watch?v=tdP3quWLM0Q\" rel=\"nofollow\">good tutorial</a> video if you need one.</p>\n\n<p>In case Duplicator doesn't work on your server, you can also try a similar plugin: <a href=\"https://nl.wordpress.org/plugins/all-in-one-wp-migration/\" rel=\"nofollow\">All in One WP Migration</a></p>\n\n<p>With these plugins, you can create your site on your own system or another (sub)domain. Then once it's finished you can make the transfer.</p>\n"
},
{
"answer_id": 230926,
"author": "Sabbir H",
"author_id": 22673,
"author_profile": "https://wordpress.stackexchange.com/users/22673",
"pm_score": 0,
"selected": false,
"text": "<p>I love WordPress, It is easy to use and gives me a lot of flexibility to play around codes. You know, All codes are opensource. So I can learn, make changes as I like. Even a newbie WordPress can be easy to use. If you keep using WordPress for a few days you will find that you are in love with WordPress as well!</p>\n\n<p>I personally follow following steps for static site to WordPress conversion....</p>\n\n<ol>\n<li>Do a Google with this.... site:domain.com</li>\n<li>I get all the URL that indexed by google and I make a xl sheet</li>\n<li>I install WordPress on a directory like this domain.com/wp</li>\n<li>I make sure the new WP installation is search block from here Settings >> Reading >> Discourage Search Engines</li>\n<li>I develop the site there.</li>\n<li>I use 301 redirect plugin to move old URL to new URL</li>\n<li>I make the site live by changing Site URL and Home page URL from here settings >> general settings</li>\n<li>I move all the files from \"wp\" directory to root and keep a backup for all the root fils</li>\n<li>I use better search and replace to replace this url domain.com/wp to domain.com</li>\n<li>Now I need to enable search engine to index your new WordPress site</li>\n<li>I double check all the 301 redirect is done correctly. It is really important if you do not want to loose any SEO ranking for your static site.</li>\n<li>Finally I am done</li>\n</ol>\n\n<p>It is fairly easy for me and I believe most of the developers love this procedure. but if I would not recommend you to follow my steps if you are not familiar with FTP and basic WordPress usages. </p>\n\n<p>Hope this helps.</p>\n\n<p>Sabbir H</p>\n"
}
] |
2016/06/23
|
[
"https://wordpress.stackexchange.com/questions/230552",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44538/"
] |
As we see in [the source](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/link-template.php#L2179), we can apply filters for `$attr`.
So I create something like this
```
function asdff(){
return 'class="iamclass"';
}
add_filter('get_next_posts_link', 'asdff',10,2);
```
or
```
function asdff($attr){
$attr .= "class='iamclass'";
return $attr;
}
add_filter('get_next_posts_link', 'asdff',10,2);
```
It should be like this at front end `<a href="#nextpage" class='iamclass'>`, but it doesnt work. My class doesnt appear. How to achive that, did i miss something at `add_filter` ?
|
While this might be not the easiest task for a beginner, it is very well possible – with a little help from some plugins.
In a similar scenario I would usually install WordPress under a subdomain. When everything is looking ok to launch, I would recommend to first (always!) **make a backup** of everything. You can then change the base url (domain) either through the admin area in WordPress, which can be a bit tricky because once you switch you will get an error message. And you're logged out. But that only means that the domain was switched. I actually prefer to change the domain name via phpMyAdmin directly inside the options table instead.
Finally there is one important step to take: WordPress writes all the links (inline page links and image urls) **including** the domain. So your site may first look a bit terrible, since no images are found – and inline links point to the old (sub-)domain. Using a plugin like [Better Search Replace](https://wordpress.org/plugins/better-search-replace/) can be of great help to find and replace the corrupt urls. You simply have to replace the old url string (e.g. "<http://subdomain.example.org>") with the new url string (e.g. "<http://example.org>"). That should do.
|
230,613 |
<p>I have this code in my header.php and its working properly except showing li's without menu-item class, its showing them with page-item instead. this is when i dont have a menu created from admin and assigned it to a menu location.</p>
<p>So the menu is wordpress default menu which shows all the pages added. Is there a way to add menu item class with them.</p>
<p>I tried following code but its not working.</p>
<pre><code>function li_nav_class($classes, $item, $args){
$classes[] = 'menu-item ';
return $classes;
}
add_filter('nav_menu_css_class' , 'li_nav_class' , 1 , 3);
</code></pre>
|
[
{
"answer_id": 230641,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": false,
"text": "<p>The default fallback in <code>wp_nav_menu</code> for a menu that doesn't exist/isn't registered is <a href=\"https://developer.wordpress.org/reference/functions/wp_page_menu/\" rel=\"nofollow\"><code>wp_page_menu</code></a>, which unfortunately does not support the same arguments/implement the same level of \"customisability\" - you either need to create a custom fallback, or remove the fallback entirely (so that the user is forced to set a menu).</p>\n"
},
{
"answer_id": 238262,
"author": "Muhammad Riyaz",
"author_id": 63027,
"author_profile": "https://wordpress.stackexchange.com/users/63027",
"pm_score": 0,
"selected": false,
"text": "<p>Try below code with required modifications</p>\n\n<pre><code><?php\n if (has_nav_menu('primary_navigation')) :\n wp_nav_menu(['theme_location' => 'primary_navigation', 'menu_class' => 'nav']);\n endif;\n ?>\n</code></pre>\n\n<p>for adding class to ul : <code>'menu_class' => 'nav'</code></p>\n\n<p>Also try <a href=\"http://sevenspark.com/how-to/how-to-add-a-custom-class-to-a-wordpress-menu-item\" rel=\"nofollow\">this</a> link.</p>\n"
}
] |
2016/06/24
|
[
"https://wordpress.stackexchange.com/questions/230613",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97306/"
] |
I have this code in my header.php and its working properly except showing li's without menu-item class, its showing them with page-item instead. this is when i dont have a menu created from admin and assigned it to a menu location.
So the menu is wordpress default menu which shows all the pages added. Is there a way to add menu item class with them.
I tried following code but its not working.
```
function li_nav_class($classes, $item, $args){
$classes[] = 'menu-item ';
return $classes;
}
add_filter('nav_menu_css_class' , 'li_nav_class' , 1 , 3);
```
|
The default fallback in `wp_nav_menu` for a menu that doesn't exist/isn't registered is [`wp_page_menu`](https://developer.wordpress.org/reference/functions/wp_page_menu/), which unfortunately does not support the same arguments/implement the same level of "customisability" - you either need to create a custom fallback, or remove the fallback entirely (so that the user is forced to set a menu).
|
230,686 |
<p>I have a multisite wordpress with multiple localized sites (es_ES, de_DE, it_IT).
I want improve page speed by caching wordpress translation file.</p>
<p>My code works (inspired by <a href="http://blog.blackfire.io/improving-wordpress.html" rel="nofollow noreferrer">Tristan Darricau</a>)! and my page speed is improved of 0.50 seconds.</p>
<p>Now, my question is: My code is right or can break something (core, theme, plug-in), i have tested and it seem to work, but i'm a newbie of wp!</p>
<pre><code>/**
* Cache translation
* @param boolean $override
* @param string $domain
* @param string $mofile
* @return boolean
*/
function my_override_load_textdomain($override, $domain, $mofile) {
global $l10n;
// check if $mofile exisiste and is readable
if ( !(is_file($mofile) && is_readable($mofile)) ){
return false;
}
// creates a unique key for cache
$key = md5($mofile);
// I try to retrive data from cache
$data = wp_cache_get($key, $domain);
// Retrieve the last modified date of the translation files
$mtime = filemtime($mofile);
$mo = new \MO();
// if cache not return data or data it's old
if ( !$data || !isset($data['mtime']) || ($mtime > $data['mtime']) ) {
// retrive data from MO file
if ( $mo->import_from_file( $mofile ) ){
$data = array(
'mtime' => $mtime,
'entries' => $mo->entries,
'headers' => $mo->headers
);
// save data in cache
wp_cache_set($key, $data, $domain, 0);
} else {
return false;
}
} else {
$mo->entries = $data['entries'];
$mo->headers = $data['headers'];
}
if ( isset( $l10n[$domain] ) ) {
$mo->merge_with( $l10n[$domain] );
}
$l10n[$domain] = &$mo;
return true;
}
add_filter('override_load_textdomain', 'my_override_load_textdomain',1,3);
</code></pre>
<p>Side note: i know this is a question for <a href="https://codereview.stackexchange.com/">code review stack's platform</a>, but all wordpress'guys are here, and this is a question for wordpress'guys.</p>
<p>I apologize for my bad English</p>
|
[
{
"answer_id": 230685,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 1,
"selected": false,
"text": "<p>No, you cannot (easily) choose what tag ID is assigned. It's not random - it's the next ID available after the last one that was created in the database.</p>\n\n<p>If you <em>really</em> want to control tag IDs, you'll need to clear your database and start fresh, and create each tag in the order you want their IDs to be (and you won't be able to change them afterwards without potentially breaking things).</p>\n\n<p>However, if you need this, there's probably something else you're not doing right...</p>\n"
},
{
"answer_id": 319908,
"author": "Richard Zack",
"author_id": 140624,
"author_profile": "https://wordpress.stackexchange.com/users/140624",
"pm_score": 0,
"selected": false,
"text": "<p>It is possible for intermediate-advanced users to change this by modifying the Wordpress database directly, however this is usually not recommended. For example, to change category with tag_id=21 to tag_id=9999, you could run direct database queries like:</p>\n\n<pre><code>update wp_terms set term_id=9999 where term_id=21;\nupdate wp_term_taxonomy set term_id=9999 where term_id=21;\n</code></pre>\n"
}
] |
2016/06/25
|
[
"https://wordpress.stackexchange.com/questions/230686",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92207/"
] |
I have a multisite wordpress with multiple localized sites (es\_ES, de\_DE, it\_IT).
I want improve page speed by caching wordpress translation file.
My code works (inspired by [Tristan Darricau](http://blog.blackfire.io/improving-wordpress.html))! and my page speed is improved of 0.50 seconds.
Now, my question is: My code is right or can break something (core, theme, plug-in), i have tested and it seem to work, but i'm a newbie of wp!
```
/**
* Cache translation
* @param boolean $override
* @param string $domain
* @param string $mofile
* @return boolean
*/
function my_override_load_textdomain($override, $domain, $mofile) {
global $l10n;
// check if $mofile exisiste and is readable
if ( !(is_file($mofile) && is_readable($mofile)) ){
return false;
}
// creates a unique key for cache
$key = md5($mofile);
// I try to retrive data from cache
$data = wp_cache_get($key, $domain);
// Retrieve the last modified date of the translation files
$mtime = filemtime($mofile);
$mo = new \MO();
// if cache not return data or data it's old
if ( !$data || !isset($data['mtime']) || ($mtime > $data['mtime']) ) {
// retrive data from MO file
if ( $mo->import_from_file( $mofile ) ){
$data = array(
'mtime' => $mtime,
'entries' => $mo->entries,
'headers' => $mo->headers
);
// save data in cache
wp_cache_set($key, $data, $domain, 0);
} else {
return false;
}
} else {
$mo->entries = $data['entries'];
$mo->headers = $data['headers'];
}
if ( isset( $l10n[$domain] ) ) {
$mo->merge_with( $l10n[$domain] );
}
$l10n[$domain] = &$mo;
return true;
}
add_filter('override_load_textdomain', 'my_override_load_textdomain',1,3);
```
Side note: i know this is a question for [code review stack's platform](https://codereview.stackexchange.com/), but all wordpress'guys are here, and this is a question for wordpress'guys.
I apologize for my bad English
|
No, you cannot (easily) choose what tag ID is assigned. It's not random - it's the next ID available after the last one that was created in the database.
If you *really* want to control tag IDs, you'll need to clear your database and start fresh, and create each tag in the order you want their IDs to be (and you won't be able to change them afterwards without potentially breaking things).
However, if you need this, there's probably something else you're not doing right...
|
230,779 |
<p>Recently i have install a wordpress multi-site for a client.<br>
After the initial launch client had change mind to transfer the site to a another domain, i have moved the WP multi-site successfully, i have no issue on front end, it's working fine i can access site 1 and site 2.</p>
<p>My issue is in back-end, when i access wp-admin dashboard under my-site, when i try access site1 and site2 dashboard my url is not changing, simply dash board not moving, the url for the site1 dashboard and site2 dashboard keep stay same, when i check the my sql table for site1 and site2 "siteurl" they are not reflecting home url for the sub site running in sub directory mode. when i change them manually they it worked, i could access dashboards of site1 and site2, but when i update site1 or site2 the url get reset again on site-url on sql database on site1 and site2, which i couldn't access again.</p>
<p>i have De-activate plugins to find the root for the issue, no results soo far, and i'm running the standard .htaccess as below</p>
<pre><code>RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
</code></pre>
<p>Below my wp-config settings</p>
<pre>
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', false);
define('DOMAIN_CURRENT_SITE', 'dhaman.net/ar');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 2);
</pre>
<p>and my site url are </p>
<p><a href="http://dhaman.net/ar" rel="nofollow">http://dhaman.net/ar</a><br>
<a href="http://dhaman.net/en" rel="nofollow">http://dhaman.net/en</a></p>
<p>Any body can shed some light on this matter, how to stop the site-url getting change in site1 and site2 sql databse</p>
|
[
{
"answer_id": 230718,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 4,
"selected": true,
"text": "<p>Each of the files you have mentioned are theme files. When you upgrade WordPress itself, it will not touch any themes (or plugins) you have installed, whether or not you have modified them.</p>\n\n<p>If this was a theme you created yourself, then you have no worries at all.</p>\n\n<p>However, if this was a theme created by someone else, for example a WordPress default theme, you can still update WordPress... but you need to be careful before updating the theme (if any updates are available for it).</p>\n\n<p>Yes, you can save your modifications and then re-apply them after updating the theme, but the best thing to do is not to make these modifications directly in the first place, and rather use a child theme.</p>\n\n<p>It's not too hard to <a href=\"https://codex.wordpress.org/Child_Themes\">set up a child theme</a>, and doing so will mean that any of your modifications are kept safe. Basically, you just copy the pre-existing archive.php, search.php etc., make your modifications, and store them in your child theme's folder. WordPress will then use these modified files instead of the originals. When you update the original theme, it's then up to you whether you fold any new changes and enhancements into your child theme.</p>\n"
},
{
"answer_id": 329035,
"author": "GRI2A",
"author_id": 161457,
"author_profile": "https://wordpress.stackexchange.com/users/161457",
"pm_score": 0,
"selected": false,
"text": "<p>Rather than copying most of your files to a child theme, A quicker (but probably not so clean) fix is simply to insert a line of code in eg. functions.php that is include='custom.php';\nYou simply put all your custom code in custom.php.\nIf you update your theme all you need to do is reinsert the include line</p>\n"
}
] |
2016/06/27
|
[
"https://wordpress.stackexchange.com/questions/230779",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97402/"
] |
Recently i have install a wordpress multi-site for a client.
After the initial launch client had change mind to transfer the site to a another domain, i have moved the WP multi-site successfully, i have no issue on front end, it's working fine i can access site 1 and site 2.
My issue is in back-end, when i access wp-admin dashboard under my-site, when i try access site1 and site2 dashboard my url is not changing, simply dash board not moving, the url for the site1 dashboard and site2 dashboard keep stay same, when i check the my sql table for site1 and site2 "siteurl" they are not reflecting home url for the sub site running in sub directory mode. when i change them manually they it worked, i could access dashboards of site1 and site2, but when i update site1 or site2 the url get reset again on site-url on sql database on site1 and site2, which i couldn't access again.
i have De-activate plugins to find the root for the issue, no results soo far, and i'm running the standard .htaccess as below
```
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
```
Below my wp-config settings
```
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', false);
define('DOMAIN_CURRENT_SITE', 'dhaman.net/ar');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 2);
```
and my site url are
<http://dhaman.net/ar>
<http://dhaman.net/en>
Any body can shed some light on this matter, how to stop the site-url getting change in site1 and site2 sql databse
|
Each of the files you have mentioned are theme files. When you upgrade WordPress itself, it will not touch any themes (or plugins) you have installed, whether or not you have modified them.
If this was a theme you created yourself, then you have no worries at all.
However, if this was a theme created by someone else, for example a WordPress default theme, you can still update WordPress... but you need to be careful before updating the theme (if any updates are available for it).
Yes, you can save your modifications and then re-apply them after updating the theme, but the best thing to do is not to make these modifications directly in the first place, and rather use a child theme.
It's not too hard to [set up a child theme](https://codex.wordpress.org/Child_Themes), and doing so will mean that any of your modifications are kept safe. Basically, you just copy the pre-existing archive.php, search.php etc., make your modifications, and store them in your child theme's folder. WordPress will then use these modified files instead of the originals. When you update the original theme, it's then up to you whether you fold any new changes and enhancements into your child theme.
|
230,836 |
<p>In my site I'm using the Product Archive Customizer plugin for WooCommerce. Great plugin. However, there is an option to set the qty of products shown per page. The next piece of code is responsible for that:</p>
<pre><code>$wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'wc_pac_products_per_page', array(
'label' => __( 'Products per page', 'woocommerce-product-archive-customiser' ),
'section' => 'wc_pac',
'settings' => 'wc_pac_products_per_page',
'type' => 'select',
'choices' => array(
'2' => '2',
'3' => '3',
----------
'23' => '23',
'24' => '24',
),
) ) );
</code></pre>
<p>I do want to add another qty to the 'choices' array and I'm told it is bad practice to add that in the original plugin file. In that case it will be overwritten with an update of the plugin.</p>
<p>I read up on a lot of array related topics but I can't get it under my thick skull.</p>
<p>What code do I have to add to my themes <code>functions.php</code> file to achieve that? </p>
|
[
{
"answer_id": 230845,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know what hook Woocommerce uses to add that customizer code, but in your <code>functions.php</code> you'll have to hook your own function on a later time, like this (the last number is the lower priority):</p>\n\n<pre><code>add_action ('the_name_of_that_hook','wpse_280836_mycontrol', 99)\n</code></pre>\n\n<p>Now in the function you are hooking, you must first remove the existing control and the add your own:</p>\n\n<pre><code>function wpse_280836_mycontrol () {\n $wp_customize->remove_control('wc_pac_products_per_page');\n $wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'wc_pac_products_per_page', array(\n 'label' => __( 'Products per page', 'woocommerce-product-archive-customiser' ),\n 'section' => 'wc_pac',\n 'settings' => 'wc_pac_products_per_page',\n 'type' => 'select',\n 'choices' => array(\n 'mystuff' => 'myotherstuff',\n '3' => '3',\n ----------\n '23' => '23',\n '24' => '24',\n\n ),\n ) ) );\n</code></pre>\n\n<p>Please note, that I don't know what this control does, because I'm not a Woocommerce specialist. Somewhere else in the code there may be a check that only allows the given choices. That would make your modification invalid.</p>\n"
},
{
"answer_id": 230905,
"author": "A3O",
"author_id": 64290,
"author_profile": "https://wordpress.stackexchange.com/users/64290",
"pm_score": 2,
"selected": true,
"text": "<p>I tried another solution and that did the trick. I found in the WooCommerce docs this little snippet: </p>\n\n<p><code>// Display 24 products per page. Goes in functions.php \nadd_filter( 'loop_shop_per_page', create_function( '$cols', 'return 24;' ), 20 );</code>. </p>\n\n<p>It is overriding the settings in the customizer. I only have to change the number '24' to my liking.</p>\n"
}
] |
2016/06/27
|
[
"https://wordpress.stackexchange.com/questions/230836",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64290/"
] |
In my site I'm using the Product Archive Customizer plugin for WooCommerce. Great plugin. However, there is an option to set the qty of products shown per page. The next piece of code is responsible for that:
```
$wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'wc_pac_products_per_page', array(
'label' => __( 'Products per page', 'woocommerce-product-archive-customiser' ),
'section' => 'wc_pac',
'settings' => 'wc_pac_products_per_page',
'type' => 'select',
'choices' => array(
'2' => '2',
'3' => '3',
----------
'23' => '23',
'24' => '24',
),
) ) );
```
I do want to add another qty to the 'choices' array and I'm told it is bad practice to add that in the original plugin file. In that case it will be overwritten with an update of the plugin.
I read up on a lot of array related topics but I can't get it under my thick skull.
What code do I have to add to my themes `functions.php` file to achieve that?
|
I tried another solution and that did the trick. I found in the WooCommerce docs this little snippet:
`// Display 24 products per page. Goes in functions.php
add_filter( 'loop_shop_per_page', create_function( '$cols', 'return 24;' ), 20 );`.
It is overriding the settings in the customizer. I only have to change the number '24' to my liking.
|
230,880 |
<p>I have created a WordPress page that has this simple PHP code:</p>
<pre><code><?php
$result = array(
'State' => 'Done',
'ID' => 1
);
wp_send_json( $result );
?>
</code></pre>
<p>When submitting a form in another page using Ajax(JQuery) it calls this PHP page, then in the JQuery method i try to read the returned value from the PHP page using this code:</p>
<pre><code>$( '#contact_form' ).bootstrapValidator({
fields: {
// ...
},
submitHandler: function( formInstance ) {
$.post( "../send-message", $("#contact_form").serialize(), function( result ) {
alert( result );
});
}
});
</code></pre>
<p>But it actually returns the whole PHP page with its WordPress theme code used in addition to the passed parameters, as shown here:</p>
<p><a href="https://i.stack.imgur.com/6MpSQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6MpSQ.jpg" alt="enter image description here"></a></p>
<p>My question is: <strong>How can i return a PHP value from a WordPress page to a JQuery function?</strong></p>
|
[
{
"answer_id": 230882,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>How can i return a PHP value from a WordPress page to a JQuery\n function?</p>\n</blockquote>\n\n<p>Use <a href=\"https://developer.wordpress.org/reference/functions/wp_localize_script/\" rel=\"nofollow\"><code>wp_localize_script</code></a> to create an object and pass it to the JavaScript.</p>\n"
},
{
"answer_id": 230989,
"author": "Dimon Smus",
"author_id": 95121,
"author_profile": "https://wordpress.stackexchange.com/users/95121",
"pm_score": 1,
"selected": false,
"text": "<pre><code>wp_send_json( $result );\nif ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {\n\n wp_die();\n}\n</code></pre>\n\n<p><strong>UPD</strong></p>\n\n<p>The besat way to use ajax requests with wp is to use wp native ajax actions</p>\n\n<pre><code>add_action( 'wp_ajax_my_action', 'my_action_callback' );\nadd_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n\n<p>so you need to make post request to admin-ajax.php</p>\n\n<pre><code>wp_enqueue_script( 'frontend-js', PATH_TO_JS . '/script.js' );\nwp_localize_script( 'frontend-js',\n 'wpUser',\n [\n 'ajaxUrl' => admin_url( 'admin-ajax.php' ),\n ] );\n\n$.post( wpUser.ajaxUrl, { action: 'my_action' } );\n</code></pre>\n"
}
] |
2016/06/28
|
[
"https://wordpress.stackexchange.com/questions/230880",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97480/"
] |
I have created a WordPress page that has this simple PHP code:
```
<?php
$result = array(
'State' => 'Done',
'ID' => 1
);
wp_send_json( $result );
?>
```
When submitting a form in another page using Ajax(JQuery) it calls this PHP page, then in the JQuery method i try to read the returned value from the PHP page using this code:
```
$( '#contact_form' ).bootstrapValidator({
fields: {
// ...
},
submitHandler: function( formInstance ) {
$.post( "../send-message", $("#contact_form").serialize(), function( result ) {
alert( result );
});
}
});
```
But it actually returns the whole PHP page with its WordPress theme code used in addition to the passed parameters, as shown here:
[](https://i.stack.imgur.com/6MpSQ.jpg)
My question is: **How can i return a PHP value from a WordPress page to a JQuery function?**
|
>
> How can i return a PHP value from a WordPress page to a JQuery
> function?
>
>
>
Use [`wp_localize_script`](https://developer.wordpress.org/reference/functions/wp_localize_script/) to create an object and pass it to the JavaScript.
|
230,888 |
<p>I've ran into this issue where WordPress requests my FTP login credentials.</p>
<p>So far I've tried:</p>
<ul>
<li>chown</li>
<li>change user</li>
<li>change file permissions</li>
<li>edited wp-config.php</li>
</ul>
<p>None of it seems to work. The server I'm hosting it on is a VPS. I don't have much info from it. I am able to connect to my FTP using FileZilla but WordPress doesn't seem to be able to connect to it. Is there additional info I should request from my web host to properly set this up?</p>
<p>EDIT:</p>
<p>I haven't looked into httpd.conf yet. The owner of the public_html directory is root. I changed the permissions and owner to root. Is that the wrong practice? </p>
<p>I spoke to my server guy this morning, the server is listening to port 22 but on the hardware firewall, the public IP is nat from port 2232 to the server's port 22. But the server doesn't allow wordpress webui to enter 2232 (the port i'm using for SSH).</p>
<p>This is the additional bit I added to wp-config.php:</p>
<pre><code>define( 'FTP_USER', 'root' );
define( 'FTP_PASS', 'ftp-password' );
define( 'FTP_HOST', '123.123.123.123:2232' );
</code></pre>
|
[
{
"answer_id": 230968,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": true,
"text": "<p>Guess it needs to be said first - it is a bad idea in general to just let anyone that succeeded to trick you into uploading his PHP onto your server to actually be able to write to your code directories. It is double problematic if you let him access to your root credentials and write to anywhere on your server.</p>\n\n<p>That said, it sounds like you just don't have an FTP server installed on your server. SFTP is different from FTP and being able to access via one do not ensure access with the other.</p>\n\n<p>You should login to your server, run an FTP command with the credentials you put in the <code>wp-config</code> to first make sure you can connect and access the relevant directories. Once you can properly connect woth the FTP command on your server you can use the same credentials in your config.</p>\n"
},
{
"answer_id": 230979,
"author": "chiragpatel",
"author_id": 97397,
"author_profile": "https://wordpress.stackexchange.com/users/97397",
"pm_score": -1,
"selected": false,
"text": "<p>1) The first thing you have to do is to open the wp-config.php file from your WORDPRESS root folder.(wordpress/wp-config.php).</p>\n\n<p>2) Paste the below code to your wp-config.php just <strong>below every other line of code.</strong></p>\n\n<pre><code>define('FS_METHOD','direct');\n</code></pre>\n"
}
] |
2016/06/28
|
[
"https://wordpress.stackexchange.com/questions/230888",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97486/"
] |
I've ran into this issue where WordPress requests my FTP login credentials.
So far I've tried:
* chown
* change user
* change file permissions
* edited wp-config.php
None of it seems to work. The server I'm hosting it on is a VPS. I don't have much info from it. I am able to connect to my FTP using FileZilla but WordPress doesn't seem to be able to connect to it. Is there additional info I should request from my web host to properly set this up?
EDIT:
I haven't looked into httpd.conf yet. The owner of the public\_html directory is root. I changed the permissions and owner to root. Is that the wrong practice?
I spoke to my server guy this morning, the server is listening to port 22 but on the hardware firewall, the public IP is nat from port 2232 to the server's port 22. But the server doesn't allow wordpress webui to enter 2232 (the port i'm using for SSH).
This is the additional bit I added to wp-config.php:
```
define( 'FTP_USER', 'root' );
define( 'FTP_PASS', 'ftp-password' );
define( 'FTP_HOST', '123.123.123.123:2232' );
```
|
Guess it needs to be said first - it is a bad idea in general to just let anyone that succeeded to trick you into uploading his PHP onto your server to actually be able to write to your code directories. It is double problematic if you let him access to your root credentials and write to anywhere on your server.
That said, it sounds like you just don't have an FTP server installed on your server. SFTP is different from FTP and being able to access via one do not ensure access with the other.
You should login to your server, run an FTP command with the credentials you put in the `wp-config` to first make sure you can connect and access the relevant directories. Once you can properly connect woth the FTP command on your server you can use the same credentials in your config.
|
230,902 |
<p>My html looks like this (simplified)</p>
<pre><code>$args = array(...);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
foreach ($comments as $comment) {
<a class="respond-to-messages" href="#<?php echo $comment->comment_ID; ?>">Reply to message</a>
<div id="comment-<?php echo $comment->comment_ID; ?>" class="comment-respond-form post-id-<?php echo $comment->comment_post_ID; ?>">
<table>
<tr>
<form id="custom_comments-form" action="" method="post">
//form fields
<button class="uk-button" type="submit">Send</button>
</form>
</tr>
</table>
</div>
}
</code></pre>
<p><a href="https://i.stack.imgur.com/Azw59.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Azw59.png" alt="enter image description here" /></a></p>
<p>My jquery</p>
<pre><code>jQuery(function ($) {
$(document).ready(function(){
$(".comment-respond-form").hide();
$(".respond-to-messages").show();
$('.respond-to-messages').on('click',function(){
$(this).text($(this).text() == 'Reply to message' ? 'Hide form' : 'Reply to message');
$(".comment-respond-form").slideToggle(function(){
if($('.comment-respond-form').height() > 0) {
$('html, body').animate({
scrollTop: $("comment-respond-form").offset().top
}, 1000);
}
});
});
});
});
</code></pre>
<p>Because we're in a loop with multiple comments, <code>.comment-respond-form</code> should actually be <code>comment-<?php echo $comment->comment_ID; ?></code>
But the jquery script is added outside the loop (in the footer and inside a .js file).</p>
<p>Any help is much appreciated.</p>
<p>EDIT: (we're almost there)</p>
<p>I created an extra button to expand/collapse all forms</p>
<pre><code><button class="collapse-forms" href="#">Collapse All</button>
$('.collapse-forms').on('click',function(){
$(this).text($(this).text() == 'Collapse All' ? 'Expand All' : 'Collapse All');
$(".comment-respond-form").slideToggle(function(){
});
});
</code></pre>
<p>But what I noticed is the following</p>
<p><a href="https://i.stack.imgur.com/YkCZ1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YkCZ1.png" alt="enter image description here" /></a></p>
<p>How to modify my code so that all forms will open/close regardless whether they were closed or open before?</p>
|
[
{
"answer_id": 230968,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": true,
"text": "<p>Guess it needs to be said first - it is a bad idea in general to just let anyone that succeeded to trick you into uploading his PHP onto your server to actually be able to write to your code directories. It is double problematic if you let him access to your root credentials and write to anywhere on your server.</p>\n\n<p>That said, it sounds like you just don't have an FTP server installed on your server. SFTP is different from FTP and being able to access via one do not ensure access with the other.</p>\n\n<p>You should login to your server, run an FTP command with the credentials you put in the <code>wp-config</code> to first make sure you can connect and access the relevant directories. Once you can properly connect woth the FTP command on your server you can use the same credentials in your config.</p>\n"
},
{
"answer_id": 230979,
"author": "chiragpatel",
"author_id": 97397,
"author_profile": "https://wordpress.stackexchange.com/users/97397",
"pm_score": -1,
"selected": false,
"text": "<p>1) The first thing you have to do is to open the wp-config.php file from your WORDPRESS root folder.(wordpress/wp-config.php).</p>\n\n<p>2) Paste the below code to your wp-config.php just <strong>below every other line of code.</strong></p>\n\n<pre><code>define('FS_METHOD','direct');\n</code></pre>\n"
}
] |
2016/06/28
|
[
"https://wordpress.stackexchange.com/questions/230902",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68619/"
] |
My html looks like this (simplified)
```
$args = array(...);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
foreach ($comments as $comment) {
<a class="respond-to-messages" href="#<?php echo $comment->comment_ID; ?>">Reply to message</a>
<div id="comment-<?php echo $comment->comment_ID; ?>" class="comment-respond-form post-id-<?php echo $comment->comment_post_ID; ?>">
<table>
<tr>
<form id="custom_comments-form" action="" method="post">
//form fields
<button class="uk-button" type="submit">Send</button>
</form>
</tr>
</table>
</div>
}
```
[](https://i.stack.imgur.com/Azw59.png)
My jquery
```
jQuery(function ($) {
$(document).ready(function(){
$(".comment-respond-form").hide();
$(".respond-to-messages").show();
$('.respond-to-messages').on('click',function(){
$(this).text($(this).text() == 'Reply to message' ? 'Hide form' : 'Reply to message');
$(".comment-respond-form").slideToggle(function(){
if($('.comment-respond-form').height() > 0) {
$('html, body').animate({
scrollTop: $("comment-respond-form").offset().top
}, 1000);
}
});
});
});
});
```
Because we're in a loop with multiple comments, `.comment-respond-form` should actually be `comment-<?php echo $comment->comment_ID; ?>`
But the jquery script is added outside the loop (in the footer and inside a .js file).
Any help is much appreciated.
EDIT: (we're almost there)
I created an extra button to expand/collapse all forms
```
<button class="collapse-forms" href="#">Collapse All</button>
$('.collapse-forms').on('click',function(){
$(this).text($(this).text() == 'Collapse All' ? 'Expand All' : 'Collapse All');
$(".comment-respond-form").slideToggle(function(){
});
});
```
But what I noticed is the following
[](https://i.stack.imgur.com/YkCZ1.png)
How to modify my code so that all forms will open/close regardless whether they were closed or open before?
|
Guess it needs to be said first - it is a bad idea in general to just let anyone that succeeded to trick you into uploading his PHP onto your server to actually be able to write to your code directories. It is double problematic if you let him access to your root credentials and write to anywhere on your server.
That said, it sounds like you just don't have an FTP server installed on your server. SFTP is different from FTP and being able to access via one do not ensure access with the other.
You should login to your server, run an FTP command with the credentials you put in the `wp-config` to first make sure you can connect and access the relevant directories. Once you can properly connect woth the FTP command on your server you can use the same credentials in your config.
|
230,940 |
<p>Contributors <a href="https://codex.wordpress.org/Roles_and_Capabilities#Contributor" rel="nofollow noreferrer">can create post drafts</a> but not publish. I'd like to add the same permission concept but to Pages. That is, can I allow a Contributor to create a page draft only to have an Editor/Admin to later approve or reject?</p>
<p>From this <a href="https://wordpress.stackexchange.com/questions/133902/">question</a>, I see that I can hook into the action <code>new_role_edit_posts</code>. Is there an equivalent <code>new_role_edit_pages</code>? </p>
<p>How would you go about this?</p>
|
[
{
"answer_id": 230942,
"author": "Rick",
"author_id": 33401,
"author_profile": "https://wordpress.stackexchange.com/users/33401",
"pm_score": -1,
"selected": false,
"text": "<p>A plugin to the rescue. It looks like <a href=\"https://wordpress.org/plugins/wpfront-user-role-editor/\" rel=\"nofollow noreferrer\">WPFront User Role Editor</a> is what I was looking for. It produces a very granulated menu of what each role can do. This looks promising. </p>\n\n<p><a href=\"https://i.stack.imgur.com/LDX1M.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LDX1M.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 263854,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>How would you go about this?</p>\n</blockquote>\n\n<p>I see this is an old question and that you found a solution with an existing plugin. However, since this is a development StackExchange, it's probably better if there's an answer that explains how to accomplish the stated goals without the need for a third-party plugin.</p>\n\n<h3>Written Answer</h3>\n\n<p>WordPress stores capabilities in the database. Therefore, what we want is a plugin that will add the <code>edit_pages</code> capability to the contributor role upon plugin activation. For completeness, the plugin should remove the capability upon deactivation.</p>\n\n<h3>Coded Answer</h3>\n\n<pre><code>/**\n * Plugin Name: WPSE 230940\n */\n\n//* Add activation hook\nregister_activation_hook( __FILE__ , 'wpse_230940_activation' ); \nfunction wpse_230940_activation() {\n //* Add edit_pages capability to contributors\n $contributor = get_role( 'contributor' );\n $contributor->add_cap( 'edit_pages' );\n}\n\n//* Add deactivation hook\nregister_deactivation_hook( __FILE__ , 'wpse_230940_deactivation' );\nfunction wpse_230940_deactivation() {\n //* Remove edit_pages capability from contributors\n $contributor = get_role( 'contributor' );\n $contributor->remove_cap( 'edit_pages' );\n}\n</code></pre>\n"
},
{
"answer_id": 400709,
"author": "Svetoslav Marinov",
"author_id": 26487,
"author_profile": "https://wordpress.stackexchange.com/users/26487",
"pm_score": 0,
"selected": false,
"text": "<p>You can do the same thing using wp-cli.</p>\n<pre><code>wp cap add 'contributor' 'edit_pages'\n</code></pre>\n"
}
] |
2016/06/28
|
[
"https://wordpress.stackexchange.com/questions/230940",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33401/"
] |
Contributors [can create post drafts](https://codex.wordpress.org/Roles_and_Capabilities#Contributor) but not publish. I'd like to add the same permission concept but to Pages. That is, can I allow a Contributor to create a page draft only to have an Editor/Admin to later approve or reject?
From this [question](https://wordpress.stackexchange.com/questions/133902/), I see that I can hook into the action `new_role_edit_posts`. Is there an equivalent `new_role_edit_pages`?
How would you go about this?
|
>
> How would you go about this?
>
>
>
I see this is an old question and that you found a solution with an existing plugin. However, since this is a development StackExchange, it's probably better if there's an answer that explains how to accomplish the stated goals without the need for a third-party plugin.
### Written Answer
WordPress stores capabilities in the database. Therefore, what we want is a plugin that will add the `edit_pages` capability to the contributor role upon plugin activation. For completeness, the plugin should remove the capability upon deactivation.
### Coded Answer
```
/**
* Plugin Name: WPSE 230940
*/
//* Add activation hook
register_activation_hook( __FILE__ , 'wpse_230940_activation' );
function wpse_230940_activation() {
//* Add edit_pages capability to contributors
$contributor = get_role( 'contributor' );
$contributor->add_cap( 'edit_pages' );
}
//* Add deactivation hook
register_deactivation_hook( __FILE__ , 'wpse_230940_deactivation' );
function wpse_230940_deactivation() {
//* Remove edit_pages capability from contributors
$contributor = get_role( 'contributor' );
$contributor->remove_cap( 'edit_pages' );
}
```
|
230,950 |
<p>I'm migrating a site from my server to a client's Bluehost (ugh) account. I've tried using</p>
<ul>
<li>All In One WP Migrate</li>
<li>BackupBuddy</li>
<li>manual migration (copying files & exporting a db using WP Migrate DB)</li>
</ul>
<p>These are the stats on my server:</p>
<pre><code>Apache Version 2.2.24
PHP Version 5.3.26
MySQL Version 5.6.28-76.1
</code></pre>
<p>And the client's server:</p>
<pre><code>Apache 2.2.31
PHP 5.2.17
MySQL 5.5.42
</code></pre>
<p>I did set the php.ini on the client server to update to php 5.4. I presume (maybe incorrectly) that the difference in MySQL version shouldn't matter.</p>
<p>Every time I'm getting an HTTP 500 Error (though after the last attempt it's an Internal Server 500 on the home page & the HTTP 500 Error everywhere else). </p>
<p>I renamed the .htaccess - no dice. Removed the php.ini - no dice. The database prefix is different, and I set wp-config to use the extension from the dev site. </p>
<p>Usually these migrations are pretty easy so I'm stumped. What am I missing?</p>
|
[
{
"answer_id": 230952,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 3,
"selected": true,
"text": "<p>You need to turn <code>WP_DEBUG</code> on in your <code>wp-config.php</code>:</p>\n\n<pre><code>define( 'WP_DEBUG', true );\n</code></pre>\n\n<p>That'll help a lot with working out where that 500 error is coming from. Based on the PHP versions you've mentioned, I'm 99.999% sure that the error is due to a feature that isn't available in PHP 5.2.17. You're probably looking at either <a href=\"http://php.net/manual/en/language.types.array.php\" rel=\"nofollow\">shorthand array notation</a> (eg. <code>$array = [];</code> - although this was added in PHP 5.4.0 so probably isn't the problem in your case, given you're coming from 5.3.26), or one of <a href=\"http://php.net/manual/en/functions.anonymous.php\" rel=\"nofollow\">anonymous functions</a>, <a href=\"http://php.net/manual/en/language.namespaces.basics.php\" rel=\"nofollow\">Namespaces</a> or <a href=\"http://php.net/manual/en/function.array-replace.php\" rel=\"nofollow\">array_replace</a>, which were all added in PHP 5.3.0.</p>\n\n<p>Having WP_DEBUG on will point you to where that error is being caused. If you've written the code yourself you could replace it with an older alternative (eg. longer array notation, or a non-anonymous function), or if it's possible on the server you're on you could upgrade the PHP version.</p>\n\n<p>As an example, to replace an <strong>anonymous function</strong>, you'd want to change something like this:</p>\n\n<pre><code>add_filter( 'the_content', function($content){ return 'hello'; });\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>add_filter( 'the_content', 'my_content_function');\n\nfunction my_content_function($content){ return 'hello'; }\n</code></pre>\n\n<p>Other things worth trying include:</p>\n\n<ul>\n<li>Commenting out lines in your <code>.htaccess</code> (add <code>#</code> to the start of the line) that aren't between the <code># START WordPress</code> and <code># END WordPress</code> lines</li>\n<li><a href=\"https://codex.wordpress.org/Changing_File_Permissions#Permission_Scheme_for_WordPress\" rel=\"nofollow\">Resetting your file permissions</a></li>\n<li>The usual disabling all plugins - and changing themes - to see if the problem goes away (if you can't access the admin, you can just rename the individual plugin or theme folders to disable them)</li>\n</ul>\n"
},
{
"answer_id": 230976,
"author": "bagpipper",
"author_id": 80397,
"author_profile": "https://wordpress.stackexchange.com/users/80397",
"pm_score": -1,
"selected": false,
"text": "<p>Try using the plugin called Duplicator <a href=\"https://wordpress.org/plugins/duplicator/\" rel=\"nofollow\">https://wordpress.org/plugins/duplicator/</a></p>\n\n<p>I always it to migrate website. You should not face any problems with this one</p>\n\n<p>As for the errors you are facing there might be additional files that blue host might keep. Do check for any unwanted files or folders</p>\n"
},
{
"answer_id": 231038,
"author": "BredeBS",
"author_id": 97573,
"author_profile": "https://wordpress.stackexchange.com/users/97573",
"pm_score": 0,
"selected": false,
"text": "<p>The absolute best way to migrate is:</p>\n\n<ol>\n<li>get access to your mysql server</li>\n<li>make a dump of the database</li>\n<li>get access to your file server</li>\n<li>zip your /wp-content folder</li>\n<li>upload your zip and sql files to the new server</li>\n<li>uncompress the /wp-content file</li>\n<li>load the old dump into your new database server</li>\n<li>modify your wp-config.php and point to the new database server</li>\n</ol>\n\n<p><em>source: my own experience throught a large list of websites.</em></p>\n\n<p>PS and important: don't dump through a WP plugin!!</p>\n"
}
] |
2016/06/28
|
[
"https://wordpress.stackexchange.com/questions/230950",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45248/"
] |
I'm migrating a site from my server to a client's Bluehost (ugh) account. I've tried using
* All In One WP Migrate
* BackupBuddy
* manual migration (copying files & exporting a db using WP Migrate DB)
These are the stats on my server:
```
Apache Version 2.2.24
PHP Version 5.3.26
MySQL Version 5.6.28-76.1
```
And the client's server:
```
Apache 2.2.31
PHP 5.2.17
MySQL 5.5.42
```
I did set the php.ini on the client server to update to php 5.4. I presume (maybe incorrectly) that the difference in MySQL version shouldn't matter.
Every time I'm getting an HTTP 500 Error (though after the last attempt it's an Internal Server 500 on the home page & the HTTP 500 Error everywhere else).
I renamed the .htaccess - no dice. Removed the php.ini - no dice. The database prefix is different, and I set wp-config to use the extension from the dev site.
Usually these migrations are pretty easy so I'm stumped. What am I missing?
|
You need to turn `WP_DEBUG` on in your `wp-config.php`:
```
define( 'WP_DEBUG', true );
```
That'll help a lot with working out where that 500 error is coming from. Based on the PHP versions you've mentioned, I'm 99.999% sure that the error is due to a feature that isn't available in PHP 5.2.17. You're probably looking at either [shorthand array notation](http://php.net/manual/en/language.types.array.php) (eg. `$array = [];` - although this was added in PHP 5.4.0 so probably isn't the problem in your case, given you're coming from 5.3.26), or one of [anonymous functions](http://php.net/manual/en/functions.anonymous.php), [Namespaces](http://php.net/manual/en/language.namespaces.basics.php) or [array\_replace](http://php.net/manual/en/function.array-replace.php), which were all added in PHP 5.3.0.
Having WP\_DEBUG on will point you to where that error is being caused. If you've written the code yourself you could replace it with an older alternative (eg. longer array notation, or a non-anonymous function), or if it's possible on the server you're on you could upgrade the PHP version.
As an example, to replace an **anonymous function**, you'd want to change something like this:
```
add_filter( 'the_content', function($content){ return 'hello'; });
```
to this:
```
add_filter( 'the_content', 'my_content_function');
function my_content_function($content){ return 'hello'; }
```
Other things worth trying include:
* Commenting out lines in your `.htaccess` (add `#` to the start of the line) that aren't between the `# START WordPress` and `# END WordPress` lines
* [Resetting your file permissions](https://codex.wordpress.org/Changing_File_Permissions#Permission_Scheme_for_WordPress)
* The usual disabling all plugins - and changing themes - to see if the problem goes away (if you can't access the admin, you can just rename the individual plugin or theme folders to disable them)
|
230,956 |
<p><strong>WordPress setup:</strong> Installed WordPress using <a href="https://github.com/Varying-Vagrant-Vagrants/VVV" rel="nofollow">VVV</a>.</p>
<p><strong>PHPUnit setup:</strong>
I have setup the testing suite as mentioned in <a href="https://pippinsplugins.com/unit-tests-wordpress-plugins-setting-up-testing-suite/" rel="nofollow">Pippin's blog</a>. And accessing PHPUnit after logging into the box machine by using <code>vagrant ssh</code>.</p>
<p><strong>Test case:</strong> I'm writing my test cases inside the <code>/tests/</code> folder in the <code>test-{my-plugin-filename}.php</code> file.</p>
<pre><code>function test_my_plugin_method() {
$links = plugin_method();
}
</code></pre>
<p><strong>Where I'm stuck?</strong></p>
<p>When I run <code>PHPUnit</code>, I'm getting the following error.</p>
<p><code>Error: Call to undefined function plugin_method()</code></p>
<p>I have added the following line. </p>
<p><code>require_once( dirname( dirname( __FILE__ ) ) . '/plugin-file.php' );</code></p>
<p>But I believe I'm missing something. Any help would be much appreciated.</p>
<p><strong>Edit 1:</strong> </p>
<p>I executed <code>wp scaffold plugin-tests</code> and then the following line as mentioned in Pippin's blog (refer above for link).</p>
<pre><code>bash bin/install-wp-tests.sh wordpress_test root '' localhost latest
</code></pre>
<p>Finally I executed <code>phpunit</code>.</p>
<p><strong>bootstrap.php</strong></p>
<p>I haven't changed anything in the bootstrap.php file.</p>
<pre><code><?php
$_tests_dir = getenv( 'WP_TESTS_DIR' );
if ( ! $_tests_dir ) {
$_tests_dir = '/tmp/wordpress-tests-lib';
}
require_once $_tests_dir . '/includes/functions.php';
function _manually_load_plugin() {
require dirname( dirname( __FILE__ ) ) . '/my-plugin.php';
}
tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' );
require $_tests_dir . '/includes/bootstrap.php';
</code></pre>
|
[
{
"answer_id": 230978,
"author": "Mohit Kumar Arora",
"author_id": 97527,
"author_profile": "https://wordpress.stackexchange.com/users/97527",
"pm_score": 1,
"selected": false,
"text": "<p>There are many differences in css files of both websites.\nFor example, have a look at the div having class <strong>et-top-navigation</strong> by inspecting it in browser.</p>\n\n<p>You will find that in staging website, there is top padding and left padding applied while it is not in case of live website.</p>\n\n<p>Similarly check for other css changes in staging website or simply take backup of all css files in staging website and place those files from live website.</p>\n\n<p>I hope this will resolve your problem.</p>\n"
},
{
"answer_id": 281963,
"author": "J Garcia",
"author_id": 111642,
"author_profile": "https://wordpress.stackexchange.com/users/111642",
"pm_score": 0,
"selected": false,
"text": "<p>I can't look at the sites now that the links are removed and don't know how you've gone about moving things to the child theme but if you think that it's a problem with the order in which stylesheets are loaded, I would have a look at any <code>add_action()</code> calls that invoke <code>wp_enqueue_style()</code>. A sometimes used 3rd argument can be passed to <code>add_action()</code> that designates a priority for the callback, it's possible that some <code>add_action()</code> from the parent theme is coming after your child theme's <code>add_action()</code>.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\">WP add_action() docs</a></p>\n\n<p>Stylesheets that need to override others should be enqueued last.</p>\n"
},
{
"answer_id": 316766,
"author": "Elena",
"author_id": 152385,
"author_profile": "https://wordpress.stackexchange.com/users/152385",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know if my experience could be helpful but in my case the custom template has its own setting page in Wordpress Theme admin area (not the wordpress built in theme setting page, I'm referring to the setting page of that template).</p>\n\n<p>My staging version is \"css different\" until I import (or manually insert) the settings of that template. I can't understand why DB and FTP cloning (with obviously full domain replacements) aren't enough ;) But I can manually fix the missing settings this way.</p>\n"
},
{
"answer_id": 384923,
"author": "OctaviaLo",
"author_id": 153787,
"author_profile": "https://wordpress.stackexchange.com/users/153787",
"pm_score": 0,
"selected": false,
"text": "<p>Five years after the OP posted his problem I find I am having the same issue, also with Elegant Theme (am guessing OP was using ET due to the class name). The comment by Mariano really helped. I was also using a child theme. Switch the theme to some other theme, bust the cache and switch it back... and viola, it works.</p>\n"
}
] |
2016/06/29
|
[
"https://wordpress.stackexchange.com/questions/230956",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83739/"
] |
**WordPress setup:** Installed WordPress using [VVV](https://github.com/Varying-Vagrant-Vagrants/VVV).
**PHPUnit setup:**
I have setup the testing suite as mentioned in [Pippin's blog](https://pippinsplugins.com/unit-tests-wordpress-plugins-setting-up-testing-suite/). And accessing PHPUnit after logging into the box machine by using `vagrant ssh`.
**Test case:** I'm writing my test cases inside the `/tests/` folder in the `test-{my-plugin-filename}.php` file.
```
function test_my_plugin_method() {
$links = plugin_method();
}
```
**Where I'm stuck?**
When I run `PHPUnit`, I'm getting the following error.
`Error: Call to undefined function plugin_method()`
I have added the following line.
`require_once( dirname( dirname( __FILE__ ) ) . '/plugin-file.php' );`
But I believe I'm missing something. Any help would be much appreciated.
**Edit 1:**
I executed `wp scaffold plugin-tests` and then the following line as mentioned in Pippin's blog (refer above for link).
```
bash bin/install-wp-tests.sh wordpress_test root '' localhost latest
```
Finally I executed `phpunit`.
**bootstrap.php**
I haven't changed anything in the bootstrap.php file.
```
<?php
$_tests_dir = getenv( 'WP_TESTS_DIR' );
if ( ! $_tests_dir ) {
$_tests_dir = '/tmp/wordpress-tests-lib';
}
require_once $_tests_dir . '/includes/functions.php';
function _manually_load_plugin() {
require dirname( dirname( __FILE__ ) ) . '/my-plugin.php';
}
tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' );
require $_tests_dir . '/includes/bootstrap.php';
```
|
There are many differences in css files of both websites.
For example, have a look at the div having class **et-top-navigation** by inspecting it in browser.
You will find that in staging website, there is top padding and left padding applied while it is not in case of live website.
Similarly check for other css changes in staging website or simply take backup of all css files in staging website and place those files from live website.
I hope this will resolve your problem.
|
230,960 |
<p>Working on my first theme and thinking about adding some options that are specifically numbers like number of menu levels or number of posts to display on the homepage. Is it possible to check that the input in the customizer is just a number? And perhaps a certain limit like 5 for menu levels and 20 or something for posts on the homepage? Here is the code I'm working on with the customizer api as an example:</p>
<pre><code>$wp_customize->add_setting( 'posts_number_home' , array(
'default' => '10',
'transport' => 'refresh',
'sanitize_callback' => 'sanitize_text_field',
) );
$wp_customize->add_control( new WP_Customize_Control(
$wp_customize,
'posts_number_home',
array(
'section' => 'mytheme_options',
'settings' => 'posts_number_home',
'type' => 'text',
'priority' => 10,
)
));
</code></pre>
|
[
{
"answer_id": 230962,
"author": "jetyet47",
"author_id": 91783,
"author_profile": "https://wordpress.stackexchange.com/users/91783",
"pm_score": 1,
"selected": false,
"text": "<p>Think I figured it out. Type number definitely works not allowing text input. And it includes little arrow counters for the user. And you can add min max attributes. Someone let me know if this is incorrect in any way, particularly the sanitization.</p>\n\n<pre><code>$wp_customize->add_setting( 'posts_number_home' , array(\n'default' => '10',\n'transport' => 'refresh',\n'sanitize_callback' => 'sanitize_text_field',\n) );\n\n$wp_customize->add_control( new WP_Customize_Control( \n$wp_customize, \n'posts_number_home',\narray(\n 'label' => __( 'Number of posts to display on homepage', 'mytheme' ), \n 'section' => 'mytheme_options',\n 'settings' => 'posts_number_home',\n 'type' => 'number',\n 'priority' => 10,\n 'input_attrs' => array(\n 'min' => 1,\n 'max' => 10,)\n) \n));\n</code></pre>\n"
},
{
"answer_id": 231127,
"author": "Dmitry Mayorov",
"author_id": 49499,
"author_profile": "https://wordpress.stackexchange.com/users/49499",
"pm_score": 2,
"selected": false,
"text": "<p>You are right. A couple of fixes/suggestions, though.</p>\n\n<ul>\n<li>You should use <a href=\"https://codex.wordpress.org/Function_Reference/absint\" rel=\"nofollow\"><code>absint</code></a> as a sanitization callback.</li>\n<li>Also, you don't have to explicitly use the WP_Customize_Control class. The number field can be created with the regular syntax you use for the text field with an exception of the type and additional attributes.</li>\n<li>Another thing is that you don't have to define the refresh transport method since it is used by default.</li>\n</ul>\n\n<p>So the refined snippet should look something like this:</p>\n\n<pre><code>$wp_customize->add_setting( 'posts_number_home' , array(\n 'default' => 10,\n 'sanitize_callback' => 'absint',\n) );\n\n$wp_customize->add_control( 'posts_number_home', array(\n 'label' => __( 'Number of posts to display on homepage', 'mytheme' ), \n 'section' => 'mytheme_options',\n 'settings' => 'posts_number_home',\n 'type' => 'number',\n 'priority' => 10,\n 'input_attrs' => array(\n 'min' => 1,\n 'max' => 10\n )\n) );\n</code></pre>\n\n<p>Edit 07/01/2016: Using <code>intval</code> is not correct because Customizer secretly passes the second object parameter to sanitization callback, while <code>intval</code> expects an optional integer. So the best way to sanitize non-negative integer is <code>absint</code>.</p>\n"
}
] |
2016/06/29
|
[
"https://wordpress.stackexchange.com/questions/230960",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91783/"
] |
Working on my first theme and thinking about adding some options that are specifically numbers like number of menu levels or number of posts to display on the homepage. Is it possible to check that the input in the customizer is just a number? And perhaps a certain limit like 5 for menu levels and 20 or something for posts on the homepage? Here is the code I'm working on with the customizer api as an example:
```
$wp_customize->add_setting( 'posts_number_home' , array(
'default' => '10',
'transport' => 'refresh',
'sanitize_callback' => 'sanitize_text_field',
) );
$wp_customize->add_control( new WP_Customize_Control(
$wp_customize,
'posts_number_home',
array(
'section' => 'mytheme_options',
'settings' => 'posts_number_home',
'type' => 'text',
'priority' => 10,
)
));
```
|
You are right. A couple of fixes/suggestions, though.
* You should use [`absint`](https://codex.wordpress.org/Function_Reference/absint) as a sanitization callback.
* Also, you don't have to explicitly use the WP\_Customize\_Control class. The number field can be created with the regular syntax you use for the text field with an exception of the type and additional attributes.
* Another thing is that you don't have to define the refresh transport method since it is used by default.
So the refined snippet should look something like this:
```
$wp_customize->add_setting( 'posts_number_home' , array(
'default' => 10,
'sanitize_callback' => 'absint',
) );
$wp_customize->add_control( 'posts_number_home', array(
'label' => __( 'Number of posts to display on homepage', 'mytheme' ),
'section' => 'mytheme_options',
'settings' => 'posts_number_home',
'type' => 'number',
'priority' => 10,
'input_attrs' => array(
'min' => 1,
'max' => 10
)
) );
```
Edit 07/01/2016: Using `intval` is not correct because Customizer secretly passes the second object parameter to sanitization callback, while `intval` expects an optional integer. So the best way to sanitize non-negative integer is `absint`.
|
230,991 |
<p>I'm applying a filter to a custom fields plugin.</p>
<pre><code>add_filter('acf/load_value', word_swap);
</code></pre>
<p>My problem is this applies it to pages within the wp-admin also. I only want the filter applied to the actual WP site, and not the admin panel.</p>
<p>How can I prevent the filter being applied to the wp-admin pages?</p>
<p>I imagine I'd do something like</p>
<pre><code>if(page == 'wp-admin')
add_filter('acf/load_value', word_swap);
</code></pre>
|
[
{
"answer_id": 230993,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>You need the <code>!is_admin()</code> check. This will return false on admin pages, failing your condition. On front end pages, that condition will return true, executing your conditional statement</p>\n\n<pre><code>if ( !is_admin() ) {\n // Do something only on frontend\n}\n</code></pre>\n"
},
{
"answer_id": 230994,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 0,
"selected": false,
"text": "<p>The function <code>is_admin()</code> is available before any plugin is loaded. So you can use it when you are registering the callback:</p>\n\n<pre><code>is_admin() or add_filter('acf/load_value', 'word_swap' );\n</code></pre>\n"
}
] |
2016/06/29
|
[
"https://wordpress.stackexchange.com/questions/230991",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29510/"
] |
I'm applying a filter to a custom fields plugin.
```
add_filter('acf/load_value', word_swap);
```
My problem is this applies it to pages within the wp-admin also. I only want the filter applied to the actual WP site, and not the admin panel.
How can I prevent the filter being applied to the wp-admin pages?
I imagine I'd do something like
```
if(page == 'wp-admin')
add_filter('acf/load_value', word_swap);
```
|
You need the `!is_admin()` check. This will return false on admin pages, failing your condition. On front end pages, that condition will return true, executing your conditional statement
```
if ( !is_admin() ) {
// Do something only on frontend
}
```
|
231,003 |
<p>How do I get a list of all users with role = 'Customers' including all the metadata per user, means wp_users + wp_usermeta.</p>
<p>Query blow does not generate the wanted results.</p>
<pre><code>$query = "SELECT * FROM wp_users INNER JOIN wp_usermeta ON wp_users.ID = wp_usermeta.user_id ORDER BY ID DESC'); ";
$data = $wpdb->get_results($query,ARRAY_A);
</code></pre>
<p>But that list is not correct. It shows each user x times depending on the number of rows in wp_usermeta.</p>
<p>How can I filter it? That each user shows per record all his user + metadata?</p>
|
[
{
"answer_id": 231057,
"author": "Syed Fakhar Abbas",
"author_id": 90591,
"author_profile": "https://wordpress.stackexchange.com/users/90591",
"pm_score": 6,
"selected": true,
"text": "<p>I think you should use wp-api functions which will do everything for you.</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/get_users/\" rel=\"noreferrer\">get_users()</a> function will get all users data just define fields which u require.</li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/get_user_meta/\" rel=\"noreferrer\">get_user_meta(</a>) function will get usermeta data.</li>\n</ul>\n\n<pre> <code>\n$users = get_users( array( 'fields' => array( 'ID' ) ) );\nforeach($users as $user){\n print_r(get_user_meta ( $user->ID));\n }\n</code></pre>\n"
},
{
"answer_id": 351711,
"author": "Debbie Kurth",
"author_id": 119560,
"author_profile": "https://wordpress.stackexchange.com/users/119560",
"pm_score": 2,
"selected": false,
"text": "<p>A bit more formal way to achieve the same results are as follows\nSubstitute any role as necessary and this code assumes you are using WooCommerce for more detailed information.</p>\n<pre><code>function GetSubscriberUserData()\n{\n $DBRecord = array();\n $args = array(\n 'role' => 'Subscriber',\n 'orderby' => 'last_name',\n 'order' => 'ASC'\n );\n $users = get_users( $args );\n $i=0;\n foreach ( $users as $user )\n {\n $DBRecord[$i]['role'] = "Subscriber";\n $DBRecord[$i]['WPId'] = $user->ID;\n $DBRecord[$i]['FirstName'] = $user->first_name;\n $DBRecord[$i]['LastName'] = $user->last_name;\n $DBRecord[$i]['RegisteredDate'] = $user->user_registered;\n $DBRecord[$i]['Email'] = $user->user_email;\n\n $UserData = get_user_meta( $user->ID );\n $DBRecord[$i]['Company'] = $UserData['billing_company'][0];\n $DBRecord[$i]['Address'] = $UserData['billing_address_1'][0];\n $DBRecord[$i]['City'] = $UserData['billing_city'][0];\n $DBRecord[$i]['State'] = $UserData['billing_state'][0];\n $DBRecord[$i]['PostCode'] = $UserData['billing_postcode'][0];\n $DBRecord[$i]['Country'] = $UserData['billing_country'][0];\n $DBRecord[$i]['Phone'] = $UserData['billing_phone'][0];\n $i++;\n }\n return $DBRecord;\n}\n</code></pre>\n"
},
{
"answer_id": 369686,
"author": "Tim Burch",
"author_id": 111215,
"author_profile": "https://wordpress.stackexchange.com/users/111215",
"pm_score": 0,
"selected": false,
"text": "<p>I created a simple, free plugin, called <a href=\"https://github.com/linchpinsoftware/wordpress_flat_metadata\" rel=\"nofollow noreferrer\">Flat Meta Data</a>, that flattens post and user meta data into a CSV that can more easily be used for reporting and analysis. In the process it creates tables in your database (<code>[:prefix]postmeta_flat</code> and <code>[:prefix]usermeta_flat</code>) that contain the same information and can be used in more complex queries. These tables have one row per post or user and one column per data point (meta_key) containing the meta values (meta_value).</p>\n<p>After installing and activating the plugin (in wp-content/plugins/flat-table), it is accessible through a link in the main menu of the admin panel, called Flat Meta Data. You can then click on either the "Download post meta data" or "Download user meta data" button to generate the table and download the CSV containing all of the data in spreadsheet form.</p>\n<p>A few notes:</p>\n<ol>\n<li>This plugin is provided free of charge. Use at your own risk.</li>\n<li>CREATE TABLE privileges are required. This shouldn't be an issue, but could be if you've restricted access to the WordPress database user.</li>\n<li>Generating and downloading a complete set of meta data can negatively impact system performance. Please do so only during off-hours or, better yet, on a sandbox populated with your live data.</li>\n</ol>\n<p>Please let me know if you have any questions. Thanks.</p>\n"
},
{
"answer_id": 398864,
"author": "user8604345",
"author_id": 215538,
"author_profile": "https://wordpress.stackexchange.com/users/215538",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$members = get_users(\n array('role' => 'company',\n 'orderby' => 'ID',\n 'order' => 'ASC'\n )\n);\narray_map( function($member ){\n $member->usermeta = array_map(function($data){\n return reset($data);\n }, get_user_meta( $member->ID ) );\n return $member;\n}, $members); \n</code></pre>\n<p>This will return data as follows</p>\n<pre><code>Array\n(\n [0] => WP_User Object\n (\n [data] => stdClass Object\n (\n [ID] => 20\n [user_login] => aastha\n [user_pass] => $P$BVmRgRiZyZWhMvGszAkquPKX0JjedF1\n [user_nicename] => aastha\n [user_email] => [email protected]\n [user_url] => \n [user_registered] => 2021-11-29 10:43:21\n [user_activation_key] => \n [user_status] => 0\n [display_name] => aastha\n [usermeta] => Array\n (\n [nickname] => aastha\n [first_name] => \n [last_name] => \n [description] => \n [rich_editing] => true\n [syntax_highlighting] => true\n [comment_shortcuts] => false\n [admin_color] => fresh\n [use_ssl] => 0\n [show_admin_bar_front] => true\n [locale] => \n [wm_capabilities] => a:1:{s:7:"company";b:1;}\n [wm_user_level] => 0\n [name] => btc\n [type] => 7\n [status] => active\n [company_age] => 10\n [company_member] => 30\n [address] => indoor\n [city] => indoor\n [pin] => 5454\n [telephone] => 5434\n [opening_time] => 09:00\n [closing_time] => 20:00\n [fax] => gfgf\n [skull_from] => wednesday\n [skull_to] => sunday\n [mobile] => 3987665213\n [overview] => ghgh\n [username] => aastha\n [email] => [email protected]\n [wesite] => http://www.aastha.com\n [skull_logo] => \n )\n\n )\n\n [ID] => 20\n [caps] => Array\n (\n [company] => 1\n )\n\n [cap_key] => wm_capabilities\n [roles] => Array\n (\n [0] => company\n )\n\n [allcaps] => Array\n (\n [read] => 1\n [level_0] => 1\n [company] => 1\n )\n\n [filter] => \n [site_id:WP_User:private] => 1\n )\n);\n</code></pre>\n"
}
] |
2016/06/29
|
[
"https://wordpress.stackexchange.com/questions/231003",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78746/"
] |
How do I get a list of all users with role = 'Customers' including all the metadata per user, means wp\_users + wp\_usermeta.
Query blow does not generate the wanted results.
```
$query = "SELECT * FROM wp_users INNER JOIN wp_usermeta ON wp_users.ID = wp_usermeta.user_id ORDER BY ID DESC'); ";
$data = $wpdb->get_results($query,ARRAY_A);
```
But that list is not correct. It shows each user x times depending on the number of rows in wp\_usermeta.
How can I filter it? That each user shows per record all his user + metadata?
|
I think you should use wp-api functions which will do everything for you.
* [get\_users()](https://developer.wordpress.org/reference/functions/get_users/) function will get all users data just define fields which u require.
* [get\_user\_meta(](https://developer.wordpress.org/reference/functions/get_user_meta/)) function will get usermeta data.
```
$users = get_users( array( 'fields' => array( 'ID' ) ) );
foreach($users as $user){
print_r(get_user_meta ( $user->ID));
}
```
|
231,008 |
<p>In the <code>footer.php</code> I show all the authors of my blog with the following code: </p>
<pre><code>$args = array(
'meta_key' => 'last_name',
'orderby' => 'meta_value',
'order' => 'ASC'
);
// Create the WP_User_Query object
$wp_user_query = new WP_User_Query( $args );
$wp_user_query->query_orderby = str_replace( 'user_login',
'wp_usermeta.meta_value', $wp_user_query->query_orderby );
// Get the results
$authors = $wp_user_query->get_results();
</code></pre>
<p>Is it possible to limit the output to 5 random users? Like <code>posts_per_page => 3</code> and <code>orderby => rand</code>?</p>
|
[
{
"answer_id": 231011,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 2,
"selected": false,
"text": "<p>Yes possible, just tell WordPress to use <code>RAND()</code> SQL sorting when passing <code>rand</code> in <a href=\"https://codex.wordpress.org/Class_Reference/WP_User_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow\"><code>orderby</code></a> parameter:</p>\n\n<pre><code>add_action( \"pre_user_query\", function( $query ) {\n if( \"rand\" == $query->query_vars[\"orderby\"] ) {\n $query->query_orderby = str_replace( \"user_login\", \"RAND()\", $query->query_orderby );\n }\n});\n</code></pre>\n\n<p>Now you can use:</p>\n\n<pre><code>$users = get_users( array(\n 'meta_key' => 'last_name',\n 'orderby' => 'rand',\n 'number' => 3 // limit\n));\n\nprint_r( $users );\n</code></pre>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 231042,
"author": "Nicholas Koskowski",
"author_id": 92318,
"author_profile": "https://wordpress.stackexchange.com/users/92318",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function get_random_authors($number) {\n\n$users = wp_list_authors( array(\n'orderby' => 'rand',\n'number' => $number // limit\n));\n\nreturn $users;\n\n}\n\nprint_r(get_random_authors(3));\n</code></pre>\n"
}
] |
2016/06/29
|
[
"https://wordpress.stackexchange.com/questions/231008",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81609/"
] |
In the `footer.php` I show all the authors of my blog with the following code:
```
$args = array(
'meta_key' => 'last_name',
'orderby' => 'meta_value',
'order' => 'ASC'
);
// Create the WP_User_Query object
$wp_user_query = new WP_User_Query( $args );
$wp_user_query->query_orderby = str_replace( 'user_login',
'wp_usermeta.meta_value', $wp_user_query->query_orderby );
// Get the results
$authors = $wp_user_query->get_results();
```
Is it possible to limit the output to 5 random users? Like `posts_per_page => 3` and `orderby => rand`?
|
Yes possible, just tell WordPress to use `RAND()` SQL sorting when passing `rand` in [`orderby`](https://codex.wordpress.org/Class_Reference/WP_User_Query#Order_.26_Orderby_Parameters) parameter:
```
add_action( "pre_user_query", function( $query ) {
if( "rand" == $query->query_vars["orderby"] ) {
$query->query_orderby = str_replace( "user_login", "RAND()", $query->query_orderby );
}
});
```
Now you can use:
```
$users = get_users( array(
'meta_key' => 'last_name',
'orderby' => 'rand',
'number' => 3 // limit
));
print_r( $users );
```
Hope that helps.
|
231,010 |
<p>I'm trying to remove or hide the update nags for non-admin users. As an admin, I see:</p>
<p><a href="https://i.stack.imgur.com/29Kmx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/29Kmx.png" alt="enter image description here"></a></p>
<p>The popular answer I've seen to handle this says to use:</p>
<pre><code>function hide_update_nag() {
if ( !current_user_can('update_core') ) {
remove_action( 'admin_notices', 'update_nag', 3 );
}
}
add_action( 'admin_head', 'hide_update_nag', 1 );
</code></pre>
<p>This works fine for removing the first message (WordPress 4.5.3 is available! Please update now) but leaves the second one visible to non-admins:</p>
<p><a href="https://i.stack.imgur.com/VTc7g.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VTc7g.png" alt="enter image description here"></a></p>
<p>Both messages are wrapped in a <code><div class="update-nag"></code>, so <a href="https://wordpress.stackexchange.com/questions/76503/remove-time-to-upgrade-message-from-dashboard">one option</a> is to modify the above chunk of code to use CSS to hide the nag with:</p>
<pre><code>echo '<style>.update-nag {display: none}</style>';
</code></pre>
<p>But this feels kludgy to me. Is there a way to hook into an action or filter and remove ALL the update nag messages for non-admin users? No third-party plugin recommendations please.</p>
|
[
{
"answer_id": 231012,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 5,
"selected": true,
"text": "<p>In <code>wp-admin/includes/update.php</code> file</p>\n\n<pre><code>if ( current_user_can('update_core') )\n $msg = sprintf( __('An automated WordPress update has failed to complete - <a href=\"%s\">please attempt the update again now</a>.'), 'update-core.php' );\n else\n $msg = __('An automated WordPress update has failed to complete! Please notify the site administrator.');\n</code></pre>\n\n<p>We can see that messages are different based on the current user role and this is <code>maintenance_nag</code>.</p>\n\n<p>Basically we have two update nags and can be found in <code>admin-filters.php</code></p>\n\n<pre><code>add_action( 'admin_notices', 'update_nag', 3 );\nadd_action( 'admin_notices', 'maintenance_nag', 10 );\n</code></pre>\n\n<p>So to remove second message we can use(also check for current user role if you want this only for non-admins)</p>\n\n<pre><code>remove_action( 'admin_notices', 'maintenance_nag', 10 );\n</code></pre>\n\n<p>For multi-site use</p>\n\n<pre><code>remove_action( 'network_admin_notices', 'maintenance_nag', 10 );\n</code></pre>\n"
},
{
"answer_id": 231013,
"author": "Stephen Harris",
"author_id": 9364,
"author_profile": "https://wordpress.stackexchange.com/users/9364",
"pm_score": 2,
"selected": false,
"text": "<p>@bravokeyl is the probably the best answer to your immediate problem.</p>\n\n<p>But to address the following:</p>\n\n<blockquote>\n <p>Is there a way to hook into an action or filter and remove ALL the\n update nag messages for non-admin users?</p>\n</blockquote>\n\n<p>No. Nag messages in WordPress are just a callback to added to the <code>admin_notices</code> hook which print some HTML to the page. They are practically the same as error or success messages, or any other 'notice' from WordPress or any other plug-in or theme for that matter.</p>\n\n<p>Hiding the nags via CSS <em>is</em> hacky. It's also liable to some false positives as some plugins/themes will, incorrectly, use the <code>.update-nag</code> class to provide the desired styling to their own notices.</p>\n\n<p>A much less hacky way is to explicitly remove each callback that you don't want printing notices (for non-admins). But this comes at a (probably very low cost) of maintaining that list and ensuring there are no notices that 'slip the net'.</p>\n"
},
{
"answer_id": 295536,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 3,
"selected": false,
"text": "<p>here is complete code, which seems to work at this moment:</p>\n\n<pre><code>add_action('admin_head', function() {\n if(!current_user_can('manage_options')){\n remove_action( 'admin_notices', 'update_nag', 3 );\n remove_action( 'admin_notices', 'maintenance_nag', 10 );\n }\n});\n</code></pre>\n"
}
] |
2016/06/29
|
[
"https://wordpress.stackexchange.com/questions/231010",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26666/"
] |
I'm trying to remove or hide the update nags for non-admin users. As an admin, I see:
[](https://i.stack.imgur.com/29Kmx.png)
The popular answer I've seen to handle this says to use:
```
function hide_update_nag() {
if ( !current_user_can('update_core') ) {
remove_action( 'admin_notices', 'update_nag', 3 );
}
}
add_action( 'admin_head', 'hide_update_nag', 1 );
```
This works fine for removing the first message (WordPress 4.5.3 is available! Please update now) but leaves the second one visible to non-admins:
[](https://i.stack.imgur.com/VTc7g.png)
Both messages are wrapped in a `<div class="update-nag">`, so [one option](https://wordpress.stackexchange.com/questions/76503/remove-time-to-upgrade-message-from-dashboard) is to modify the above chunk of code to use CSS to hide the nag with:
```
echo '<style>.update-nag {display: none}</style>';
```
But this feels kludgy to me. Is there a way to hook into an action or filter and remove ALL the update nag messages for non-admin users? No third-party plugin recommendations please.
|
In `wp-admin/includes/update.php` file
```
if ( current_user_can('update_core') )
$msg = sprintf( __('An automated WordPress update has failed to complete - <a href="%s">please attempt the update again now</a>.'), 'update-core.php' );
else
$msg = __('An automated WordPress update has failed to complete! Please notify the site administrator.');
```
We can see that messages are different based on the current user role and this is `maintenance_nag`.
Basically we have two update nags and can be found in `admin-filters.php`
```
add_action( 'admin_notices', 'update_nag', 3 );
add_action( 'admin_notices', 'maintenance_nag', 10 );
```
So to remove second message we can use(also check for current user role if you want this only for non-admins)
```
remove_action( 'admin_notices', 'maintenance_nag', 10 );
```
For multi-site use
```
remove_action( 'network_admin_notices', 'maintenance_nag', 10 );
```
|
231,040 |
<p>Default WordPress galleries img tags close like <code><img></code> which is invalid XHTML. The lazyload XT plugin that I'm using targets valid XHTML img tags which means ending should be:</p>
<pre><code><img src="http://www.acaciafotografia.com/wp-content/themes/jamdxstarter/img/tri.jpg"/>
</code></pre>
<p><em>instead of</em></p>
<pre><code><img src="http://www.acaciafotografia.com/wp-content/themes/jamdxstarter/img/tri.jpg">
</code></pre>
<p>How can I filter or modify this so lazyload works correctly?</p>
<p><a href="https://wordpress.org/support/topic/unable-to-lazy-load?replies=8#post-8586177" rel="nofollow">Issue explained by author of wp lazyload XT integration</a>.</p>
<p>The theme I'm using, UNDERSCORES, modifies the markup of WP galleries to make it HTML5 compliant. This doesn't work well with Lazyload XT , that fetches XHTML img tags that end with "/>" , while HTML5 img tags don't need this and close with ">"</p>
<p>In <code>functions.php</code> I commented out the following line:</p>
<pre><code> /*
* Switch default core markup for search form, comment form, and comments
* to output valid HTML5.
*/
add_theme_support( 'html5', array(
'search-form',
'comment-form',
'comment-list',
// 'gallery',
'caption',
) );
</code></pre>
|
[
{
"answer_id": 231045,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 1,
"selected": false,
"text": "<p>As <a href=\"https://stackoverflow.com/a/23410472/1982136\">linked to</a> from the comments on your question, the <a href=\"https://developer.wordpress.org/reference/hooks/post_gallery/\" rel=\"nofollow noreferrer\">post_gallery filter</a> should help you here.</p>\n\n<p>Unlike a lot of other hooks though, you can't filter the output that comes through from WordPress; you can only provide your own alternative output. This is slightly annoying, and results in you needing to build the gallery from scratch. You can do that with a bit of extra code, though, and the <a href=\"https://stackoverflow.com/a/23410472/1982136\">linked StackOverflow answer</a> provides an example (but strangely uses <code><div src></code>, so just change that to <code><img src></code> - and then draw from the default WordPress markup for the rest, making sure to close your <code><img /></code> tag).</p>\n\n<hr>\n\n<p>An alternative, where you <em>can</em> filter the output, is to use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content\" rel=\"nofollow noreferrer\"><code>the_content</code> filter</a> and some clever regex'ing. You need to be careful, because if you don't think of all potential cases, your regex could catch something you don't intend it to. This is exactly the problem the plugin author in this case is <a href=\"https://wordpress.org/support/topic/unable-to-lazy-load?replies=8\" rel=\"nofollow noreferrer\">trying to avoid</a>.</p>\n\n<p>With that said, here's a potential solution. Modify to your needs, but <strong>don't rely on this as a 100% foolproof solution</strong>.</p>\n\n<pre><code>// priority must be more than 10, so it runs after the gallery shortcode does\nadd_filter( 'the_content', 'wpse231040_close_gallery_img_tags', 11);\n\n function wpse231040_close_gallery_img_tags ( $html ) {\n if ( strpos ( $html, '#gallery-' ) === false ) { return $html; }\n // make sure there's at least one gallery before running the more expensive preg_replace\n\n $html = preg_replace(\n '/\n (\n \\<dl.*?class=[\"\\'].*?gallery-item[\\s\"\\'].*? # look inside a <dl> with gallery-item class\n \\<dt.*?class=[\"\\'].*?gallery-icon[\\s\"\\'].*? # look inside a <dt> with gallery-icon class\n \\<img\\s # look inside an <img> tag\n )\n (.*?)\\> # match the attributes inside the tag\n /sx',\n '$1$2 />', // add the initial content, the img tag attributes, and finally a closing />\n $html\n );\n\n return $html;\n }\n</code></pre>\n"
},
{
"answer_id": 231073,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Default wordpress galleries img tags close with invalid XHTML</p>\n</blockquote>\n\n<p>That's not the case, as far as I understand it.</p>\n\n<p>The native gallery <a href=\"https://github.com/WordPress/WordPress/blob/b39bddfd2a85fa79a0df3172cb540b484895860e/wp-includes/media.php#L1724-1728\" rel=\"nofollow\">uses</a> <code>wp_get_attachment_image()</code> to generate each image tag and <code>wp_get_attachment_link()</code>, that's a wrapper for <code>wp_get_attachment_image()</code>, to fetch the image link. </p>\n\n<p>The <a href=\"https://github.com/WordPress/WordPress/blob/b39bddfd2a85fa79a0df3172cb540b484895860e/wp-includes/media.php#L854-858\" rel=\"nofollow\">output</a> of <code>wp_get_attachment_image()</code> is:</p>\n\n<pre><code>$html = rtrim(\"<img $hwstring\");\nforeach ( $attr as $name => $value ) {\n $html .= \" $name=\" . '\"' . $value . '\"';\n}\n$html .= ' />';\n</code></pre>\n\n<p>where we can explicitly see the <code>/></code> closing.</p>\n"
}
] |
2016/06/29
|
[
"https://wordpress.stackexchange.com/questions/231040",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67879/"
] |
Default WordPress galleries img tags close like `<img>` which is invalid XHTML. The lazyload XT plugin that I'm using targets valid XHTML img tags which means ending should be:
```
<img src="http://www.acaciafotografia.com/wp-content/themes/jamdxstarter/img/tri.jpg"/>
```
*instead of*
```
<img src="http://www.acaciafotografia.com/wp-content/themes/jamdxstarter/img/tri.jpg">
```
How can I filter or modify this so lazyload works correctly?
[Issue explained by author of wp lazyload XT integration](https://wordpress.org/support/topic/unable-to-lazy-load?replies=8#post-8586177).
The theme I'm using, UNDERSCORES, modifies the markup of WP galleries to make it HTML5 compliant. This doesn't work well with Lazyload XT , that fetches XHTML img tags that end with "/>" , while HTML5 img tags don't need this and close with ">"
In `functions.php` I commented out the following line:
```
/*
* Switch default core markup for search form, comment form, and comments
* to output valid HTML5.
*/
add_theme_support( 'html5', array(
'search-form',
'comment-form',
'comment-list',
// 'gallery',
'caption',
) );
```
|
As [linked to](https://stackoverflow.com/a/23410472/1982136) from the comments on your question, the [post\_gallery filter](https://developer.wordpress.org/reference/hooks/post_gallery/) should help you here.
Unlike a lot of other hooks though, you can't filter the output that comes through from WordPress; you can only provide your own alternative output. This is slightly annoying, and results in you needing to build the gallery from scratch. You can do that with a bit of extra code, though, and the [linked StackOverflow answer](https://stackoverflow.com/a/23410472/1982136) provides an example (but strangely uses `<div src>`, so just change that to `<img src>` - and then draw from the default WordPress markup for the rest, making sure to close your `<img />` tag).
---
An alternative, where you *can* filter the output, is to use the [`the_content` filter](https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content) and some clever regex'ing. You need to be careful, because if you don't think of all potential cases, your regex could catch something you don't intend it to. This is exactly the problem the plugin author in this case is [trying to avoid](https://wordpress.org/support/topic/unable-to-lazy-load?replies=8).
With that said, here's a potential solution. Modify to your needs, but **don't rely on this as a 100% foolproof solution**.
```
// priority must be more than 10, so it runs after the gallery shortcode does
add_filter( 'the_content', 'wpse231040_close_gallery_img_tags', 11);
function wpse231040_close_gallery_img_tags ( $html ) {
if ( strpos ( $html, '#gallery-' ) === false ) { return $html; }
// make sure there's at least one gallery before running the more expensive preg_replace
$html = preg_replace(
'/
(
\<dl.*?class=["\'].*?gallery-item[\s"\'].*? # look inside a <dl> with gallery-item class
\<dt.*?class=["\'].*?gallery-icon[\s"\'].*? # look inside a <dt> with gallery-icon class
\<img\s # look inside an <img> tag
)
(.*?)\> # match the attributes inside the tag
/sx',
'$1$2 />', // add the initial content, the img tag attributes, and finally a closing />
$html
);
return $html;
}
```
|
231,054 |
<p>As you see this pagination. there is no "pre" button or text. because there is no previous posts. ( <a href="http://prntscr.com/bmuui2" rel="nofollow">http://prntscr.com/bmuui2</a> )</p>
<p>However I want to show the buttons (previous / next ) even if there is no (previous / next ) posts.</p>
<p>Because of design balance. </p>
<p>I want to make to show like this all the time. ( <a href="http://prntscr.com/bmutmv" rel="nofollow">http://prntscr.com/bmutmv</a> )</p>
<p>I use this code and refer this codex ( <a href="https://codex.wordpress.org/Function_Reference/paginate_links" rel="nofollow">https://codex.wordpress.org/Function_Reference/paginate_links</a> )</p>
<pre><code><?php
global $wp_query;
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages
) );
?>
</code></pre>
<p>I have tried to add more array values. but it seems no way to make it.</p>
<p>Thank you,</p>
|
[
{
"answer_id": 231045,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 1,
"selected": false,
"text": "<p>As <a href=\"https://stackoverflow.com/a/23410472/1982136\">linked to</a> from the comments on your question, the <a href=\"https://developer.wordpress.org/reference/hooks/post_gallery/\" rel=\"nofollow noreferrer\">post_gallery filter</a> should help you here.</p>\n\n<p>Unlike a lot of other hooks though, you can't filter the output that comes through from WordPress; you can only provide your own alternative output. This is slightly annoying, and results in you needing to build the gallery from scratch. You can do that with a bit of extra code, though, and the <a href=\"https://stackoverflow.com/a/23410472/1982136\">linked StackOverflow answer</a> provides an example (but strangely uses <code><div src></code>, so just change that to <code><img src></code> - and then draw from the default WordPress markup for the rest, making sure to close your <code><img /></code> tag).</p>\n\n<hr>\n\n<p>An alternative, where you <em>can</em> filter the output, is to use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content\" rel=\"nofollow noreferrer\"><code>the_content</code> filter</a> and some clever regex'ing. You need to be careful, because if you don't think of all potential cases, your regex could catch something you don't intend it to. This is exactly the problem the plugin author in this case is <a href=\"https://wordpress.org/support/topic/unable-to-lazy-load?replies=8\" rel=\"nofollow noreferrer\">trying to avoid</a>.</p>\n\n<p>With that said, here's a potential solution. Modify to your needs, but <strong>don't rely on this as a 100% foolproof solution</strong>.</p>\n\n<pre><code>// priority must be more than 10, so it runs after the gallery shortcode does\nadd_filter( 'the_content', 'wpse231040_close_gallery_img_tags', 11);\n\n function wpse231040_close_gallery_img_tags ( $html ) {\n if ( strpos ( $html, '#gallery-' ) === false ) { return $html; }\n // make sure there's at least one gallery before running the more expensive preg_replace\n\n $html = preg_replace(\n '/\n (\n \\<dl.*?class=[\"\\'].*?gallery-item[\\s\"\\'].*? # look inside a <dl> with gallery-item class\n \\<dt.*?class=[\"\\'].*?gallery-icon[\\s\"\\'].*? # look inside a <dt> with gallery-icon class\n \\<img\\s # look inside an <img> tag\n )\n (.*?)\\> # match the attributes inside the tag\n /sx',\n '$1$2 />', // add the initial content, the img tag attributes, and finally a closing />\n $html\n );\n\n return $html;\n }\n</code></pre>\n"
},
{
"answer_id": 231073,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Default wordpress galleries img tags close with invalid XHTML</p>\n</blockquote>\n\n<p>That's not the case, as far as I understand it.</p>\n\n<p>The native gallery <a href=\"https://github.com/WordPress/WordPress/blob/b39bddfd2a85fa79a0df3172cb540b484895860e/wp-includes/media.php#L1724-1728\" rel=\"nofollow\">uses</a> <code>wp_get_attachment_image()</code> to generate each image tag and <code>wp_get_attachment_link()</code>, that's a wrapper for <code>wp_get_attachment_image()</code>, to fetch the image link. </p>\n\n<p>The <a href=\"https://github.com/WordPress/WordPress/blob/b39bddfd2a85fa79a0df3172cb540b484895860e/wp-includes/media.php#L854-858\" rel=\"nofollow\">output</a> of <code>wp_get_attachment_image()</code> is:</p>\n\n<pre><code>$html = rtrim(\"<img $hwstring\");\nforeach ( $attr as $name => $value ) {\n $html .= \" $name=\" . '\"' . $value . '\"';\n}\n$html .= ' />';\n</code></pre>\n\n<p>where we can explicitly see the <code>/></code> closing.</p>\n"
}
] |
2016/06/30
|
[
"https://wordpress.stackexchange.com/questions/231054",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34463/"
] |
As you see this pagination. there is no "pre" button or text. because there is no previous posts. ( <http://prntscr.com/bmuui2> )
However I want to show the buttons (previous / next ) even if there is no (previous / next ) posts.
Because of design balance.
I want to make to show like this all the time. ( <http://prntscr.com/bmutmv> )
I use this code and refer this codex ( <https://codex.wordpress.org/Function_Reference/paginate_links> )
```
<?php
global $wp_query;
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages
) );
?>
```
I have tried to add more array values. but it seems no way to make it.
Thank you,
|
As [linked to](https://stackoverflow.com/a/23410472/1982136) from the comments on your question, the [post\_gallery filter](https://developer.wordpress.org/reference/hooks/post_gallery/) should help you here.
Unlike a lot of other hooks though, you can't filter the output that comes through from WordPress; you can only provide your own alternative output. This is slightly annoying, and results in you needing to build the gallery from scratch. You can do that with a bit of extra code, though, and the [linked StackOverflow answer](https://stackoverflow.com/a/23410472/1982136) provides an example (but strangely uses `<div src>`, so just change that to `<img src>` - and then draw from the default WordPress markup for the rest, making sure to close your `<img />` tag).
---
An alternative, where you *can* filter the output, is to use the [`the_content` filter](https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content) and some clever regex'ing. You need to be careful, because if you don't think of all potential cases, your regex could catch something you don't intend it to. This is exactly the problem the plugin author in this case is [trying to avoid](https://wordpress.org/support/topic/unable-to-lazy-load?replies=8).
With that said, here's a potential solution. Modify to your needs, but **don't rely on this as a 100% foolproof solution**.
```
// priority must be more than 10, so it runs after the gallery shortcode does
add_filter( 'the_content', 'wpse231040_close_gallery_img_tags', 11);
function wpse231040_close_gallery_img_tags ( $html ) {
if ( strpos ( $html, '#gallery-' ) === false ) { return $html; }
// make sure there's at least one gallery before running the more expensive preg_replace
$html = preg_replace(
'/
(
\<dl.*?class=["\'].*?gallery-item[\s"\'].*? # look inside a <dl> with gallery-item class
\<dt.*?class=["\'].*?gallery-icon[\s"\'].*? # look inside a <dt> with gallery-icon class
\<img\s # look inside an <img> tag
)
(.*?)\> # match the attributes inside the tag
/sx',
'$1$2 />', // add the initial content, the img tag attributes, and finally a closing />
$html
);
return $html;
}
```
|
231,087 |
<p>I want to make a permalink to my most recent blog post. I would use this link as a navbar link. The reason I'm not putting code straight into the navbar is because I am using a widget which will not let me get into the code, and my coding knowledge is next to none. Could someone ELI5 how to do this and where to insert any php if needed. Thanks in advance. </p>
<p>EDIT: Could you also explain how I would implement the PHP code or where I would put it in the WordPress environment.</p>
|
[
{
"answer_id": 231045,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 1,
"selected": false,
"text": "<p>As <a href=\"https://stackoverflow.com/a/23410472/1982136\">linked to</a> from the comments on your question, the <a href=\"https://developer.wordpress.org/reference/hooks/post_gallery/\" rel=\"nofollow noreferrer\">post_gallery filter</a> should help you here.</p>\n\n<p>Unlike a lot of other hooks though, you can't filter the output that comes through from WordPress; you can only provide your own alternative output. This is slightly annoying, and results in you needing to build the gallery from scratch. You can do that with a bit of extra code, though, and the <a href=\"https://stackoverflow.com/a/23410472/1982136\">linked StackOverflow answer</a> provides an example (but strangely uses <code><div src></code>, so just change that to <code><img src></code> - and then draw from the default WordPress markup for the rest, making sure to close your <code><img /></code> tag).</p>\n\n<hr>\n\n<p>An alternative, where you <em>can</em> filter the output, is to use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content\" rel=\"nofollow noreferrer\"><code>the_content</code> filter</a> and some clever regex'ing. You need to be careful, because if you don't think of all potential cases, your regex could catch something you don't intend it to. This is exactly the problem the plugin author in this case is <a href=\"https://wordpress.org/support/topic/unable-to-lazy-load?replies=8\" rel=\"nofollow noreferrer\">trying to avoid</a>.</p>\n\n<p>With that said, here's a potential solution. Modify to your needs, but <strong>don't rely on this as a 100% foolproof solution</strong>.</p>\n\n<pre><code>// priority must be more than 10, so it runs after the gallery shortcode does\nadd_filter( 'the_content', 'wpse231040_close_gallery_img_tags', 11);\n\n function wpse231040_close_gallery_img_tags ( $html ) {\n if ( strpos ( $html, '#gallery-' ) === false ) { return $html; }\n // make sure there's at least one gallery before running the more expensive preg_replace\n\n $html = preg_replace(\n '/\n (\n \\<dl.*?class=[\"\\'].*?gallery-item[\\s\"\\'].*? # look inside a <dl> with gallery-item class\n \\<dt.*?class=[\"\\'].*?gallery-icon[\\s\"\\'].*? # look inside a <dt> with gallery-icon class\n \\<img\\s # look inside an <img> tag\n )\n (.*?)\\> # match the attributes inside the tag\n /sx',\n '$1$2 />', // add the initial content, the img tag attributes, and finally a closing />\n $html\n );\n\n return $html;\n }\n</code></pre>\n"
},
{
"answer_id": 231073,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Default wordpress galleries img tags close with invalid XHTML</p>\n</blockquote>\n\n<p>That's not the case, as far as I understand it.</p>\n\n<p>The native gallery <a href=\"https://github.com/WordPress/WordPress/blob/b39bddfd2a85fa79a0df3172cb540b484895860e/wp-includes/media.php#L1724-1728\" rel=\"nofollow\">uses</a> <code>wp_get_attachment_image()</code> to generate each image tag and <code>wp_get_attachment_link()</code>, that's a wrapper for <code>wp_get_attachment_image()</code>, to fetch the image link. </p>\n\n<p>The <a href=\"https://github.com/WordPress/WordPress/blob/b39bddfd2a85fa79a0df3172cb540b484895860e/wp-includes/media.php#L854-858\" rel=\"nofollow\">output</a> of <code>wp_get_attachment_image()</code> is:</p>\n\n<pre><code>$html = rtrim(\"<img $hwstring\");\nforeach ( $attr as $name => $value ) {\n $html .= \" $name=\" . '\"' . $value . '\"';\n}\n$html .= ' />';\n</code></pre>\n\n<p>where we can explicitly see the <code>/></code> closing.</p>\n"
}
] |
2016/06/30
|
[
"https://wordpress.stackexchange.com/questions/231087",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97595/"
] |
I want to make a permalink to my most recent blog post. I would use this link as a navbar link. The reason I'm not putting code straight into the navbar is because I am using a widget which will not let me get into the code, and my coding knowledge is next to none. Could someone ELI5 how to do this and where to insert any php if needed. Thanks in advance.
EDIT: Could you also explain how I would implement the PHP code or where I would put it in the WordPress environment.
|
As [linked to](https://stackoverflow.com/a/23410472/1982136) from the comments on your question, the [post\_gallery filter](https://developer.wordpress.org/reference/hooks/post_gallery/) should help you here.
Unlike a lot of other hooks though, you can't filter the output that comes through from WordPress; you can only provide your own alternative output. This is slightly annoying, and results in you needing to build the gallery from scratch. You can do that with a bit of extra code, though, and the [linked StackOverflow answer](https://stackoverflow.com/a/23410472/1982136) provides an example (but strangely uses `<div src>`, so just change that to `<img src>` - and then draw from the default WordPress markup for the rest, making sure to close your `<img />` tag).
---
An alternative, where you *can* filter the output, is to use the [`the_content` filter](https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content) and some clever regex'ing. You need to be careful, because if you don't think of all potential cases, your regex could catch something you don't intend it to. This is exactly the problem the plugin author in this case is [trying to avoid](https://wordpress.org/support/topic/unable-to-lazy-load?replies=8).
With that said, here's a potential solution. Modify to your needs, but **don't rely on this as a 100% foolproof solution**.
```
// priority must be more than 10, so it runs after the gallery shortcode does
add_filter( 'the_content', 'wpse231040_close_gallery_img_tags', 11);
function wpse231040_close_gallery_img_tags ( $html ) {
if ( strpos ( $html, '#gallery-' ) === false ) { return $html; }
// make sure there's at least one gallery before running the more expensive preg_replace
$html = preg_replace(
'/
(
\<dl.*?class=["\'].*?gallery-item[\s"\'].*? # look inside a <dl> with gallery-item class
\<dt.*?class=["\'].*?gallery-icon[\s"\'].*? # look inside a <dt> with gallery-icon class
\<img\s # look inside an <img> tag
)
(.*?)\> # match the attributes inside the tag
/sx',
'$1$2 />', // add the initial content, the img tag attributes, and finally a closing />
$html
);
return $html;
}
```
|
231,096 |
<p>Using this code to get some data into a PHP array:</p>
<pre><code>$currentProducts = array();
$currentProducts = $wpdb->get_results("SELECT id, feedid, size, price FROM products WHERE shopid = $shopid");
</code></pre>
<p>No problems getting the data into a normal PHP array.</p>
<p>How do I get the data into an array where the feedid is key, so I can easily and quickly check if a specific feedid exist in the array, remove a specific feedid element etc?</p>
|
[
{
"answer_id": 231101,
"author": "dg4220",
"author_id": 91201,
"author_profile": "https://wordpress.stackexchange.com/users/91201",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure why you need to do that but, all you need is a loop:</p>\n\n<pre><code>foreach ( $currentProducts as $currentProduct ) \n{\n $myNewArray[$currentProduct->feedid] = $currentProduct->size;//use whatever value you need\n}\n</code></pre>\n"
},
{
"answer_id": 231234,
"author": "Louisa",
"author_id": 97605,
"author_profile": "https://wordpress.stackexchange.com/users/97605",
"pm_score": 3,
"selected": false,
"text": "<p>Found the solution:</p>\n\n<pre><code>$currentProducts = $wpdb->get_results(\"SELECT feedid, id, size, price FROM products WHERE shopid = $shopid\", OBJECT_K);\n</code></pre>\n\n<p>The OBJECT_K parameter makes an associative array with feedid as key: <a href=\"https://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results\" rel=\"noreferrer\">https://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results</a></p>\n"
}
] |
2016/06/30
|
[
"https://wordpress.stackexchange.com/questions/231096",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97605/"
] |
Using this code to get some data into a PHP array:
```
$currentProducts = array();
$currentProducts = $wpdb->get_results("SELECT id, feedid, size, price FROM products WHERE shopid = $shopid");
```
No problems getting the data into a normal PHP array.
How do I get the data into an array where the feedid is key, so I can easily and quickly check if a specific feedid exist in the array, remove a specific feedid element etc?
|
Found the solution:
```
$currentProducts = $wpdb->get_results("SELECT feedid, id, size, price FROM products WHERE shopid = $shopid", OBJECT_K);
```
The OBJECT\_K parameter makes an associative array with feedid as key: <https://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.