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
|
---|---|---|---|---|---|---|
250,547 |
<p>I have created a custom sidebar widgets using below code : </p>
<pre><code>register_sidebar(array(
'id' => 'sidebar-widget-1',
'name' => 'Sidebar Widget 1',
'before_widget' => '',
'after_widget' => '',
'before_title' => '',
'after_title' => '',
));
</code></pre>
<p>and it is showing in <code>Appearance -> Widgets</code> and it is also showing content on frontend using <code>dynamic_sidebar('Sidebar Widget 1')</code>.</p>
<p>But I want to get content of this <code>register_sidebar</code> by using its <code>id</code> into a variable.</p>
<p>How to get sidebar content by using its <code>id</code>?</p>
|
[
{
"answer_id": 250534,
"author": "jetyet47",
"author_id": 91783,
"author_profile": "https://wordpress.stackexchange.com/users/91783",
"pm_score": 2,
"selected": false,
"text": "<p>Not totally clear what you're asking, but post_class is probably your best bet.</p>\n\n<pre><code><?php post_class(); ?>\n</code></pre>\n\n<p>More info: <a href=\"https://codex.wordpress.org/Function_Reference/post_class\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/post_class</a></p>\n"
},
{
"answer_id": 250549,
"author": "Rishabh",
"author_id": 81621,
"author_profile": "https://wordpress.stackexchange.com/users/81621",
"pm_score": 0,
"selected": false,
"text": "<p>If you are showing list of latest post then here is the easier way of it in which you can add classes and DIV as per your wish.</p>\n\n<pre><code>$paged = get_query_var('paged') ? get_query_var('paged') : 1;\n $args = array(\n 'post_type' => 'post', //Post type that you want to show\n 'posts_per_page' => 5, //No. of Pages to show \n 'offset' => 0, //excluding the latest post if any\n 'paged' => $paged //For Pagination\n );\n\n$loop = new WP_Query( $args );\n\nwhile ( $loop->have_posts() ) : $loop->the_post();?>\n <?php /*** Title of Post ***/ ?>\n <h3><a href=\"<?php the_permalink() ?>\" title=\"<?php the_title(); ?>\"><?php the_title();?></a></h3>\n <?php /*** Title of Post ends ***/ ?>\n <?php \n /***** Thumbnail ******/\n the_post_thumbnail(\n array(120, 90), \n array(\n\n 'class' => 'enter_class', //custom class for post thumbnail if any \n 'alt' => 'post thumbnail', //post thumbnail alternate title\n 'title' => 'my custom title' //Title of thumbnail\n )\n );\n/******* Thumbnail Ends ********/\n/*** Post contents/Description ***/\nthe_excerpt();\n/*** Post contents/Description ends ***/\n?> \n<?php \nendwhile;\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>If you want to add div on individual post then you need to add div inside <code>while</code> loop. </p>\n\n<p>If you want to wrap your every post in individual div then add div in <code>while</code> loop in above mentioned code like this</p>\n\n<pre><code><?php while ( $loop->have_posts() ) : $loop->the_post(); ?>\n<div class=\"enter_class_name\">\n <?php\n //Rest of the code in while loop like title,description and thumbnail code will come here.\n ?>\n\n</div>\n</code></pre>\n\n<p><strong>NOTE</strong> Make sure you don't add DIV inside php tags (<code><?php ?></code>). Specify your DIV outside php tags.</p>\n\n<p>And you can also add DIV in parts of post also. For example if you want to add DIV to wrap thumbnail of every posta individually then you can also do that easily.</p>\n\n<p>To do that you have to read all comments in code to understand what code is using to show thumbnail of post and simply wrap that code inside DIV. And your post thumbnail will be enclosed in separate DIV. </p>\n\n<p>In my given code this piece of code inside while loop is responsible for showing post thumbnail</p>\n\n<pre><code><?php \n/***** Thumbnail ******/\nthe_post_thumbnail(\n array(120, 90), \n array(\n\n 'class' => 'enter_class', //custom class for post thumbnail if any \n 'alt' => 'post thumbnail', //post thumbnail alternate title\n 'title' => 'my custom title' //Title of thumbnail\n )\n);\n/******* Thumbnail Ends ********/\n</code></pre>\n\n<p>And to wrap thumbnail inside div, just wrap this code inside div(outside php tags) like this</p>\n\n<pre><code><div class=\"enter_class_name\">\n <?php \n /***** Thumbnail ******/\n the_post_thumbnail(\n array(120, 90), \n array(\n\n 'class' => 'enter_class', //custom class for post thumbnail if any \n 'alt' => 'post thumbnail', //post thumbnail alternate title\n 'title' => 'my custom title' //Title of thumbnail\n )\n );\n /******* Thumbnail Ends ********/\n ?>\n</div>\n</code></pre>\n\n<p>Like this you can also wrap your Title of post or Description of post in separate DIV just by enclosing their respective code in DIV. </p>\n\n<p>BUT make sure to put all DIVs only inside <code>while</code> loop. Only then your posts will get separate DIV. </p>\n\n<p>And it is strongly recommended that you read all comments line attach to the code carefully to understand every line of code is performing what kind of action/activity. This info will help you to add DIV as per your need.</p>\n"
}
] |
2016/12/28
|
[
"https://wordpress.stackexchange.com/questions/250547",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74147/"
] |
I have created a custom sidebar widgets using below code :
```
register_sidebar(array(
'id' => 'sidebar-widget-1',
'name' => 'Sidebar Widget 1',
'before_widget' => '',
'after_widget' => '',
'before_title' => '',
'after_title' => '',
));
```
and it is showing in `Appearance -> Widgets` and it is also showing content on frontend using `dynamic_sidebar('Sidebar Widget 1')`.
But I want to get content of this `register_sidebar` by using its `id` into a variable.
How to get sidebar content by using its `id`?
|
Not totally clear what you're asking, but post\_class is probably your best bet.
```
<?php post_class(); ?>
```
More info: <https://codex.wordpress.org/Function_Reference/post_class>
|
250,565 |
<p>Based on <a href="https://wordpress.stackexchange.com/questions/50233/how-to-develop-a-theme-while-having-another-show-up?noredirect=1&lq=1">answers like this one</a>, I made a small plugin to display a theme displaying a "Coming soon" theme, whilst our team of editors can fill in the final theme.</p>
<p>It worked yesterday, but today, even though I'm logged in, I only see the "waiting" theme.
I logged out and logged back in, but still, I'm seeing the "waiting" theme, as if the <code>is_user_logged_in()</code> function returned false. Are these hooks too early to check for user authentification?</p>
<pre><code><?php
add_filter('template', 'pxln_change_theme');
add_filter('stylesheet', 'pxln_change_theme');
function pxln_change_theme($theme) {
if ( ! is_user_logged_in() ) {
$theme = 'waiting';
}
return $theme;
}
</code></pre>
|
[
{
"answer_id": 250573,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference\" rel=\"nofollow noreferrer\">Filters</a>, unlike actions, don't run at a specific moment, but when the function they are attached too, is called. The template-filter is called from <a href=\"https://developer.wordpress.org/reference/functions/get_template/\" rel=\"nofollow noreferrer\"><code>get_template</code></a> and the stylesheet-filter from <a href=\"https://developer.wordpress.org/reference/functions/get_stylesheet/\" rel=\"nofollow noreferrer\"><code>get_stylesheet</code></a>.</p>\n\n<p>Typically, these functions are called to enqueue styles and scripts using <code>wp_enqueue-scripts</code>, an <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">action that takes place after</a> the current user has been set. However, it is not uncommon to see these functions also called from a function that is attached to <code>after_setup_theme</code>, which is fired before the current user has been set.</p>\n\n<p>So, you will have to check your theme for the use of <code>get_template</code> and <code>get_stylesheet</code> (or a function that uses them, which you can find under 'used by' in the links above). Then check if the function is attached to a hook that is too early. </p>\n"
},
{
"answer_id": 250575,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Try hooking on all these:</p>\n\n<p>(But I guess you'd have to do it from a plugin, since doing it from theme <code>functions.php</code> might be too late).</p>\n\n<p>E.g.:</p>\n\n<pre><code>/*\nPlugin Name: test\nDescription: switchtest\nVersion: 0.1.0\n*/\n\nadd_filter( 'template', 'yourthing_switch_theme' );\nadd_filter( 'option_template', 'yourthing_switch_theme' );\nadd_filter( 'option_stylesheet', 'yourthing_switch_theme' );\nadd_filter( 'pre_option_stylesheet', 'yourthing_switch_theme' );\n\nfunction yourthing_switch_theme( $theme )\n{\n if ( is_user_logged_in() ) {\n return $theme;\n }\n else {\n return 'waiting';\n }\n}\n</code></pre>\n"
}
] |
2016/12/28
|
[
"https://wordpress.stackexchange.com/questions/250565",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82/"
] |
Based on [answers like this one](https://wordpress.stackexchange.com/questions/50233/how-to-develop-a-theme-while-having-another-show-up?noredirect=1&lq=1), I made a small plugin to display a theme displaying a "Coming soon" theme, whilst our team of editors can fill in the final theme.
It worked yesterday, but today, even though I'm logged in, I only see the "waiting" theme.
I logged out and logged back in, but still, I'm seeing the "waiting" theme, as if the `is_user_logged_in()` function returned false. Are these hooks too early to check for user authentification?
```
<?php
add_filter('template', 'pxln_change_theme');
add_filter('stylesheet', 'pxln_change_theme');
function pxln_change_theme($theme) {
if ( ! is_user_logged_in() ) {
$theme = 'waiting';
}
return $theme;
}
```
|
[Filters](https://codex.wordpress.org/Plugin_API/Filter_Reference), unlike actions, don't run at a specific moment, but when the function they are attached too, is called. The template-filter is called from [`get_template`](https://developer.wordpress.org/reference/functions/get_template/) and the stylesheet-filter from [`get_stylesheet`](https://developer.wordpress.org/reference/functions/get_stylesheet/).
Typically, these functions are called to enqueue styles and scripts using `wp_enqueue-scripts`, an [action that takes place after](https://codex.wordpress.org/Plugin_API/Action_Reference) the current user has been set. However, it is not uncommon to see these functions also called from a function that is attached to `after_setup_theme`, which is fired before the current user has been set.
So, you will have to check your theme for the use of `get_template` and `get_stylesheet` (or a function that uses them, which you can find under 'used by' in the links above). Then check if the function is attached to a hook that is too early.
|
250,587 |
<p>My understanding of private posts/pages is that they only work when you are logged into the WP admin system as an administrator or editor. </p>
<p>I have a site where I need to occasionally share custom posts to users via links and I don't want them to appear elsewhere on the site. Setting posts to "private" almost does what I want as it instantly removes the posts from the site homepage and other areas that it would normally be included. </p>
<p>The only problem is that the private post feature assumes I want to look at the post when logged in to the admin which is not the case as I get a 404 error when not logged in. I want to share this post with strangers manually as and when I need to without a password and for them to appear as normal via their standard permalink.</p>
<p>This may well be plugin territory but to my surprise I haven't found one that does that. </p>
<p>To clarify, the post type I need to implement this on is a custom post type defined by a plugin that the site needs in order to run.</p>
|
[
{
"answer_id": 250613,
"author": "jetyet47",
"author_id": 91783,
"author_profile": "https://wordpress.stackexchange.com/users/91783",
"pm_score": 0,
"selected": false,
"text": "<p>Probably plugin territory, because as you mention the way private pages work, they are only visible to logged in admin or editor level users.</p>\n\n<p>See <a href=\"https://codex.wordpress.org/Content_Visibility\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Content_Visibility</a></p>\n\n<p>Not totally clear on your use case, but you may be able to create a custom post type that is not visible on index pages (set public to false, don't add an archive for it, etc.) so only someone with the permalink could see it. Someone could guess the permalink though, so it wouldn't be totally 'private'.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#Arguments\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_post_type#Arguments</a></p>\n"
},
{
"answer_id": 250790,
"author": "swissspidy",
"author_id": 12404,
"author_profile": "https://wordpress.stackexchange.com/users/12404",
"pm_score": 1,
"selected": false,
"text": "<p>In WordPress core, private posts are probably the closest you can get without using a plugin. Since you mentioned that you need to send links to private posts to others, I recommend you to not re-invent the wheel and use one of the plugins out there that does this.</p>\n\n<p>For example, I can highly recommend <a href=\"https://wordpress.org/plugins/public-post-preview/\" rel=\"nofollow noreferrer\">Public Post Preview</a> by WordPress Core Committer Dominik Schilling (ocean90). I think it does exactly what you want:</p>\n\n<blockquote>\n <p>Enables you to give a link to anonymous users for public preview of a post before it is published.</p>\n</blockquote>\n\n<p>It handles all the link expiration stuff, capability checks, etc. for you so you don't have to worry about accidentally exposing too much of your content when using a custom built solution.</p>\n"
},
{
"answer_id": 250791,
"author": "Jami Gibbs",
"author_id": 75524,
"author_profile": "https://wordpress.stackexchange.com/users/75524",
"pm_score": 3,
"selected": true,
"text": "<p>If you <em>don't</em> want to use a plugin (or can't find one that does what you're needing), you might want to approach it this way:</p>\n\n<ol>\n<li>Add a <a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\">custom meta box</a> that allows you to mark the post as <code>hidden</code>.</li>\n<li>Modifying the query with <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/\" rel=\"nofollow noreferrer\">pre_get_posts</a> to remove the posts you've labeled as hidden from your site (but will be available with a direct link).</li>\n</ol>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Following the suggestion above, here is a possible solution. </p>\n\n<p><strong>Create a custom meta box</strong></p>\n\n<p>First, create the custom meta box by registering one:</p>\n\n<pre><code>function yourtextdomain_add_custom_meta_box() {\n add_meta_box(\"demo-meta-box\", \"Custom Meta Box\", \"yourtextdomain_custom_meta_box_markup\", \"post\", \"side\", \"high\", null);\n}\nadd_action(\"add_meta_boxes\", \"yourtextdomain_add_custom_meta_box\");\n</code></pre>\n\n<p>Add the markup to the metabox (a checkbox in the case):</p>\n\n<pre><code>function yourtextdomain_custom_meta_box_markup($object) {\n wp_nonce_field(basename(__FILE__), \"meta-box-nonce\"); ?>\n <div>\n <br />\n <label for=\"meta-box-checkbox\">Hidden</label>\n\n <?php $checkbox_value = get_post_meta($object->ID, \"meta-box-checkbox\", true);\n if($checkbox_value == \"\") { ?>\n\n <input name=\"meta-box-checkbox\" type=\"checkbox\" value=\"true\">\n\n <?php } else if($checkbox_value == \"true\") { ?>\n\n <input name=\"meta-box-checkbox\" type=\"checkbox\" value=\"true\" checked>\n\n <?php } ?>\n\n <p style=\"color: #cccccc\"><i>When selected, the post will be removed from the WP loop but still accessible from a direct link.</i></p>\n </div>\n <?php\n}\n</code></pre>\n\n<p>This will give you a meta box for each post that looks like this:</p>\n\n<p><img src=\"https://i.stack.imgur.com/4WWEF.png\" width=\"450\"></p>\n\n<p>And finally save the meta box value:</p>\n\n<pre><code>function yourtextdomain_save_custom_meta_box($post_id, $post, $update) {\n if (!isset($_POST[\"meta-box-nonce\"]) || !wp_verify_nonce($_POST[\"meta-box-nonce\"], basename(__FILE__)))\n return $post_id;\n\n if(!current_user_can(\"edit_post\", $post_id))\n return $post_id;\n\n if(defined(\"DOING_AUTOSAVE\") && DOING_AUTOSAVE)\n return $post_id;\n\n $slug = \"post\";\n\n if($slug != $post->post_type)\n return $post_id;\n\n $meta_box_checkbox_value = \"\";\n\n if(isset($_POST[\"meta-box-checkbox\"])) {\n $meta_box_checkbox_value = $_POST[\"meta-box-checkbox\"];\n }\n update_post_meta($post_id, \"meta-box-checkbox\", $meta_box_checkbox_value);\n}\nadd_action(\"save_post\", \"yourtextdomain_save_custom_meta_box\", 10, 3);\n</code></pre>\n\n<p>In the <code>wp_postmeta</code> table, you should now see the meta value 'true' assigned to the posts you've checked as hidden and saved:</p>\n\n<p><a href=\"https://i.stack.imgur.com/JXucB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JXucB.png\" alt=\"Post Meta Table\"></a></p>\n\n<p><strong>Modifying the query with pre_get_posts</strong></p>\n\n<p>Now it's just a matter of filtering out those posts that are marked as hidden from the main query. We can do this with <code>pre_get_posts</code>:</p>\n\n<pre><code>add_action( 'pre_get_posts', 'yourtextdomain_pre_get_posts_hidden', 9999 );\nfunction yourtextdomain_pre_get_posts_hidden( $query ){\n\n // Check if on frontend and main query.\n if( ! is_admin() && $query->is_main_query() ) {\n\n // For the posts we want to exclude.\n $exclude = array();\n\n // Locate our posts marked as hidden.\n $hidden = get_posts(array(\n 'post_type' => 'post',\n 'meta_query' => array(\n array(\n 'key' => 'meta-box-checkbox',\n 'value' => 'true',\n 'compare' => '==',\n ),\n )\n ));\n\n // Create an array of hidden posts.\n foreach($hidden as $hide) {\n $exclude[] = $hide->ID;\n }\n\n // Exclude the hidden posts.\n $query->set('post__not_in', $exclude);\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 251060,
"author": "codiiv",
"author_id": 91561,
"author_profile": "https://wordpress.stackexchange.com/users/91561",
"pm_score": 0,
"selected": false,
"text": "<p>1) Create a custom post type that is NOT public (e.g \"hidden_posts\"). </p>\n\n<p>2) Create a custom template in the current them and run a custom $wpdb query passing the post_type parameter to \"hidden_posts\" in the template</p>\n\n<p>3) Create a regular page using the template you just created. </p>\n\n<p>4) Add the page in (3) to your robots text and deny access to make sure it is not indexed! </p>\n\n<p>5) Vote my answer as the best :) </p>\n\n<p>NB: If you need a detailed code of this, let me know ! </p>\n"
},
{
"answer_id": 251095,
"author": "Pratik bhatt",
"author_id": 60922,
"author_profile": "https://wordpress.stackexchange.com/users/60922",
"pm_score": 0,
"selected": false,
"text": "<p>You can make a custom post type for this type of posts that you want to display only to non-logged in user .</p>\n\n<p>in the you can customize the single.php file for your custom posttype by overriding it in custom-postype.php in this you can check if the user is not logged in you can display it else not.</p>\n\n<p>Let me know your views in below by comment </p>\n"
}
] |
2016/12/28
|
[
"https://wordpress.stackexchange.com/questions/250587",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28543/"
] |
My understanding of private posts/pages is that they only work when you are logged into the WP admin system as an administrator or editor.
I have a site where I need to occasionally share custom posts to users via links and I don't want them to appear elsewhere on the site. Setting posts to "private" almost does what I want as it instantly removes the posts from the site homepage and other areas that it would normally be included.
The only problem is that the private post feature assumes I want to look at the post when logged in to the admin which is not the case as I get a 404 error when not logged in. I want to share this post with strangers manually as and when I need to without a password and for them to appear as normal via their standard permalink.
This may well be plugin territory but to my surprise I haven't found one that does that.
To clarify, the post type I need to implement this on is a custom post type defined by a plugin that the site needs in order to run.
|
If you *don't* want to use a plugin (or can't find one that does what you're needing), you might want to approach it this way:
1. Add a [custom meta box](https://developer.wordpress.org/reference/functions/add_meta_box/) that allows you to mark the post as `hidden`.
2. Modifying the query with [pre\_get\_posts](https://developer.wordpress.org/reference/hooks/pre_get_posts/) to remove the posts you've labeled as hidden from your site (but will be available with a direct link).
**UPDATE**
Following the suggestion above, here is a possible solution.
**Create a custom meta box**
First, create the custom meta box by registering one:
```
function yourtextdomain_add_custom_meta_box() {
add_meta_box("demo-meta-box", "Custom Meta Box", "yourtextdomain_custom_meta_box_markup", "post", "side", "high", null);
}
add_action("add_meta_boxes", "yourtextdomain_add_custom_meta_box");
```
Add the markup to the metabox (a checkbox in the case):
```
function yourtextdomain_custom_meta_box_markup($object) {
wp_nonce_field(basename(__FILE__), "meta-box-nonce"); ?>
<div>
<br />
<label for="meta-box-checkbox">Hidden</label>
<?php $checkbox_value = get_post_meta($object->ID, "meta-box-checkbox", true);
if($checkbox_value == "") { ?>
<input name="meta-box-checkbox" type="checkbox" value="true">
<?php } else if($checkbox_value == "true") { ?>
<input name="meta-box-checkbox" type="checkbox" value="true" checked>
<?php } ?>
<p style="color: #cccccc"><i>When selected, the post will be removed from the WP loop but still accessible from a direct link.</i></p>
</div>
<?php
}
```
This will give you a meta box for each post that looks like this:

And finally save the meta box value:
```
function yourtextdomain_save_custom_meta_box($post_id, $post, $update) {
if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-box-nonce"], basename(__FILE__)))
return $post_id;
if(!current_user_can("edit_post", $post_id))
return $post_id;
if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE)
return $post_id;
$slug = "post";
if($slug != $post->post_type)
return $post_id;
$meta_box_checkbox_value = "";
if(isset($_POST["meta-box-checkbox"])) {
$meta_box_checkbox_value = $_POST["meta-box-checkbox"];
}
update_post_meta($post_id, "meta-box-checkbox", $meta_box_checkbox_value);
}
add_action("save_post", "yourtextdomain_save_custom_meta_box", 10, 3);
```
In the `wp_postmeta` table, you should now see the meta value 'true' assigned to the posts you've checked as hidden and saved:
[](https://i.stack.imgur.com/JXucB.png)
**Modifying the query with pre\_get\_posts**
Now it's just a matter of filtering out those posts that are marked as hidden from the main query. We can do this with `pre_get_posts`:
```
add_action( 'pre_get_posts', 'yourtextdomain_pre_get_posts_hidden', 9999 );
function yourtextdomain_pre_get_posts_hidden( $query ){
// Check if on frontend and main query.
if( ! is_admin() && $query->is_main_query() ) {
// For the posts we want to exclude.
$exclude = array();
// Locate our posts marked as hidden.
$hidden = get_posts(array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'meta-box-checkbox',
'value' => 'true',
'compare' => '==',
),
)
));
// Create an array of hidden posts.
foreach($hidden as $hide) {
$exclude[] = $hide->ID;
}
// Exclude the hidden posts.
$query->set('post__not_in', $exclude);
}
}
```
|
250,614 |
<p>I am trying to create taxonomy elements (the taxonomies are already registered) from the front end using the REST Api v2. I am able to do so except not able to save the meta fields from the taxonomies.</p>
<hr>
<p>I have a registered taxonomy ("place") and I am trying to create elements for it using the Rest Api.</p>
<p>The taxonomy has a term meta ("my_meta"). I am able to get the information from the taxonomy:</p>
<pre><code>add_action( 'rest_api_init', 'slug_register_meta' );
function slug_register_meta() {
register_rest_field( 'place',
'meta',
array(
'get_callback' => 'slug_get_meta',
'update_callback' => null,
'schema' => null,
)
);
}
function slug_get_meta( $object, $field_name, $request ) {
return get_term_meta( $object[ 'id' ] );
}
</code></pre>
<p>which lets me get the information when I access: /wp-json/wp/v2/place/53</p>
<pre><code>{
"id": 53,
"count": 0,
...
"taxonomy": "place",
"meta": {
"my_meta": [
"the meta value"
]
},
...
}
</code></pre>
<p>I can register a new taxonomy element through JavaScript:</p>
<pre><code>var place_new = new wp.api.models.Place({
name: 'the name',// works
description: 'the description',// works
my_meta: 'test1',// doesn't work
fields: {// doesn't work
my_meta: 'test3'
},
meta: {// doesn't work
my_meta: 'test2'
}
});
place_new.save();
</code></pre>
<p><strong>The problem is the my_meta value won't save</strong>, I am not sure how to refer to it or if there is some PHP I am missing.</p>
|
[
{
"answer_id": 250695,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 0,
"selected": false,
"text": "<p>You should pass your meta value as an array to your meta key.</p>\n\n<pre><code>var place_new = new wp.api.models.Place({\n name: 'the name',// works\n description: 'the description',// works\n\n meta: {\n \"my_meta\": [\n \"new_meta_value\"\n ]\n }\n\n});\n</code></pre>\n"
},
{
"answer_id": 318803,
"author": "alexwc_",
"author_id": 47344,
"author_profile": "https://wordpress.stackexchange.com/users/47344",
"pm_score": 3,
"selected": true,
"text": "<p>I think you need an <code>update_callback</code> in <code>register_rest_field()</code>. Please note that I haven't tested this.</p>\n\n<pre><code>add_action( 'rest_api_init', 'slug_register_meta' );\nfunction slug_register_meta() {\n register_rest_field( 'place',\n 'meta', \n array(\n 'get_callback' => 'slug_get_meta',\n 'update_callback' => 'slug_update_meta',\n 'schema' => null,\n )\n );\n}\nfunction slug_get_meta( $object, $field_name, $request ) {\n return get_term_meta( $object[ 'id' ] );\n}\nfunction slug_update_meta($value, $object, $field_name){\n // please note: make sure that $object is indeed and object or array\n return update_post_meta($object['id'], $field_name, $value);\n}\n</code></pre>\n"
}
] |
2016/12/28
|
[
"https://wordpress.stackexchange.com/questions/250614",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16533/"
] |
I am trying to create taxonomy elements (the taxonomies are already registered) from the front end using the REST Api v2. I am able to do so except not able to save the meta fields from the taxonomies.
---
I have a registered taxonomy ("place") and I am trying to create elements for it using the Rest Api.
The taxonomy has a term meta ("my\_meta"). I am able to get the information from the taxonomy:
```
add_action( 'rest_api_init', 'slug_register_meta' );
function slug_register_meta() {
register_rest_field( 'place',
'meta',
array(
'get_callback' => 'slug_get_meta',
'update_callback' => null,
'schema' => null,
)
);
}
function slug_get_meta( $object, $field_name, $request ) {
return get_term_meta( $object[ 'id' ] );
}
```
which lets me get the information when I access: /wp-json/wp/v2/place/53
```
{
"id": 53,
"count": 0,
...
"taxonomy": "place",
"meta": {
"my_meta": [
"the meta value"
]
},
...
}
```
I can register a new taxonomy element through JavaScript:
```
var place_new = new wp.api.models.Place({
name: 'the name',// works
description: 'the description',// works
my_meta: 'test1',// doesn't work
fields: {// doesn't work
my_meta: 'test3'
},
meta: {// doesn't work
my_meta: 'test2'
}
});
place_new.save();
```
**The problem is the my\_meta value won't save**, I am not sure how to refer to it or if there is some PHP I am missing.
|
I think you need an `update_callback` in `register_rest_field()`. Please note that I haven't tested this.
```
add_action( 'rest_api_init', 'slug_register_meta' );
function slug_register_meta() {
register_rest_field( 'place',
'meta',
array(
'get_callback' => 'slug_get_meta',
'update_callback' => 'slug_update_meta',
'schema' => null,
)
);
}
function slug_get_meta( $object, $field_name, $request ) {
return get_term_meta( $object[ 'id' ] );
}
function slug_update_meta($value, $object, $field_name){
// please note: make sure that $object is indeed and object or array
return update_post_meta($object['id'], $field_name, $value);
}
```
|
250,616 |
<p><strong>For example:</strong> </p>
<ul>
<li><code>mydomain.com/embed</code> automatically redirecting to homepage although I
haven't set redirection. </li>
<li>I want to add a page in my website name embed and for this page URL<br>
automatically becoming <code>mydomain.com/embed-2</code>.</li>
</ul>
<p>I checked everything, there is no existing or trash post, page, tags Etc. </p>
<p><strong>How to remove that existing embed slug from the database?</strong> </p>
<p>Thanks</p>
|
[
{
"answer_id": 250695,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 0,
"selected": false,
"text": "<p>You should pass your meta value as an array to your meta key.</p>\n\n<pre><code>var place_new = new wp.api.models.Place({\n name: 'the name',// works\n description: 'the description',// works\n\n meta: {\n \"my_meta\": [\n \"new_meta_value\"\n ]\n }\n\n});\n</code></pre>\n"
},
{
"answer_id": 318803,
"author": "alexwc_",
"author_id": 47344,
"author_profile": "https://wordpress.stackexchange.com/users/47344",
"pm_score": 3,
"selected": true,
"text": "<p>I think you need an <code>update_callback</code> in <code>register_rest_field()</code>. Please note that I haven't tested this.</p>\n\n<pre><code>add_action( 'rest_api_init', 'slug_register_meta' );\nfunction slug_register_meta() {\n register_rest_field( 'place',\n 'meta', \n array(\n 'get_callback' => 'slug_get_meta',\n 'update_callback' => 'slug_update_meta',\n 'schema' => null,\n )\n );\n}\nfunction slug_get_meta( $object, $field_name, $request ) {\n return get_term_meta( $object[ 'id' ] );\n}\nfunction slug_update_meta($value, $object, $field_name){\n // please note: make sure that $object is indeed and object or array\n return update_post_meta($object['id'], $field_name, $value);\n}\n</code></pre>\n"
}
] |
2016/12/28
|
[
"https://wordpress.stackexchange.com/questions/250616",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109805/"
] |
**For example:**
* `mydomain.com/embed` automatically redirecting to homepage although I
haven't set redirection.
* I want to add a page in my website name embed and for this page URL
automatically becoming `mydomain.com/embed-2`.
I checked everything, there is no existing or trash post, page, tags Etc.
**How to remove that existing embed slug from the database?**
Thanks
|
I think you need an `update_callback` in `register_rest_field()`. Please note that I haven't tested this.
```
add_action( 'rest_api_init', 'slug_register_meta' );
function slug_register_meta() {
register_rest_field( 'place',
'meta',
array(
'get_callback' => 'slug_get_meta',
'update_callback' => 'slug_update_meta',
'schema' => null,
)
);
}
function slug_get_meta( $object, $field_name, $request ) {
return get_term_meta( $object[ 'id' ] );
}
function slug_update_meta($value, $object, $field_name){
// please note: make sure that $object is indeed and object or array
return update_post_meta($object['id'], $field_name, $value);
}
```
|
250,626 |
<p>Is it possible to add controls to sub panels of the widgets panel in the customizer? If yes, how do I address them? The widget area would be named “top-widget-area”</p>
<p>Neither addressing:</p>
<pre><code>'panel' => 'widgets-top-widget-area'
</code></pre>
<p>nor</p>
<pre><code>'section' => 'widgets-top-widget-area'
</code></pre>
<p>in <code>$wp_customize->add_control</code> work.</p>
<p>Do you have an idea?</p>
|
[
{
"answer_id": 250695,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 0,
"selected": false,
"text": "<p>You should pass your meta value as an array to your meta key.</p>\n\n<pre><code>var place_new = new wp.api.models.Place({\n name: 'the name',// works\n description: 'the description',// works\n\n meta: {\n \"my_meta\": [\n \"new_meta_value\"\n ]\n }\n\n});\n</code></pre>\n"
},
{
"answer_id": 318803,
"author": "alexwc_",
"author_id": 47344,
"author_profile": "https://wordpress.stackexchange.com/users/47344",
"pm_score": 3,
"selected": true,
"text": "<p>I think you need an <code>update_callback</code> in <code>register_rest_field()</code>. Please note that I haven't tested this.</p>\n\n<pre><code>add_action( 'rest_api_init', 'slug_register_meta' );\nfunction slug_register_meta() {\n register_rest_field( 'place',\n 'meta', \n array(\n 'get_callback' => 'slug_get_meta',\n 'update_callback' => 'slug_update_meta',\n 'schema' => null,\n )\n );\n}\nfunction slug_get_meta( $object, $field_name, $request ) {\n return get_term_meta( $object[ 'id' ] );\n}\nfunction slug_update_meta($value, $object, $field_name){\n // please note: make sure that $object is indeed and object or array\n return update_post_meta($object['id'], $field_name, $value);\n}\n</code></pre>\n"
}
] |
2016/12/28
|
[
"https://wordpress.stackexchange.com/questions/250626",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109814/"
] |
Is it possible to add controls to sub panels of the widgets panel in the customizer? If yes, how do I address them? The widget area would be named “top-widget-area”
Neither addressing:
```
'panel' => 'widgets-top-widget-area'
```
nor
```
'section' => 'widgets-top-widget-area'
```
in `$wp_customize->add_control` work.
Do you have an idea?
|
I think you need an `update_callback` in `register_rest_field()`. Please note that I haven't tested this.
```
add_action( 'rest_api_init', 'slug_register_meta' );
function slug_register_meta() {
register_rest_field( 'place',
'meta',
array(
'get_callback' => 'slug_get_meta',
'update_callback' => 'slug_update_meta',
'schema' => null,
)
);
}
function slug_get_meta( $object, $field_name, $request ) {
return get_term_meta( $object[ 'id' ] );
}
function slug_update_meta($value, $object, $field_name){
// please note: make sure that $object is indeed and object or array
return update_post_meta($object['id'], $field_name, $value);
}
```
|
250,633 |
<p>I am making a wordpress site but i need little help,</p>
<p>What I have is a function with Next and Previous buttons to list projects, but
when i go to the last project the Next button is gone.</p>
<p>What I want to do is, when I go to the last project I hit "Next" and direct me to the first project something like loop slide</p>
<p>Here is my code:</p>
<pre><code><?php if (has_term( 'type-1', 'projecttype' ) ) { ?>
<div class="holder">
<?php if ( have_posts() ) : ?>
<div class="container-fluid">
<div class="project-paginat">
<?php if(get_post_meta($post->ID, "_type", true)){ ?>
<ul class="list-inline">
<li><a href="<?php echo get_home_url(); ?>/our-work">Back to Our Work</a></li>
<li>>> &nbsp;<?php echo get_post_meta($post->ID, "_type", true); ?></li>
<li><?php previous_post_link('%link', '&lt; Previous Project', true, '', 'projectcategory') ?></li>
<li><?php next_post_link('%link', 'Next Project &gt;', true, '', 'projectcategory') ?></li>
</ul>
<?php } else {
echo '<p>There Is No Project Type To Display.</p>';
} ?>
</div>
</code></pre>
|
[
{
"answer_id": 250644,
"author": "iguanarama",
"author_id": 109807,
"author_profile": "https://wordpress.stackexchange.com/users/109807",
"pm_score": 2,
"selected": true,
"text": "<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_adjacent_post\" rel=\"nofollow noreferrer\">get_adjacent_post</a> to first see if there's actually a next post:</p>\n\n<pre><code>if (get_adjacent_post (false, '', false)) {\n next_post_link ('%link', 'Next Project &gt;', true, '', 'projectcategory');\n} else {\n // manually create link to first post here\n}\n</code></pre>\n\n<p><a href=\"http://wplancer.com/infinite-next-and-previous-post-looping-in-wordpress/\" rel=\"nofollow noreferrer\">This site</a> shows one way of actually getting the first post's link, such as with a WP_Query call and then calling get_permalink. The exact code depends on the types of post you are showing.</p>\n"
},
{
"answer_id": 250659,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 0,
"selected": false,
"text": "<p>Using the link in <strong>iguanarama's</strong> answer, your updated code would be:</p>\n\n<pre><code><?php if (has_term( 'type-1', 'projecttype' ) ) { ?>\n<div class=\"holder\">\n <?php if ( have_posts() ) : ?>\n <div class=\"container-fluid\">\n <div class=\"project-paginat\">\n <?php if(get_post_meta($post->ID, \"_type\", true)){ ?>\n <ul class=\"list-inline\">\n <li><a href=\"<?php echo get_home_url(); ?>/our-work\">Back to Our Work</a></li>\n <li>>> &nbsp;<?php echo get_post_meta($post->ID, \"_type\", true); ?></li>\n <li>\n <?php\n if( get_adjacent_post(false, '', true) ) {\n previous_post_link('%link', '&lt; Previous Project', true, '', 'projectcategory');\n } else {\n $args = array(\n 'posts_per_page' => 1,\n 'order' => 'DESC',\n 'category_name' => 'projectcategory',\n );\n $first = new WP_Query( $args ); $first->the_post();\n echo '<a href=\"' . get_permalink() . '\">&lt; Previous Project</a>';\n wp_reset_query();\n };\n\n ?>\n </li>\n <li>\n <?php\n if( get_adjacent_post(false, '', false) ) {\n next_post_link('%link', 'Next Project &gt;', true, '', 'projectcategory');\n } else {\n $args = array(\n 'posts_per_page' => 1,\n 'order' => 'ASC',\n 'category_name' => 'projectcategory',\n );\n $last = new WP_Query( $args ); $last->the_post();\n echo '<a href=\"' . get_permalink() . '\">Next Project &gt;</a>';\n wp_reset_query();\n };\n\n ?>\n </li>\n </ul>\n <?php } else {\n echo '<p>There Is No Project Type To Display.</p>';\n } ?>\n </div>\n</code></pre>\n\n<p><strong>Reference:</strong> <a href=\"http://wplancer.com/infinite-next-and-previous-post-looping-in-wordpress/\" rel=\"nofollow noreferrer\">http://wplancer.com/infinite-next-and-previous-post-looping-in-wordpress/</a></p>\n"
},
{
"answer_id": 379638,
"author": "Nuno Sarmento",
"author_id": 75461,
"author_profile": "https://wordpress.stackexchange.com/users/75461",
"pm_score": 0,
"selected": false,
"text": "<p>You can use get_adjacent_post, see below working example.</p>\n<pre><code> <?php\n /**\n * Infinite next and previous post looping in WordPress\n */\n if( get_adjacent_post(false, '', true) ) {\n previous_post_link('%link', '&larr; Previous Post');\n } else {\n $first = new WP_Query('posts_per_page=1&order=DESC'); $first->the_post();\n echo '<a href="' . get_permalink() . '">&larr; Previous Post</a>';\n wp_reset_query();\n };\n\n if( get_adjacent_post(false, '', false) ) {\n next_post_link('%link', 'Next Post &rarr;');\n } else {\n $last = new WP_Query('posts_per_page=1&order=ASC'); $last->the_post();\n echo '<a href="' . get_permalink() . '">Next Post &rarr;</a>';\n wp_reset_query();\n };\n\n ?>\n</code></pre>\n"
}
] |
2016/12/29
|
[
"https://wordpress.stackexchange.com/questions/250633",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101369/"
] |
I am making a wordpress site but i need little help,
What I have is a function with Next and Previous buttons to list projects, but
when i go to the last project the Next button is gone.
What I want to do is, when I go to the last project I hit "Next" and direct me to the first project something like loop slide
Here is my code:
```
<?php if (has_term( 'type-1', 'projecttype' ) ) { ?>
<div class="holder">
<?php if ( have_posts() ) : ?>
<div class="container-fluid">
<div class="project-paginat">
<?php if(get_post_meta($post->ID, "_type", true)){ ?>
<ul class="list-inline">
<li><a href="<?php echo get_home_url(); ?>/our-work">Back to Our Work</a></li>
<li>>> <?php echo get_post_meta($post->ID, "_type", true); ?></li>
<li><?php previous_post_link('%link', '< Previous Project', true, '', 'projectcategory') ?></li>
<li><?php next_post_link('%link', 'Next Project >', true, '', 'projectcategory') ?></li>
</ul>
<?php } else {
echo '<p>There Is No Project Type To Display.</p>';
} ?>
</div>
```
|
Use [get\_adjacent\_post](https://codex.wordpress.org/Function_Reference/get_adjacent_post) to first see if there's actually a next post:
```
if (get_adjacent_post (false, '', false)) {
next_post_link ('%link', 'Next Project >', true, '', 'projectcategory');
} else {
// manually create link to first post here
}
```
[This site](http://wplancer.com/infinite-next-and-previous-post-looping-in-wordpress/) shows one way of actually getting the first post's link, such as with a WP\_Query call and then calling get\_permalink. The exact code depends on the types of post you are showing.
|
250,637 |
<p>Ultimately, I'm really confused on how exactly you create a single class that affects each post in a static home page "recent post" type content area. I want to essentially have it where there's a post with a background, a space, then the next post with the same background, but not have the background behind all the posts. I hope that makes sense. Here's the code I have, but no matter what I do, I'm only able to add a class for one post at a time with the ID. </p>
<pre><code><ul>
<?php $the_query = new WP_Query( 'posts_per_page=5' ); ?>
<div class="new_home_single"><?php the_post()?></div>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
<?php the_excerpt(__('(more…)')); ?>
<?php
endwhile;
wp_reset_postdata();
?>
</ul>
</code></pre>
|
[
{
"answer_id": 250639,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": true,
"text": "<p>Wordpress already generates class for each posts, you can use these classes using the <a href=\"https://developer.wordpress.org/reference/functions/post_class/\" rel=\"nofollow noreferrer\"><strong><code>post_class</code></strong></a> function.</p>\n\n<p><strong>Note:</strong> The function can be used either within the loop or by passing the <code>$post_id</code></p>\n\n<p>So you would have</p>\n\n<pre><code><ul>\n <?php $the_query = new WP_Query( 'posts_per_page=5' ); ?>\n\n <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>\n\n <div id=\"post-<?php the_ID(); ?>\" <?php post_class( 'post' ); ?>>\n <a href=\"<?php the_permalink() ?>\"><?php the_title(); ?></a>\n\n <?php the_excerpt(__('(more…)')); ?>\n </div>\n\n <?php\n endwhile;\n wp_reset_postdata();\n ?>\n</ul>\n</code></pre>\n"
},
{
"answer_id": 250640,
"author": "iguanarama",
"author_id": 109807,
"author_profile": "https://wordpress.stackexchange.com/users/109807",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>I hope that makes sense.</p>\n</blockquote>\n\n<p>Partly :) But if I've understood it right and you want to style each post excerpt you'll need a container around it that you can reference with CSS, and currently, you've got your class \"new_home_single\" outside the while loop, so that single class is being applied to all your post excerpts.</p>\n\n<p>So the simplest change to your code is to add a wrapper around the excerpt like this:</p>\n\n<pre><code><div class=\"post-excerpt\">\n <a href=\"<?php the_permalink() ?>\"><?php the_title(); ?></a>\n <?php the_excerpt(__('(more…)')); ?>\n</div>\n</code></pre>\n\n<p>And then some CSS to style each excerpt, using margin instead of padding to have background-free space between each one:</p>\n\n<pre><code>.post-excerpt {\n background-color: #dddddd;\n margin: 2rem 0;\n}\n</code></pre>\n"
}
] |
2016/12/29
|
[
"https://wordpress.stackexchange.com/questions/250637",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108586/"
] |
Ultimately, I'm really confused on how exactly you create a single class that affects each post in a static home page "recent post" type content area. I want to essentially have it where there's a post with a background, a space, then the next post with the same background, but not have the background behind all the posts. I hope that makes sense. Here's the code I have, but no matter what I do, I'm only able to add a class for one post at a time with the ID.
```
<ul>
<?php $the_query = new WP_Query( 'posts_per_page=5' ); ?>
<div class="new_home_single"><?php the_post()?></div>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
<?php the_excerpt(__('(more…)')); ?>
<?php
endwhile;
wp_reset_postdata();
?>
</ul>
```
|
Wordpress already generates class for each posts, you can use these classes using the [**`post_class`**](https://developer.wordpress.org/reference/functions/post_class/) function.
**Note:** The function can be used either within the loop or by passing the `$post_id`
So you would have
```
<ul>
<?php $the_query = new WP_Query( 'posts_per_page=5' ); ?>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class( 'post' ); ?>>
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
<?php the_excerpt(__('(more…)')); ?>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</ul>
```
|
250,662 |
<p>Let's say I have two pages on a WordPress site with content (text, HTML, shortcodes). How could I create a shortcode to display the content from Page A when Page B loads?</p>
<p>I recognize of course that this has the potential to become an infinite loop if used improperly and that there are potential formatting hazards. Best practices aside, there is an important use case for it on our site.</p>
|
[
{
"answer_id": 250688,
"author": "robin416",
"author_id": 109865,
"author_profile": "https://wordpress.stackexchange.com/users/109865",
"pm_score": 0,
"selected": false,
"text": "<p><P>Jeff Starr's <A HREF=\"https://wordpress.org/plugins/simple-custom-content/\" rel=\"nofollow noreferrer\">Simple Custom Content</A> plugin provides Shortcodes to add custom content to specific Posts and Pages and one of its features is adding custom content to specific Posts and Pages. The plugin's primary use is adding boilerplate such as copyright information, official policies, disclaimers, etc. but may serve your purpose.</P><P>Check out the <A HREF=\"https://en-ca.wordpress.org/plugins/tags/tldr\" rel=\"nofollow noreferrer\">tl;dr — Tags — WordPress Plugins</A> for plugins which enable content to be injected into a page or post.</P></p>\n"
},
{
"answer_id": 250759,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 3,
"selected": false,
"text": "<p>You can create a shortcode as below:</p>\n\n<pre><code>function wpse250662_post_content_shortcode($atts) {\n\n $args = shortcode_atts( array(\n 'pagename' => ''\n ), $atts );\n\n $query = new WP_Query( $args );\n\n if ( $query->have_posts() ) :\n while ( $query->have_posts() ) : $query->the_post();\n $content = apply_filters('the_content',get_the_content( ));\n ob_start();\n ?>\n <div class=\"content\">\n <?php echo $content; ?>\n </div>\n <?php\n endwhile;\n endif;\n wp_reset_postdata();\n return ob_get_clean();\n}\nadd_shortcode('wpse250662-content', 'wpse250662_post_content_shortcode');\n</code></pre>\n\n<p><strong>USAGE:</strong></p>\n\n<p><code>[wpse250662-content pagename=\"</code><strong><code>PAGE SLUG YOU WANT TO DISPLAY</code></strong><code>\"]</code></p>\n\n<p><strong>Resources: <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"noreferrer\">Shortcode API</a></strong></p>\n"
}
] |
2016/12/29
|
[
"https://wordpress.stackexchange.com/questions/250662",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96983/"
] |
Let's say I have two pages on a WordPress site with content (text, HTML, shortcodes). How could I create a shortcode to display the content from Page A when Page B loads?
I recognize of course that this has the potential to become an infinite loop if used improperly and that there are potential formatting hazards. Best practices aside, there is an important use case for it on our site.
|
You can create a shortcode as below:
```
function wpse250662_post_content_shortcode($atts) {
$args = shortcode_atts( array(
'pagename' => ''
), $atts );
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
$content = apply_filters('the_content',get_the_content( ));
ob_start();
?>
<div class="content">
<?php echo $content; ?>
</div>
<?php
endwhile;
endif;
wp_reset_postdata();
return ob_get_clean();
}
add_shortcode('wpse250662-content', 'wpse250662_post_content_shortcode');
```
**USAGE:**
`[wpse250662-content pagename="`**`PAGE SLUG YOU WANT TO DISPLAY`**`"]`
**Resources: [Shortcode API](https://codex.wordpress.org/Shortcode_API)**
|
250,675 |
<p>I was importing my website' database on to another server but it is showing this error which I have no idea about:</p>
<p><img src="https://i.imgur.com/6vRhZag.png" alt=""></p>
<p>I tried importing the database multiple times but failed.
I also checked 'Add Drop Table' field that comes when exporting the database file but it didn't do anything.</p>
|
[
{
"answer_id": 250676,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 4,
"selected": true,
"text": "<p>This issue is as a result of your server not supporting the <code>utf8mb4_unicode_520_ci</code> collation type.</p>\n\n<p>To resolve this you should convert the collation for all tables with <code>utf8mb4_unicode_520_ci</code> to <code>utf8_general_ci</code></p>\n\n<p><strong>If you're exporting through phpmyadmin, you can:</strong></p>\n\n<ol>\n<li><p>Click the \"Export\" tab for the database</p></li>\n<li><p>Click the \"Custom\" radio button</p></li>\n<li><p>Go the section titled \"Format-specific options\" and change the\ndropdown for \"Database system or older MySQL server to maximize\noutput compatibility with:\" from NONE to MYSQL40.</p></li>\n<li><p>Scroll to the bottom and click \"GO\".</p></li>\n</ol>\n\n<p><strong>OR run the following query on each of the affected tables:</strong></p>\n\n<pre><code>ALTER TABLE myTable CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci\n</code></pre>\n\n<p><strong>UPDATE:</strong>\n You should also replace in your sql exported file <code>TYPE=MyISAM</code> with <code>ENGINE=MyISAM</code></p>\n"
},
{
"answer_id": 251567,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": false,
"text": "<p>For some, the collation <code>utf8mb4_unicode_520_ci</code> looks strange but WordPress uses this collation when possible. Other collations are the second best.</p>\n\n<p>Note this line:</p>\n\n<blockquote>\n <p>// _unicode_520_ is a better collation, we should use that when it's available.</p>\n</blockquote>\n\n<p>Some plugins will create <code>utf8mb4_unicode_520_ci</code> collation tables no matter what.</p>\n\n<pre><code>File: /var/www/html/test100.com/wp-includes/wp-db.php\n761: /**\n762: * Determines the best charset and collation to use given a charset and collation.\n763: *\n764: * For example, when able, utf8mb4 should be used instead of utf8.\n765: *\n766: * @since 4.6.0\n767: * @access public\n768: *\n769: * @param string $charset The character set to check.\n770: * @param string $collate The collation to check.\n771: * @return array The most appropriate character set and collation to use.\n772: */\n773: public function determine_charset( $charset, $collate ) {\n774: if ( ( $this->use_mysqli && ! ( $this->dbh instanceof mysqli ) ) || empty( $this->dbh ) ) {\n775: return compact( 'charset', 'collate' );\n776: }\n777: \n778: if ( 'utf8' === $charset && $this->has_cap( 'utf8mb4' ) ) {\n779: $charset = 'utf8mb4';\n780: }\n781: \n782: if ( 'utf8mb4' === $charset && ! $this->has_cap( 'utf8mb4' ) ) {\n783: $charset = 'utf8';\n784: $collate = str_replace( 'utf8mb4_', 'utf8_', $collate );\n785: }\n786: \n787: if ( 'utf8mb4' === $charset ) {\n788: // _general_ is outdated, so we can upgrade it to _unicode_, instead.\n789: if ( ! $collate || 'utf8_general_ci' === $collate ) {\n790: $collate = 'utf8mb4_unicode_ci';\n791: } else {\n792: $collate = str_replace( 'utf8_', 'utf8mb4_', $collate );\n793: }\n794: }\n795: \n796: // _unicode_520_ is a better collation, we should use that when it's available.\n797: if ( $this->has_cap( 'utf8mb4_520' ) && 'utf8mb4_unicode_ci' === $collate ) {\n798: $collate = 'utf8mb4_unicode_520_ci';\n799: }\n800: \n801: return compact( 'charset', 'collate' );\n802: }\n</code></pre>\n\n<blockquote>\n <p>The <code>utf8mb4_unicode_520_ci</code> (Unicode Collation Algorithm 5.2.0, October 2010) collation is an improvement over <code>utf8mb4_unicode_ci</code> (UCA 4.0.0, November 2003).</p>\n</blockquote>\n\n<p>There is no word on when MySQL will support later UCAs.</p>\n\n<p><strong>The very latest UCA is 9.0.0 <a href=\"http://www.unicode.org/reports/tr10/\" rel=\"nofollow noreferrer\">http://www.unicode.org/reports/tr10/</a></strong>, but MySQL doesn't support that.</p>\n"
}
] |
2016/12/29
|
[
"https://wordpress.stackexchange.com/questions/250675",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106457/"
] |
I was importing my website' database on to another server but it is showing this error which I have no idea about:

I tried importing the database multiple times but failed.
I also checked 'Add Drop Table' field that comes when exporting the database file but it didn't do anything.
|
This issue is as a result of your server not supporting the `utf8mb4_unicode_520_ci` collation type.
To resolve this you should convert the collation for all tables with `utf8mb4_unicode_520_ci` to `utf8_general_ci`
**If you're exporting through phpmyadmin, you can:**
1. Click the "Export" tab for the database
2. Click the "Custom" radio button
3. Go the section titled "Format-specific options" and change the
dropdown for "Database system or older MySQL server to maximize
output compatibility with:" from NONE to MYSQL40.
4. Scroll to the bottom and click "GO".
**OR run the following query on each of the affected tables:**
```
ALTER TABLE myTable CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci
```
**UPDATE:**
You should also replace in your sql exported file `TYPE=MyISAM` with `ENGINE=MyISAM`
|
250,725 |
<p>Now its display only 12 item</p>
<p>Here is code. can you please anyone help me</p>
<pre><code><?php query_posts('post_type=faq&post_status=publish&order=DESC&orderby=date=' ) ?>
<?php if( have_posts() ): ?>
<ul id="myUL" class="margb-40">
<?php while( have_posts() ): the_post(); ?>
</code></pre>
|
[
{
"answer_id": 250726,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 0,
"selected": false,
"text": "<p>you could always add: </p>\n\n<pre><code>'posts_per_page'=-1\n\n<?php query_posts('posts_per_page=-1&post_type=faq&post_status=publish&order=DESC&orderby=date=' ) ?>\n <?php if( have_posts() ): ?>\n <ul id=\"myUL\" class=\"margb-40\">\n <?php while( have_posts() ): the_post(); ?>\n</code></pre>\n\n<p>if that doesn't work put it in an array:</p>\n\n<pre><code><?php query_posts( array(\n 'category_name' => 'my-category-slug',\n 'posts_per_page' => -1,\n 'post_type' => 'faq',\n 'post_status'=> 'publish',\n 'order'=> 'DESC',\n 'orderby'=> 'date', \n) );\n?>\n<?php if( have_posts() ): ?>\n<ul id=\"myUL\" class=\"margb-40\">\n<?php while( have_posts() ): the_post(); ?>\n</code></pre>\n\n<p>lastly try changing posts_per_page to numberposts.</p>\n"
},
{
"answer_id": 250727,
"author": "SierraTR",
"author_id": 49035,
"author_profile": "https://wordpress.stackexchange.com/users/49035",
"pm_score": 0,
"selected": false,
"text": "<p>WP Dashboard\nSettings\nReading\nProbably set to display at most 12 posts on blog page.</p>\n"
},
{
"answer_id": 250731,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><strong>WP_Query</strong></a></p>\n\n<pre><code><?php \n $args = array(\n 'post_type' => 'faq',\n 'post_status' => 'publish',\n 'order' => 'DESC',\n 'orderby' => 'date',\n 'posts_per_page' => -1\n );\n\n $query = new WP_Query( $args );\n\nif( $query->have_posts() ): ?>\n <ul id=\"myUL\" class=\"margb-40\">\n <?php while( $query->have_posts() ): $query->the_post(); ?>\n\n //content\n\n <?php\n endwhile; ?>\n </ul>\n<?php\n wp_reset_postdata();\nendif;\n</code></pre>\n"
},
{
"answer_id": 250732,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>If you plan to use <code>query_posts</code> you need to use: </p>\n\n<p><code>wp_reset_query();</code> after the block.</p>\n\n<pre><code>while( have_posts() ): the_post(); \n// do\nendwhile;\n</code></pre>\n"
}
] |
2016/12/29
|
[
"https://wordpress.stackexchange.com/questions/250725",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109890/"
] |
Now its display only 12 item
Here is code. can you please anyone help me
```
<?php query_posts('post_type=faq&post_status=publish&order=DESC&orderby=date=' ) ?>
<?php if( have_posts() ): ?>
<ul id="myUL" class="margb-40">
<?php while( have_posts() ): the_post(); ?>
```
|
You can use [**WP\_Query**](https://codex.wordpress.org/Class_Reference/WP_Query)
```
<?php
$args = array(
'post_type' => 'faq',
'post_status' => 'publish',
'order' => 'DESC',
'orderby' => 'date',
'posts_per_page' => -1
);
$query = new WP_Query( $args );
if( $query->have_posts() ): ?>
<ul id="myUL" class="margb-40">
<?php while( $query->have_posts() ): $query->the_post(); ?>
//content
<?php
endwhile; ?>
</ul>
<?php
wp_reset_postdata();
endif;
```
|
250,734 |
<p>I have the following code and i am trying to exclude a specific category id ex-144</p>
<pre><code>function product_count_shortcode( ) {
$count_posts = wp_count_posts( 'product' );
return $count_posts->publish;
}
add_shortcode( 'product_count', 'product_count_shortcode' );
</code></pre>
<p>How can exclude one category?</p>
|
[
{
"answer_id": 250726,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 0,
"selected": false,
"text": "<p>you could always add: </p>\n\n<pre><code>'posts_per_page'=-1\n\n<?php query_posts('posts_per_page=-1&post_type=faq&post_status=publish&order=DESC&orderby=date=' ) ?>\n <?php if( have_posts() ): ?>\n <ul id=\"myUL\" class=\"margb-40\">\n <?php while( have_posts() ): the_post(); ?>\n</code></pre>\n\n<p>if that doesn't work put it in an array:</p>\n\n<pre><code><?php query_posts( array(\n 'category_name' => 'my-category-slug',\n 'posts_per_page' => -1,\n 'post_type' => 'faq',\n 'post_status'=> 'publish',\n 'order'=> 'DESC',\n 'orderby'=> 'date', \n) );\n?>\n<?php if( have_posts() ): ?>\n<ul id=\"myUL\" class=\"margb-40\">\n<?php while( have_posts() ): the_post(); ?>\n</code></pre>\n\n<p>lastly try changing posts_per_page to numberposts.</p>\n"
},
{
"answer_id": 250727,
"author": "SierraTR",
"author_id": 49035,
"author_profile": "https://wordpress.stackexchange.com/users/49035",
"pm_score": 0,
"selected": false,
"text": "<p>WP Dashboard\nSettings\nReading\nProbably set to display at most 12 posts on blog page.</p>\n"
},
{
"answer_id": 250731,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><strong>WP_Query</strong></a></p>\n\n<pre><code><?php \n $args = array(\n 'post_type' => 'faq',\n 'post_status' => 'publish',\n 'order' => 'DESC',\n 'orderby' => 'date',\n 'posts_per_page' => -1\n );\n\n $query = new WP_Query( $args );\n\nif( $query->have_posts() ): ?>\n <ul id=\"myUL\" class=\"margb-40\">\n <?php while( $query->have_posts() ): $query->the_post(); ?>\n\n //content\n\n <?php\n endwhile; ?>\n </ul>\n<?php\n wp_reset_postdata();\nendif;\n</code></pre>\n"
},
{
"answer_id": 250732,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>If you plan to use <code>query_posts</code> you need to use: </p>\n\n<p><code>wp_reset_query();</code> after the block.</p>\n\n<pre><code>while( have_posts() ): the_post(); \n// do\nendwhile;\n</code></pre>\n"
}
] |
2016/12/29
|
[
"https://wordpress.stackexchange.com/questions/250734",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108699/"
] |
I have the following code and i am trying to exclude a specific category id ex-144
```
function product_count_shortcode( ) {
$count_posts = wp_count_posts( 'product' );
return $count_posts->publish;
}
add_shortcode( 'product_count', 'product_count_shortcode' );
```
How can exclude one category?
|
You can use [**WP\_Query**](https://codex.wordpress.org/Class_Reference/WP_Query)
```
<?php
$args = array(
'post_type' => 'faq',
'post_status' => 'publish',
'order' => 'DESC',
'orderby' => 'date',
'posts_per_page' => -1
);
$query = new WP_Query( $args );
if( $query->have_posts() ): ?>
<ul id="myUL" class="margb-40">
<?php while( $query->have_posts() ): $query->the_post(); ?>
//content
<?php
endwhile; ?>
</ul>
<?php
wp_reset_postdata();
endif;
```
|
250,753 |
<p>I need to get a list of all pages in a dropdown list, so I can get the page id of the selected page to store in the options of my plugin.</p>
<p>Right now I have:</p>
<pre><code>?>
<input name='wpplf23_plugin_options[thankyou_page]' type='number' value='<?php if ( ( isset( $options['thankyou_page'] ) ) ) { echo $options['thankyou_page']; } ?>' />
<?php
</code></pre>
<p>To just store the id manually.</p>
<p>I found this code:</p>
<pre><code>$args = array(
'depth' => 0,
'child_of' => 0,
'selected' => 0,
'echo' => 1,
'name' => 'page_id',
'id' => null, // string
'class' => null, // string
'show_option_none' => null, // string
'show_option_no_change' => null, // string
'option_none_value' => null, // string
);
wp_dropdown_pages( $args );
</code></pre>
<p>But I cant work out how to get it to do what I need. How would I go about this?</p>
<p>Thanks for any help you can provide me.</p>
|
[
{
"answer_id": 250755,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 1,
"selected": false,
"text": "<p>Try below code.</p>\n\n<pre><code><select name=\"page\"> \n <option value=\"\"><?php echo esc_attr( __( 'Select page' ) ); ?></option> \n <?php \n $pages = get_pages(); \n foreach ( $pages as $page ) {\n $option = '<option value=\"' . $page->ID . '\">'.$page->post_title.'</option>';\n echo $option;\n }\n ?>\n</select>\n</code></pre>\n\n<p>Hope this will helps you.</p>\n"
},
{
"answer_id": 250777,
"author": "LWS-Mo",
"author_id": 88895,
"author_profile": "https://wordpress.stackexchange.com/users/88895",
"pm_score": 2,
"selected": false,
"text": "<p>Iam using following code to display a page select dropdown menu on an plugin option page.</p>\n\n<p>If you select an page and save it, the next time you visit the option-site, you will also see which page was saved. (so no more \"select page\")</p>\n\n<p>You can use the WordPress <em>selected()</em> function, you can find more details here:\n<a href=\"https://codex.wordpress.org/Function_Reference/selected\" rel=\"nofollow noreferrer\" title=\"https://codex.wordpress.org/Function_Reference/selected\">https://codex.wordpress.org/Function_Reference/selected</a></p>\n\n<pre><code>$options = get_option( 'my_settings' ); ?>\n\n<select name='my_settings[selected_page]'>\n <option value='0'><?php _e('Select a Page', 'textdomain'); ?></option>\n <?php $pages = get_pages(); ?>\n <?php foreach( $pages as $page ) { ?>\n <option value='<?php echo $page->ID; ?>' <?php selected( $options['selected_page'], $page->ID ); ?> ><?php echo $page->post_title; ?></option>\n <?php }; ?>\n</select>\n</code></pre>\n\n<p>You just need to get the current-saved-value of the field and than use the WP <em>selected()</em> function to compare the current-saved-value with the <code>$page->ID</code>.</p>\n\n<p>Maybe this can help you.</p>\n"
}
] |
2016/12/30
|
[
"https://wordpress.stackexchange.com/questions/250753",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109162/"
] |
I need to get a list of all pages in a dropdown list, so I can get the page id of the selected page to store in the options of my plugin.
Right now I have:
```
?>
<input name='wpplf23_plugin_options[thankyou_page]' type='number' value='<?php if ( ( isset( $options['thankyou_page'] ) ) ) { echo $options['thankyou_page']; } ?>' />
<?php
```
To just store the id manually.
I found this code:
```
$args = array(
'depth' => 0,
'child_of' => 0,
'selected' => 0,
'echo' => 1,
'name' => 'page_id',
'id' => null, // string
'class' => null, // string
'show_option_none' => null, // string
'show_option_no_change' => null, // string
'option_none_value' => null, // string
);
wp_dropdown_pages( $args );
```
But I cant work out how to get it to do what I need. How would I go about this?
Thanks for any help you can provide me.
|
Iam using following code to display a page select dropdown menu on an plugin option page.
If you select an page and save it, the next time you visit the option-site, you will also see which page was saved. (so no more "select page")
You can use the WordPress *selected()* function, you can find more details here:
[https://codex.wordpress.org/Function\_Reference/selected](https://codex.wordpress.org/Function_Reference/selected "https://codex.wordpress.org/Function_Reference/selected")
```
$options = get_option( 'my_settings' ); ?>
<select name='my_settings[selected_page]'>
<option value='0'><?php _e('Select a Page', 'textdomain'); ?></option>
<?php $pages = get_pages(); ?>
<?php foreach( $pages as $page ) { ?>
<option value='<?php echo $page->ID; ?>' <?php selected( $options['selected_page'], $page->ID ); ?> ><?php echo $page->post_title; ?></option>
<?php }; ?>
</select>
```
You just need to get the current-saved-value of the field and than use the WP *selected()* function to compare the current-saved-value with the `$page->ID`.
Maybe this can help you.
|
250,761 |
<p>Example: I have following HTML code and where should I place that <code>bootstrap.min.css</code> link. If I place that link in HTML code itself, when the page is published it's not loading the CSS.</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Thumbnail</h2>
<p>The .img-thumbnail class creates a thumbnail of the image:</p>
<img src="cinqueterre.jpg" class="img-thumbnail" alt="Cinque Terre" width="304" height="236">
</div>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 250764,
"author": "dgarceran",
"author_id": 109222,
"author_profile": "https://wordpress.stackexchange.com/users/109222",
"pm_score": 1,
"selected": false,
"text": "<p>Use <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style()</a> in your functions.php:</p>\n\n<pre><code>function custom_wp_enqueue_style() {\nwp_enqueue_style( 'bootstrapcdn', \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css\" );\n}\nadd_action ( 'wp_enqueue_scripts', 'custom_wp_enqueue_style' );\n</code></pre>\n\n<p>The second parameter can be the path to the folder in your server where you have your bootstrap.</p>\n"
},
{
"answer_id": 250765,
"author": "Jayesh",
"author_id": 98501,
"author_profile": "https://wordpress.stackexchange.com/users/98501",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to load css then you have to simply add single php line before css link.\nCall this line before href and src link.</p>\n\n<pre><code><?php echo esc_url( get_template_directory_uri() ); ?>/\n</code></pre>\n\n<p>using this line you can load all type of css and image also.\nhere you are trying to link bootstrap \nexample:-</p>\n\n<pre><code><link rel=\"stylesheet\" href=\"<?php echo esc_url( get_template_directory_uri() ); ?>/https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\n</code></pre>\n\n<p>now your css will work.</p>\n"
},
{
"answer_id": 304654,
"author": "eyal_katz",
"author_id": 97833,
"author_profile": "https://wordpress.stackexchange.com/users/97833",
"pm_score": 0,
"selected": false,
"text": "<p>If other methods don't work, you can always use @import inside another css file:</p>\n\n<p>@import url(\"stylesheet_2.css\");</p>\n\n<p>This will work, but may not be as fast since it is waiting for the other css to load before loading the rest of the css.</p>\n\n<p>Sometimes there's no other choice, in case it's a website that you have limited access to, or complicated setup, etc.</p>\n"
}
] |
2016/12/30
|
[
"https://wordpress.stackexchange.com/questions/250761",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109905/"
] |
Example: I have following HTML code and where should I place that `bootstrap.min.css` link. If I place that link in HTML code itself, when the page is published it's not loading the CSS.
```
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Thumbnail</h2>
<p>The .img-thumbnail class creates a thumbnail of the image:</p>
<img src="cinqueterre.jpg" class="img-thumbnail" alt="Cinque Terre" width="304" height="236">
</div>
</body>
</html>
```
|
Use [wp\_enqueue\_style()](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) in your functions.php:
```
function custom_wp_enqueue_style() {
wp_enqueue_style( 'bootstrapcdn', "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" );
}
add_action ( 'wp_enqueue_scripts', 'custom_wp_enqueue_style' );
```
The second parameter can be the path to the folder in your server where you have your bootstrap.
|
250,797 |
<p>I have made a query which gives me 8 results. I need to show these in 2 columns of 4 items.</p>
<p>This is my query :</p>
<pre><code> $args = array(
'post_type' => 'event',
'meta_key' => 'date',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'posts_per_page' => 8,
'meta_query' => array(
'key' => 'date',
'value' => date('Y-m-d',strtotime("today")),
'compare' => '>=',
'type' => 'DATE'
),
);
$events = new WP_Query( $args );
</code></pre>
<p>I tried using array_splice. Example :</p>
<pre><code> $firstCol = array_slice($events, 0, 4, true);
$secondCol = array_slice($events, 4, true);
</code></pre>
<p>But this does not seem to work. How can I get 2 arrays from my result?</p>
|
[
{
"answer_id": 250808,
"author": "Anas Bouayour",
"author_id": 109935,
"author_profile": "https://wordpress.stackexchange.com/users/109935",
"pm_score": 0,
"selected": false,
"text": "<p>if i realy understand your question, put the array in a loop and use a variable as counter </p>\n\n<pre><code>$count=0; \n$firstCol=array(); \n$secondCol=array(); \nforeach($events as $event) {\n $count++;\n if($count <= 4 ) {\n array_push($firstCol, $event);\n }\n else {\n array_push($secondCol, $event);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 250815,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": true,
"text": "<p>There's no need to split the array, you can just close the first div once you've counted up to four elements of the array.</p>\n\n<pre><code>$args = array(\n 'post_type' => 'event',\n 'meta_key' => 'date',\n 'orderby' => 'meta_value_num',\n 'order' => 'ASC',\n 'posts_per_page' => 8,\n 'meta_query' => array(\n 'key' => 'date',\n 'value' => date('Y-m-d',strtotime(\"today\")),\n 'compare' => '>=',\n 'type' => 'DATE'\n ),\n);\n\n$events = new WP_Query( $args ); \n$count = 1;\n\nif ( $events->have_posts() ) : ?>\n <div class=\"column-1\">\n <?php while ( $events->have_posts() ) : $events->the_post();\n // YOUR CONTENT\nif ( $count == 4 ) { ?>\n </div>\n <div class=\"column-2\">\n<?php }\n\n $count++;\n endwhile;\n wp_reset_postdata();\nendif;\n?>\n</div>\n</code></pre>\n"
}
] |
2016/12/30
|
[
"https://wordpress.stackexchange.com/questions/250797",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101046/"
] |
I have made a query which gives me 8 results. I need to show these in 2 columns of 4 items.
This is my query :
```
$args = array(
'post_type' => 'event',
'meta_key' => 'date',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'posts_per_page' => 8,
'meta_query' => array(
'key' => 'date',
'value' => date('Y-m-d',strtotime("today")),
'compare' => '>=',
'type' => 'DATE'
),
);
$events = new WP_Query( $args );
```
I tried using array\_splice. Example :
```
$firstCol = array_slice($events, 0, 4, true);
$secondCol = array_slice($events, 4, true);
```
But this does not seem to work. How can I get 2 arrays from my result?
|
There's no need to split the array, you can just close the first div once you've counted up to four elements of the array.
```
$args = array(
'post_type' => 'event',
'meta_key' => 'date',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'posts_per_page' => 8,
'meta_query' => array(
'key' => 'date',
'value' => date('Y-m-d',strtotime("today")),
'compare' => '>=',
'type' => 'DATE'
),
);
$events = new WP_Query( $args );
$count = 1;
if ( $events->have_posts() ) : ?>
<div class="column-1">
<?php while ( $events->have_posts() ) : $events->the_post();
// YOUR CONTENT
if ( $count == 4 ) { ?>
</div>
<div class="column-2">
<?php }
$count++;
endwhile;
wp_reset_postdata();
endif;
?>
</div>
```
|
250,810 |
<p>I downloaded a whole WP install and moved it to a LAMP test environment in order to update it. The original site could be found under example.com, the test site should be under example.com.mytestdomain.com aka {testurl}. In order to achieve that, I created a local DNS record and I changed the site url as well as the home url in the WP dashboard to reflect this test domain. </p>
<p>I can access {testurl}/wp-admin fine, and both the site address as well as the home address are set to {testurl}, and not example.com. </p>
<p>Yet, when I try to access {testurl}, I am always being forwarded to example.com. </p>
<p>I'd be grateful for hints why this could be happening. I have no redirect plugins, (internal) DNS is set up correctly. </p>
<p><strong>Update:</strong> In the end, it turned out I did not activate the mod_rewrite module in my httpd.conf which led to my permalinks being ignored on the test server. </p>
<p>After I corrected this mistake, I could correctly access {testurl}/postname but I was still being redirected to example.com when calling {testurl}. </p>
<p>As a next step, I directly called {testurl}/index.php. And this worked. And from that moment on, I can call {testurl} without being redirected. </p>
<p>Frankly, I'm not at all sure about how this last step solved the problem but it's gone now. </p>
|
[
{
"answer_id": 250814,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 0,
"selected": false,
"text": "<p>You should define both the <code>WP_SITEURL</code> and <code>WP_HOME</code> in your test wp-config.php file, don't forget to remove it when migrating back to the live server.</p>\n\n<pre><code>/**#@-*/\ndefine( 'WP_SITEURL', 'http://example.com.mytestdomain.com' );\ndefine( 'WP_HOME', 'http://example.com.mytestdomain.com' );\n</code></pre>\n"
},
{
"answer_id": 250880,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 2,
"selected": false,
"text": "<p>You may have some problem with JavaScript on your website, with the hardcoded URLs. As I can see you are trying to create the test environment.</p>\n<p>This is good, and I like people creating the test environments.\nYou need to go to through your code, JavaScript and PHP to seek for the hardcoded URLs.</p>\n<p>Also it is good to have the lines like this in your <code>wp-config.php</code>:</p>\n<pre><code>define( 'WP_SITEURL', 'http://example.com.mytestdomain.com' );\ndefine( 'WP_HOME', 'http://example.com.mytestdomain.com' );\n</code></pre>\n<hr />\n<p>I would suggest you do the database export something like</p>\n<pre><code>wp db export\n</code></pre>\n<p>If you use <code>wp-cli</code>\nand after that try to search the export to understand what you have in there. Let us know the feedback.</p>\n<p>Anyway, very interesting question.\nPlease feel free to accept this answer if you find it helpful.\nI think the approach explained in here is really general but you may find it helpful.</p>\n<hr />\n<p>From the web server configuration standpoint, try to create a simple index.php in a root of your WordPress that will print "You cannot redirect me!". Let me know the feedback if this will be redirected. ;)</p>\n<p>PS: Don't forget to backup the original WordPress's index.php.</p>\n<hr />\n<blockquote>\n<p>So, I think I have a better idea of what is happening. Although the site's address is set correctly to the test site, and even the pages show the correct test site permalinks, all posts still contain, hard coded in the DB, a reference to the original site. Since the site, after calling index.php, immediately opens post number 1, it is being redirected to the original site. Frankly, this is strange, I thought the purpose of the site url and home url is to prevent just that? I will now try changing wp-config.php to see if it has a different effect than setting homeurl and siteurl in the db</p>\n</blockquote>\n<p>You can do something like <a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">this</a> once:</p>\n<pre><code>update_option( 'siteurl', 'http://example.com.mytestdomain.com' );\nupdate_option( 'home', 'http://example.com.mytestdomain.com' );\n</code></pre>\n<p>After that check what you have in the database when you export it.</p>\n<h3>Also note, some menu links may be hardcoded in the database, in the options table.</h3>\n"
}
] |
2016/12/30
|
[
"https://wordpress.stackexchange.com/questions/250810",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109938/"
] |
I downloaded a whole WP install and moved it to a LAMP test environment in order to update it. The original site could be found under example.com, the test site should be under example.com.mytestdomain.com aka {testurl}. In order to achieve that, I created a local DNS record and I changed the site url as well as the home url in the WP dashboard to reflect this test domain.
I can access {testurl}/wp-admin fine, and both the site address as well as the home address are set to {testurl}, and not example.com.
Yet, when I try to access {testurl}, I am always being forwarded to example.com.
I'd be grateful for hints why this could be happening. I have no redirect plugins, (internal) DNS is set up correctly.
**Update:** In the end, it turned out I did not activate the mod\_rewrite module in my httpd.conf which led to my permalinks being ignored on the test server.
After I corrected this mistake, I could correctly access {testurl}/postname but I was still being redirected to example.com when calling {testurl}.
As a next step, I directly called {testurl}/index.php. And this worked. And from that moment on, I can call {testurl} without being redirected.
Frankly, I'm not at all sure about how this last step solved the problem but it's gone now.
|
You may have some problem with JavaScript on your website, with the hardcoded URLs. As I can see you are trying to create the test environment.
This is good, and I like people creating the test environments.
You need to go to through your code, JavaScript and PHP to seek for the hardcoded URLs.
Also it is good to have the lines like this in your `wp-config.php`:
```
define( 'WP_SITEURL', 'http://example.com.mytestdomain.com' );
define( 'WP_HOME', 'http://example.com.mytestdomain.com' );
```
---
I would suggest you do the database export something like
```
wp db export
```
If you use `wp-cli`
and after that try to search the export to understand what you have in there. Let us know the feedback.
Anyway, very interesting question.
Please feel free to accept this answer if you find it helpful.
I think the approach explained in here is really general but you may find it helpful.
---
From the web server configuration standpoint, try to create a simple index.php in a root of your WordPress that will print "You cannot redirect me!". Let me know the feedback if this will be redirected. ;)
PS: Don't forget to backup the original WordPress's index.php.
---
>
> So, I think I have a better idea of what is happening. Although the site's address is set correctly to the test site, and even the pages show the correct test site permalinks, all posts still contain, hard coded in the DB, a reference to the original site. Since the site, after calling index.php, immediately opens post number 1, it is being redirected to the original site. Frankly, this is strange, I thought the purpose of the site url and home url is to prevent just that? I will now try changing wp-config.php to see if it has a different effect than setting homeurl and siteurl in the db
>
>
>
You can do something like [this](https://codex.wordpress.org/Changing_The_Site_URL) once:
```
update_option( 'siteurl', 'http://example.com.mytestdomain.com' );
update_option( 'home', 'http://example.com.mytestdomain.com' );
```
After that check what you have in the database when you export it.
### Also note, some menu links may be hardcoded in the database, in the options table.
|
250,837 |
<p>I am trying to get <code>add_rewrite_rule</code> working to extract a param from url and pass it through to the request. Seen a number of posts about this, but can't seem to get it working.</p>
<p>If a url begins with a certain string, I would like to remove it from the url and pass it as a query params.</p>
<p>Example request url:</p>
<pre><code>http://domain.com/foo/my_page
</code></pre>
<p>This would get transformed to </p>
<pre><code>http://domain.com/my_page?param=foo
</code></pre>
<p>If 'foo' is not present, it should just go through as a normal request. This logic should apply to any page url or custom post type url on my site (basically foo/*). Thinking it would act as a pass thru, if the url has 'foo' strip it out and then just pass along to Wordpress to to it's normal thing.</p>
<p>I already have 'param' in as an allowed query_vars.</p>
<p>In total, it would need to work for the following:</p>
<blockquote>
<ul>
<li>/foo/my_page (Page)</li>
<li>/foo/my_folder/my_page (Sub-Page)</li>
<li>/foo/example_type (Custom Post Archive)</li>
<li>/foo/example_type/example_post (Custom Post Single)</li>
</ul>
</blockquote>
|
[
{
"answer_id": 250972,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 4,
"selected": false,
"text": "<p>A basic rule that would work for your example:</p>\n\n<pre><code>function wpd_foo_rewrite_rule() {\n add_rewrite_rule(\n '^foo/([^/]*)/?',\n 'index.php?pagename=$matches[1]&param=foo',\n 'top'\n );\n}\nadd_action( 'init', 'wpd_foo_rewrite_rule' );\n</code></pre>\n\n<p>This takes whatever comes after <code>foo/</code> and sets that as <code>pagename</code> for the query, and then <code>param</code> gets the static value <code>foo</code>. If you need different URL patterns, you'll need extra rules for each unique pattern. Refer to <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\"><code>WP_Query</code> docs</a> for the various query vars that can be set within rewrite rules. Don't forget to flush rewrite rules after adding new ones. This can be done by visiting the Permalinks Settings page.</p>\n\n<p>Now visiting your example URL:</p>\n\n<pre><code>http://domain.com/foo/my_page\n</code></pre>\n\n<p>will load the correct page, but it's not going to behave exactly like visiting:</p>\n\n<pre><code>http://domain.com/my_page?param=foo\n</code></pre>\n\n<p>because when using internal rewrites, <code>param</code> is set within the <code>$wp_query</code> query object, not the <code>$_GET</code> superglobal. If you need to work with code that's looking for a value in <code>$_GET</code>, you'll need an extra step to set that value:</p>\n\n<pre><code>function wpd_foo_get_param() {\n if( false !== get_query_var( 'param' ) ){\n $_GET['param'] = get_query_var( 'param' );\n }\n}\nadd_action( 'parse_query', 'wpd_foo_get_param' );\n</code></pre>\n\n<p>Another method to consider is using endpoints, so <code>/foo/</code> would be on the end of URLs rather than as a prefix. The advantage to this is that the API's <code>add_rewrite_endpoint</code> simplifies adding all of the rules you need, including enabling pagination.</p>\n"
},
{
"answer_id": 251422,
"author": "Louis W",
"author_id": 8642,
"author_profile": "https://wordpress.stackexchange.com/users/8642",
"pm_score": 4,
"selected": true,
"text": "<p>Ok, I've gotten working examples for all 3 types of requests. It took a ton of experimenting and messing around in order to get them working. I guess Milo is good at nudging people into answering their own questions. </p>\n\n<p>After countless changes and refreshing the permalinks I realized it was much easier to figure out the urls outside of the add_rewrite_url and once they worked then define the rewrite. Example being <code>index.php?param=foo&post_type=example_type</code>. </p>\n\n<p>Another obvious thing, but adding it here so it might help someone else. You must define the custom post type add_rewrite_rule rules BEFORE you define your page/sub-page wildcard rules. I wasted quite a bit of time with that one and think it's the main thing that was causing me to not understand why the rules didn't work.</p>\n\n<p>Here are the 3 rules which work across all my needs. The Page/Sub-Page rule was combined into a single one.</p>\n\n<pre><code>// Custom Post Archive\nadd_rewrite_rule(\n '^foo/example_type/?$',\n 'index.php?param=foo&post_type=example_type',\n 'top'\n );\n\n// Custom Post Individual\nadd_rewrite_rule(\n '^foo/example_type/([^/]*)/?$',\n 'index.php?param=foo&example_type=$matches[1]',\n 'top'\n );\n\n// Pages, Top-Level and Sub-Pages\n// This MUST be placed in the code AFTER custom post add_rewrite_rule\nadd_rewrite_rule(\n '^foo/(.+)/?$', \n 'index.php?param=foo&pagename=$matches[1]',\n 'top'\n );\n</code></pre>\n\n<p>Additionally what I've done is set up a loop to add multiple custom post type rules. Remember, you must define the custom post type add_rewrite_rule rules BEFORE you define your page/sub-page wildcard rules.</p>\n\n<pre><code>$custom_types = array('example_type', 'projects', 'people');\n\nforeach($custom_types as $type) {\n\n // Custom Post Archive\n add_rewrite_rule(\n '^foo/'.$type.'/?$',\n 'index.php?param=foo&post_type='.$type,\n 'top'\n );\n\n // Custom Post Individual\n add_rewrite_rule(\n '^foo/'.$type.'/([^/]*)/?$',\n 'index.php?param=foo&'.$type.'=$matches[1]',\n 'top'\n );\n\n}\n</code></pre>\n\n<p>The <a href=\"https://wordpress.org/plugins-wp/monkeyman-rewrite-analyzer/\" rel=\"noreferrer\">Rewrite Analyzer</a> which Milo passed along was quite helpful when trying to better understand how Wordpress queries for pages/posts.</p>\n"
}
] |
2016/12/30
|
[
"https://wordpress.stackexchange.com/questions/250837",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8642/"
] |
I am trying to get `add_rewrite_rule` working to extract a param from url and pass it through to the request. Seen a number of posts about this, but can't seem to get it working.
If a url begins with a certain string, I would like to remove it from the url and pass it as a query params.
Example request url:
```
http://domain.com/foo/my_page
```
This would get transformed to
```
http://domain.com/my_page?param=foo
```
If 'foo' is not present, it should just go through as a normal request. This logic should apply to any page url or custom post type url on my site (basically foo/\*). Thinking it would act as a pass thru, if the url has 'foo' strip it out and then just pass along to Wordpress to to it's normal thing.
I already have 'param' in as an allowed query\_vars.
In total, it would need to work for the following:
>
> * /foo/my\_page (Page)
> * /foo/my\_folder/my\_page (Sub-Page)
> * /foo/example\_type (Custom Post Archive)
> * /foo/example\_type/example\_post (Custom Post Single)
>
>
>
|
Ok, I've gotten working examples for all 3 types of requests. It took a ton of experimenting and messing around in order to get them working. I guess Milo is good at nudging people into answering their own questions.
After countless changes and refreshing the permalinks I realized it was much easier to figure out the urls outside of the add\_rewrite\_url and once they worked then define the rewrite. Example being `index.php?param=foo&post_type=example_type`.
Another obvious thing, but adding it here so it might help someone else. You must define the custom post type add\_rewrite\_rule rules BEFORE you define your page/sub-page wildcard rules. I wasted quite a bit of time with that one and think it's the main thing that was causing me to not understand why the rules didn't work.
Here are the 3 rules which work across all my needs. The Page/Sub-Page rule was combined into a single one.
```
// Custom Post Archive
add_rewrite_rule(
'^foo/example_type/?$',
'index.php?param=foo&post_type=example_type',
'top'
);
// Custom Post Individual
add_rewrite_rule(
'^foo/example_type/([^/]*)/?$',
'index.php?param=foo&example_type=$matches[1]',
'top'
);
// Pages, Top-Level and Sub-Pages
// This MUST be placed in the code AFTER custom post add_rewrite_rule
add_rewrite_rule(
'^foo/(.+)/?$',
'index.php?param=foo&pagename=$matches[1]',
'top'
);
```
Additionally what I've done is set up a loop to add multiple custom post type rules. Remember, you must define the custom post type add\_rewrite\_rule rules BEFORE you define your page/sub-page wildcard rules.
```
$custom_types = array('example_type', 'projects', 'people');
foreach($custom_types as $type) {
// Custom Post Archive
add_rewrite_rule(
'^foo/'.$type.'/?$',
'index.php?param=foo&post_type='.$type,
'top'
);
// Custom Post Individual
add_rewrite_rule(
'^foo/'.$type.'/([^/]*)/?$',
'index.php?param=foo&'.$type.'=$matches[1]',
'top'
);
}
```
The [Rewrite Analyzer](https://wordpress.org/plugins-wp/monkeyman-rewrite-analyzer/) which Milo passed along was quite helpful when trying to better understand how Wordpress queries for pages/posts.
|
250,861 |
<p>i create a custom page to display loop of cpt with custom field. </p>
<p>I need to add a numberic pagination and i try with this code but not work.</p>
<p><strong>Functions.php</strong></p>
<pre><code>function pagination_bar() {
global $wp_query;
$total_pages = $wp_query->max_num_pages;
if ($total_pages > 1){
$current_page = max(1, get_query_var('paged'));
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '/page/%#%',
'current' => $current_page,
'total' => $total_pages,
));
}
}
</code></pre>
<p><strong>custompage.php</strong></p>
<pre><code><!--Loop Salmi-->
<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$loop = new WP_Query( array( 'post_type' => 'salmi',
'posts_per_page' => 15,
'paged' => $paged )
);
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<!--Colonne Contenuto -->
<div class="salmicpt">
<div class="wpb_column vc_column_container td-pb-span8">
<div class="titlecpt"><?php the_title(); ?></div>
</div>
<div class="wpb_column vc_column_container td-pb-span4">
<?php if( get_field('audio_salmi') ): ?>
<a href="<?php the_field('audio_salmi'); ?>" ><img src="mysite.com/wp-content/uploads/cuffia-cpt-e1481533293805.png" alt="Ascolta" title="Ascolta" /></a>
<?php endif; ?>
<?php if( get_field('salmi_pdf') ): ?>
<a href="<?php the_field('salmi_pdf'); ?>" ><img src="mysite.com/wp-content/uploads/freccia-32.png" alt="Scarica il PDf" title="Scarica il PDF" /></a>
<?php endif; ?>
</div>
<div style='clear:both'></div><hr class="style-one" />
</div>
<nav class="pagination">
<?php pagination_bar(); ?>
</nav>
<?php endwhile; wp_reset_query(); ?>
</code></pre>
<p>Where is wrong?? Thanks</p>
|
[
{
"answer_id": 250866,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 4,
"selected": true,
"text": "<p>You're referencing the <strong><code>global $wp_query</code></strong> object in your function which you've reset using <strong><code>wp_reset_query()</code></strong>. </p>\n\n<p>You can resolve the pagination by passing your custom <strong><code>$loop</code></strong> WP_Query object to the function. I also changed <strong><code>wp_reset_query</code></strong> to <strong><code>wp_reset_postdata</code></strong></p>\n\n<p>Also you're making the call to your pagination function in the <strong>while loop</strong> instead of after it.</p>\n\n<p><strong>Your function should be updated to:</strong></p>\n\n<pre><code>function pagination_bar( $custom_query ) {\n\n $total_pages = $custom_query->max_num_pages;\n $big = 999999999; // need an unlikely integer\n\n if ($total_pages > 1){\n $current_page = max(1, get_query_var('paged'));\n\n echo paginate_links(array(\n 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '?paged=%#%',\n 'current' => $current_page,\n 'total' => $total_pages,\n ));\n }\n}\n</code></pre>\n\n<p>and in your <strong>custompage.php</strong> file:</p>\n\n<pre><code><!--Loop Salmi-->\n<?php\n$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;\n$loop = new WP_Query( array( 'post_type' => 'salmi',\n 'posts_per_page' => 15,\n 'paged' => $paged )\n);\nif ( $loop->have_posts() ):\n while ( $loop->have_posts() ) : $loop->the_post(); ?>\n\n <!--Colonne Contenuto -->\n <div class=\"salmicpt\">\n <div class=\"wpb_column vc_column_container td-pb-span8\">\n <div class=\"titlecpt\"><?php the_title(); ?></div>\n </div>\n <div class=\"wpb_column vc_column_container td-pb-span4\">\n <?php if( get_field('audio_salmi') ): ?>\n <a href=\"<?php the_field('audio_salmi'); ?>\" ><img src=\"mysite.com/wp-content/uploads/cuffia-cpt-e1481533293805.png\" alt=\"Ascolta\" title=\"Ascolta\" /></a>\n <?php endif; ?>\n <?php if( get_field('salmi_pdf') ): ?>\n <a href=\"<?php the_field('salmi_pdf'); ?>\" ><img src=\"mysite.com/wp-content/uploads/freccia-32.png\" alt=\"Scarica il PDf\" title=\"Scarica il PDF\" /></a>\n <?php endif; ?>\n </div>\n <div style='clear:both'></div><hr class=\"style-one\" />\n </div>\n <?php endwhile; ?>\n <nav class=\"pagination\">\n <?php pagination_bar( $loop ); ?>\n </nav>\n<?php wp_reset_postdata();\nendif;\n</code></pre>\n"
},
{
"answer_id": 298905,
"author": "NikHiL Gadhiya",
"author_id": 136899,
"author_profile": "https://wordpress.stackexchange.com/users/136899",
"pm_score": 0,
"selected": false,
"text": "<p><strong>copy and pest in your function file</strong></p>\n\n<pre><code>function pagination_bar( $query_wp ) \n{\n $pages = $query_wp->max_num_pages;\n $big = 999999999; // need an unlikely integer\n if ($pages > 1)\n {\n $page_current = max(1, get_query_var('paged'));\n echo paginate_links(array(\n 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '?paged=%#%',\n 'current' => $page_current,\n 'total' => $pages,\n ));\n }\n}\n</code></pre>\n\n<p>**copy and pest code in your custompage.php file **</p>\n\n<pre><code><?php\n$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;\n$args = array('post_type'=>'salmi','posts_per_page' => 15,'paged' => $paged);\n$the_query = new WP_Query($args);\nif ( $the_query->have_posts() ):\n while ( $the_query->have_posts() ) : $the_query->the_post(); ?> \n <!--Colonne Contenuto -->\n <div class=\"salmicpt\">\n <div class=\"wpb_column vc_column_container td-pb-span8\">\n <div class=\"titlecpt\"><?php the_title(); ?></div>\n </div>\n <div class=\"wpb_column vc_column_container td-pb-span4\">\n <?php if( get_field('audio_salmi') ): ?>\n <a href=\"<?php the_field('audio_salmi'); ?>\" >\n <img src=\"mysite.com/wp-content/uploads/cuffia-cpt-e1481533293805.png\" alt=\"Ascolta\" title=\"Ascolta\" />\n </a>\n <?php endif; ?>\n <?php if( get_field('salmi_pdf') ): ?>\n <a href=\"<?php the_field('salmi_pdf'); ?>\" >\n <img src=\"mysite.com/wp-content/uploads/freccia-32.png\" alt=\"Scarica il PDf\" title=\"Scarica il PDF\" />\n </a>\n <?php endif; ?>\n </div>\n <div style='clear:both'></div><hr class=\"style-one\" />\n </div>\n <?php endwhile; ?>\n <nav class=\"pagination\">\n <?php pagination_bar( $the_query ); ?>\n </nav>\n<?php wp_reset_postdata();\nendif;\n</code></pre>\n"
},
{
"answer_id": 371951,
"author": "kaustubh chaudhari",
"author_id": 192359,
"author_profile": "https://wordpress.stackexchange.com/users/192359",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Make following changes in custompage.php file</strong></p>\n<pre><code><?php\n$paged = ( get_query_var( 'page' ) ) ? get_query_var( 'page' ) : 1;\n$args = array('post_type'=>'salmi','posts_per_page' => 15,'paged' => $paged);\n$the_query = new WP_Query($args);\nif ( $the_query->have_posts() ):\n while ( $the_query->have_posts() ) : $the_query->the_post(); ?> \n <!--Colonne Contenuto -->\n <div class="salmicpt">\n <div class="wpb_column vc_column_container td-pb-span8">\n <div class="titlecpt"><?php the_title(); ?></div>\n </div>\n <div class="wpb_column vc_column_container td-pb-span4">\n <?php if( get_field('audio_salmi') ): ?>\n <a href="<?php the_field('audio_salmi'); ?>" >\n <img src="mysite.com/wp-content/uploads/cuffia-cpt-e1481533293805.png" alt="Ascolta" title="Ascolta" />\n </a>\n <?php endif; ?>\n <?php if( get_field('salmi_pdf') ): ?>\n <a href="<?php the_field('salmi_pdf'); ?>" >\n <img src="mysite.com/wp-content/uploads/freccia-32.png" alt="Scarica il PDf" title="Scarica il PDF" />\n </a>\n <?php endif; ?>\n </div>\n <div style='clear:both'></div><hr class="style-one" />\n </div>\n <?php endwhile; ?>\n <nav class="pagination">\n <?php pagination_bar( $the_query ); ?>\n </nav>\n<?php wp_reset_postdata();\nendif;\n</div>\n</code></pre>\n<p><strong>And in functions.php</strong></p>\n<pre><code>function pagination_bar( $query_wp ) \n{\n$pages = $query_wp->max_num_pages;\n$big = 999999999; // need an unlikely integer\nif ($pages > 1)\n{\n $page_current = max(1, get_query_var('page'));\n echo paginate_links(array(\n 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '?paged=%#%',\n 'current' => $page_current,\n 'total' => $pages,\n ));\n}\n}\n</code></pre>\n<p><strong>This works perfectly</strong></p>\n"
}
] |
2016/12/31
|
[
"https://wordpress.stackexchange.com/questions/250861",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51160/"
] |
i create a custom page to display loop of cpt with custom field.
I need to add a numberic pagination and i try with this code but not work.
**Functions.php**
```
function pagination_bar() {
global $wp_query;
$total_pages = $wp_query->max_num_pages;
if ($total_pages > 1){
$current_page = max(1, get_query_var('paged'));
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '/page/%#%',
'current' => $current_page,
'total' => $total_pages,
));
}
}
```
**custompage.php**
```
<!--Loop Salmi-->
<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$loop = new WP_Query( array( 'post_type' => 'salmi',
'posts_per_page' => 15,
'paged' => $paged )
);
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<!--Colonne Contenuto -->
<div class="salmicpt">
<div class="wpb_column vc_column_container td-pb-span8">
<div class="titlecpt"><?php the_title(); ?></div>
</div>
<div class="wpb_column vc_column_container td-pb-span4">
<?php if( get_field('audio_salmi') ): ?>
<a href="<?php the_field('audio_salmi'); ?>" ><img src="mysite.com/wp-content/uploads/cuffia-cpt-e1481533293805.png" alt="Ascolta" title="Ascolta" /></a>
<?php endif; ?>
<?php if( get_field('salmi_pdf') ): ?>
<a href="<?php the_field('salmi_pdf'); ?>" ><img src="mysite.com/wp-content/uploads/freccia-32.png" alt="Scarica il PDf" title="Scarica il PDF" /></a>
<?php endif; ?>
</div>
<div style='clear:both'></div><hr class="style-one" />
</div>
<nav class="pagination">
<?php pagination_bar(); ?>
</nav>
<?php endwhile; wp_reset_query(); ?>
```
Where is wrong?? Thanks
|
You're referencing the **`global $wp_query`** object in your function which you've reset using **`wp_reset_query()`**.
You can resolve the pagination by passing your custom **`$loop`** WP\_Query object to the function. I also changed **`wp_reset_query`** to **`wp_reset_postdata`**
Also you're making the call to your pagination function in the **while loop** instead of after it.
**Your function should be updated to:**
```
function pagination_bar( $custom_query ) {
$total_pages = $custom_query->max_num_pages;
$big = 999999999; // need an unlikely integer
if ($total_pages > 1){
$current_page = max(1, get_query_var('paged'));
echo paginate_links(array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => $current_page,
'total' => $total_pages,
));
}
}
```
and in your **custompage.php** file:
```
<!--Loop Salmi-->
<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$loop = new WP_Query( array( 'post_type' => 'salmi',
'posts_per_page' => 15,
'paged' => $paged )
);
if ( $loop->have_posts() ):
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<!--Colonne Contenuto -->
<div class="salmicpt">
<div class="wpb_column vc_column_container td-pb-span8">
<div class="titlecpt"><?php the_title(); ?></div>
</div>
<div class="wpb_column vc_column_container td-pb-span4">
<?php if( get_field('audio_salmi') ): ?>
<a href="<?php the_field('audio_salmi'); ?>" ><img src="mysite.com/wp-content/uploads/cuffia-cpt-e1481533293805.png" alt="Ascolta" title="Ascolta" /></a>
<?php endif; ?>
<?php if( get_field('salmi_pdf') ): ?>
<a href="<?php the_field('salmi_pdf'); ?>" ><img src="mysite.com/wp-content/uploads/freccia-32.png" alt="Scarica il PDf" title="Scarica il PDF" /></a>
<?php endif; ?>
</div>
<div style='clear:both'></div><hr class="style-one" />
</div>
<?php endwhile; ?>
<nav class="pagination">
<?php pagination_bar( $loop ); ?>
</nav>
<?php wp_reset_postdata();
endif;
```
|
250,871 |
<p>Trying to populate a drop down element of a html form in a word press page with data from SQL query in a php file in a php directory: <code>site/php/</code>.</p>
<p><strong>Php code is working fine:</strong></p>
<hr>
<pre><code><?php
require_once "connectPDO.php";
define('WP_USE_THEMES', false);
require('../wp-load.php');
require_once('../wp-config.php');
require_once('../wp-includes/wp-db.php');
require_once('../wp-includes/pluggable.php');
require('../wp-blog-header.php');
if ( is_user_logged_in() ) {
global $current_user;
get_currentuserinfo();
$user = $current_user->ID;
} else {
echo '<a href="'. get_bloginfo('url') .'/wp-admin" class="loginlinktop">Login</a>';
}
global $wpdb;
$results = $wpdb->get_results("SELECT my-column FROM wp_table WHERE user_id = ."'$user'".");
if($results){
foreach($results as $value){
echo serialize ($value);
}
}
?>
</code></pre>
<hr>
<p>In a wordpress page I use execPHP plugin and this instruction:</p>
<pre><code><?php require_once(ABSPATH. '/php/phpfile.php'); ?>
</code></pre>
<p>I just get a blank page.
1 How can I get the result on word press?</p>
<p>2 A code sample to populate drop down from a serialized array?</p>
<p>Thanks. I've been more than a week with this.</p>
|
[
{
"answer_id": 250876,
"author": "Vitzkrieg",
"author_id": 109973,
"author_profile": "https://wordpress.stackexchange.com/users/109973",
"pm_score": 0,
"selected": false,
"text": "<p>I would first check that <code>$value</code> is not null. Also, would it make more sense to call <code>unserialize($value);</code> here since you are pulling the data out of the database and not storing it?</p>\n\n<p>Code sample for populating dropdown:</p>\n\n<pre><code><select class=\"dropdown\" id=\"mydropdown\" name=\"mydropdown\" title=\"My Dropdown\">\n <?php\n foreach ($results as $value) {\n echo '<option value=\"' . unserialize($value) . '\">' . unserialize($value) . '</option>';\n }\n ?>\n</select>\n</code></pre>\n"
},
{
"answer_id": 251595,
"author": "Joan Pescador",
"author_id": 109971,
"author_profile": "https://wordpress.stackexchange.com/users/109971",
"pm_score": 2,
"selected": true,
"text": "<p>Thanks everybody for your answers. You bring me value clues.\nFinally I opted to make the query directly from wordpress page with the wordpress sintax for the defaults wordpress tables, using a little trick:\nIncluding my custom tables in wp-includes/wp-db.php.</p>\n\n<p>wordpress code:</p>\n\n<pre><code><?php\nglobal $current_user;\nget_currentuserinfo();\n$user = $current_user->ID;\nglobal $wpdb;\nglobal $result;\n$courses = array();\n$result = $wpdb->get_results ( \"SELECT * FROM $wpdb->mytable WHERE user_id = $user\" );\n?>\nname\n<select>\n <option selected=\"selected\">name</option>\n <?php\n foreach( $result as $value ) { ?>\n <option value=\"<?php echo $value->name; ?>\"><?php echo $value->name; ?></option>\n <?php\n }\n?>\n</select>\n</code></pre>\n"
}
] |
2016/12/31
|
[
"https://wordpress.stackexchange.com/questions/250871",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109971/"
] |
Trying to populate a drop down element of a html form in a word press page with data from SQL query in a php file in a php directory: `site/php/`.
**Php code is working fine:**
---
```
<?php
require_once "connectPDO.php";
define('WP_USE_THEMES', false);
require('../wp-load.php');
require_once('../wp-config.php');
require_once('../wp-includes/wp-db.php');
require_once('../wp-includes/pluggable.php');
require('../wp-blog-header.php');
if ( is_user_logged_in() ) {
global $current_user;
get_currentuserinfo();
$user = $current_user->ID;
} else {
echo '<a href="'. get_bloginfo('url') .'/wp-admin" class="loginlinktop">Login</a>';
}
global $wpdb;
$results = $wpdb->get_results("SELECT my-column FROM wp_table WHERE user_id = ."'$user'".");
if($results){
foreach($results as $value){
echo serialize ($value);
}
}
?>
```
---
In a wordpress page I use execPHP plugin and this instruction:
```
<?php require_once(ABSPATH. '/php/phpfile.php'); ?>
```
I just get a blank page.
1 How can I get the result on word press?
2 A code sample to populate drop down from a serialized array?
Thanks. I've been more than a week with this.
|
Thanks everybody for your answers. You bring me value clues.
Finally I opted to make the query directly from wordpress page with the wordpress sintax for the defaults wordpress tables, using a little trick:
Including my custom tables in wp-includes/wp-db.php.
wordpress code:
```
<?php
global $current_user;
get_currentuserinfo();
$user = $current_user->ID;
global $wpdb;
global $result;
$courses = array();
$result = $wpdb->get_results ( "SELECT * FROM $wpdb->mytable WHERE user_id = $user" );
?>
name
<select>
<option selected="selected">name</option>
<?php
foreach( $result as $value ) { ?>
<option value="<?php echo $value->name; ?>"><?php echo $value->name; ?></option>
<?php
}
?>
</select>
```
|
250,879 |
<p>I have a small bit of hourly-changing css and I want to</p>
<ol>
<li><p>keep it in a second file (apart from style.css) and </p></li>
<li><p>load it <em>after</em> my theme's <code>style.css</code> file.</p></li>
</ol>
<p>I believe I can make it load before <code>style.css</code> by setting its priority to the <code>style.css</code> minus one (e.g. if the main style.css has a priority of 10, my bit of code would have a priority of 9). </p>
<p>But here's my problem: apart from trial and error I don't know how to identify, programmatically the priority of a style sheet. I know could simple use the method of halving to hone in on the value, but I'd rather not do that. It would be nice to learn a principled way of solving this problem. Perhaps there is a default priority of main-theme CSS file? If this is the case I can easily try the ($defaultPriorityValue - 1). Is this possible, and if not what is a good way to do this?</p>
<p><em>p.s. I do not want to enqueue inline styles in my <code>functions.php</code> because I need to keep this code in a separate file</em> </p>
<p>Although I found the functional solution I listed in the answers below, I would still like it if someone could explain if there is a way to id, programmatically, the priority of a sheet. Thanks!</p>
|
[
{
"answer_id": 250881,
"author": "CoderScissorhands",
"author_id": 105196,
"author_profile": "https://wordpress.stackexchange.com/users/105196",
"pm_score": 0,
"selected": false,
"text": "<h2>The Dependency Solution</h2>\n<p>One functional solution I found and successfully tested came from @helgatheviking's answer to <a href=\"https://wordpress.stackexchange.com/questions/115637/how-can-i-make-new-css-file-in-child-theme-override-styles-in-child-themes-sty?noredirect=1&lq=1\">this question</a>. This solution involves setting a dependency on small CSS file (which is a third argument) when enqueuing it. You set the small CSS file's dependency to the handle/id of the main CSS file.</p>\n<pre><code> wp_enqueue_style(\n 'my-little-css-style',\n get_stylesheet_directory_uri() . '/my_little_style.css',\n 'themename-style' // this is the dependency, which I set to the handle of the main css stylesheet. It makes the small sheet load before the main one. \n );\n</code></pre>\n"
},
{
"answer_id": 250889,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": true,
"text": "<p>When you properly enqueue a file, an instance of the <a href=\"https://developer.wordpress.org/reference/classes/wp_styles/\" rel=\"nofollow noreferrer\"><code>wp_styles</code></a> (<a href=\"https://codex.wordpress.org/Class_Reference/WP_Styles\" rel=\"nofollow noreferrer\">more on this</a>) class is created. The priority of actions is ignored. So it doesn't matter if you write anything like</p>\n\n<pre><code>add_action ('wp_enqueue_scripts','function_adding_main_style',10);\nadd_action ('wp_enqueue_scripts','function_adding_small_style',11);\n</code></pre>\n\n<p>The reason is exactly the existence of the dependency system. WP first collects all enqueued style files and then checks them for dependencies. If <code>A.css</code> is enqueued before <code>B.css</code> but the former depends on the latter, they will be loaded accordingly. You can see this reordening happen in the <code>all_deps</code> method of the <a href=\"https://developer.wordpress.org/reference/classes/wp_dependencies/\" rel=\"nofollow noreferrer\">parent class</a>.</p>\n\n<p>To cut a long story short: you're not supposed to mess with the priority of style files outside the dependency system that WP gives you. Your own solution is the best.</p>\n\n<p>That said, you can always circumvent the enqueueing system and echo your file directly towards the end of the <code>wp_head</code> hook. Unelegant, but effective.</p>\n"
}
] |
2016/12/31
|
[
"https://wordpress.stackexchange.com/questions/250879",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105196/"
] |
I have a small bit of hourly-changing css and I want to
1. keep it in a second file (apart from style.css) and
2. load it *after* my theme's `style.css` file.
I believe I can make it load before `style.css` by setting its priority to the `style.css` minus one (e.g. if the main style.css has a priority of 10, my bit of code would have a priority of 9).
But here's my problem: apart from trial and error I don't know how to identify, programmatically the priority of a style sheet. I know could simple use the method of halving to hone in on the value, but I'd rather not do that. It would be nice to learn a principled way of solving this problem. Perhaps there is a default priority of main-theme CSS file? If this is the case I can easily try the ($defaultPriorityValue - 1). Is this possible, and if not what is a good way to do this?
*p.s. I do not want to enqueue inline styles in my `functions.php` because I need to keep this code in a separate file*
Although I found the functional solution I listed in the answers below, I would still like it if someone could explain if there is a way to id, programmatically, the priority of a sheet. Thanks!
|
When you properly enqueue a file, an instance of the [`wp_styles`](https://developer.wordpress.org/reference/classes/wp_styles/) ([more on this](https://codex.wordpress.org/Class_Reference/WP_Styles)) class is created. The priority of actions is ignored. So it doesn't matter if you write anything like
```
add_action ('wp_enqueue_scripts','function_adding_main_style',10);
add_action ('wp_enqueue_scripts','function_adding_small_style',11);
```
The reason is exactly the existence of the dependency system. WP first collects all enqueued style files and then checks them for dependencies. If `A.css` is enqueued before `B.css` but the former depends on the latter, they will be loaded accordingly. You can see this reordening happen in the `all_deps` method of the [parent class](https://developer.wordpress.org/reference/classes/wp_dependencies/).
To cut a long story short: you're not supposed to mess with the priority of style files outside the dependency system that WP gives you. Your own solution is the best.
That said, you can always circumvent the enqueueing system and echo your file directly towards the end of the `wp_head` hook. Unelegant, but effective.
|
250,883 |
<p>Does anybody know how to exclude pingbacks from this query? I tried to add <code>AND post_type = 'comment'</code> after <code>AND post_password = ''</code> but this didn't work.</p>
<pre><code>$query = "select
wp_posts.*,
coalesce((
select
max(comment_date)
from
$wpdb->comments wpc
where
wpc.comment_post_id = wp_posts.id
AND comment_approved = 1
AND post_password = ''
),
wp_posts.post_date ) as mcomment_date
from
$wpdb->posts wp_posts
where
post_type = 'post'
and post_status = 'publish'
and comment_count > '0'
order by
mcomment_date desc limit $limit";
</code></pre>
<p>Happy New Year! Even if you might not know the answer ;-)</p>
|
[
{
"answer_id": 250887,
"author": "iguanarama",
"author_id": 109807,
"author_profile": "https://wordpress.stackexchange.com/users/109807",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"https://codex.wordpress.org/Database_Description#Table:_wp_comments\" rel=\"nofollow noreferrer\">wp_comments table</a> has a field 'comment_type' which indicates pingback etc. So while my SQL knowledge is not great, I think you just need one extra line in your query where you're selecting from the comments table:</p>\n\n<pre><code>[...]\nwhere\n wpc.comment_post_id = wp_posts.id\n AND wpc.comment_type != 'pingback'\n [...]\n</code></pre>\n"
},
{
"answer_id": 250894,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": true,
"text": "<p>You can achieve this by excluding <code>pingback</code> from the <code>comment_type</code> column of wordpress <a href=\"https://codex.wordpress.org/Database_Description#Table:_wp_comments\" rel=\"nofollow noreferrer\"><strong>comments table</strong></a></p>\n\n<pre><code>$query = \"select\n wp_posts.*,\n coalesce((\n select\n max(comment_date)\n from\n $wpdb->comments wpc\n where\n wpc.comment_post_id = wp_posts.id\n AND comment_approved = 1\n AND post_password = ''\n AND comment_type NOT IN ( 'pingback' )\n ),\n wp_posts.post_date ) as mcomment_date\n from\n $wpdb->posts wp_posts\n where\n post_type = 'post'\n and post_status = 'publish'\n and comment_count > '0'\n order by\n mcomment_date desc limit $limit\";\n</code></pre>\n"
}
] |
2016/12/31
|
[
"https://wordpress.stackexchange.com/questions/250883",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33797/"
] |
Does anybody know how to exclude pingbacks from this query? I tried to add `AND post_type = 'comment'` after `AND post_password = ''` but this didn't work.
```
$query = "select
wp_posts.*,
coalesce((
select
max(comment_date)
from
$wpdb->comments wpc
where
wpc.comment_post_id = wp_posts.id
AND comment_approved = 1
AND post_password = ''
),
wp_posts.post_date ) as mcomment_date
from
$wpdb->posts wp_posts
where
post_type = 'post'
and post_status = 'publish'
and comment_count > '0'
order by
mcomment_date desc limit $limit";
```
Happy New Year! Even if you might not know the answer ;-)
|
You can achieve this by excluding `pingback` from the `comment_type` column of wordpress [**comments table**](https://codex.wordpress.org/Database_Description#Table:_wp_comments)
```
$query = "select
wp_posts.*,
coalesce((
select
max(comment_date)
from
$wpdb->comments wpc
where
wpc.comment_post_id = wp_posts.id
AND comment_approved = 1
AND post_password = ''
AND comment_type NOT IN ( 'pingback' )
),
wp_posts.post_date ) as mcomment_date
from
$wpdb->posts wp_posts
where
post_type = 'post'
and post_status = 'publish'
and comment_count > '0'
order by
mcomment_date desc limit $limit";
```
|
250,931 |
<p>I am still a bit new to wordpress development and I am facing a issue that I cant figure out.</p>
<p>My wordpress website theme uses the following code to display 3 categorys that show a image, category name and a link.</p>
<pre><code><?php echo do_shortcode('[product_categories number="' . $number . '" parent="0" columns="3"]'); ?>
</code></pre>
<p>This code outputs in:</p>
<pre><code><div class="woocommerce columns-3">
<ul class="products">
<li class="product-category product first"><a href="#">Cat1</a><li>
<li class="product-category product"><a href="#">Cat2</a><li>
<li class="product-category product last"><a href="#">Cat2</a></li>
</ul>
</div>
</code></pre>
<p>My question is where can I find the code that outputs the html? I want to add a href before the li instead of after it. Because now it only links to the category page when you click on the word but I want it to link when you also click anywhere on the image.</p>
<p>I've looked in the short_code.php file but it was really hard to follow the code to find where it get's outputted.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 250887,
"author": "iguanarama",
"author_id": 109807,
"author_profile": "https://wordpress.stackexchange.com/users/109807",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"https://codex.wordpress.org/Database_Description#Table:_wp_comments\" rel=\"nofollow noreferrer\">wp_comments table</a> has a field 'comment_type' which indicates pingback etc. So while my SQL knowledge is not great, I think you just need one extra line in your query where you're selecting from the comments table:</p>\n\n<pre><code>[...]\nwhere\n wpc.comment_post_id = wp_posts.id\n AND wpc.comment_type != 'pingback'\n [...]\n</code></pre>\n"
},
{
"answer_id": 250894,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": true,
"text": "<p>You can achieve this by excluding <code>pingback</code> from the <code>comment_type</code> column of wordpress <a href=\"https://codex.wordpress.org/Database_Description#Table:_wp_comments\" rel=\"nofollow noreferrer\"><strong>comments table</strong></a></p>\n\n<pre><code>$query = \"select\n wp_posts.*,\n coalesce((\n select\n max(comment_date)\n from\n $wpdb->comments wpc\n where\n wpc.comment_post_id = wp_posts.id\n AND comment_approved = 1\n AND post_password = ''\n AND comment_type NOT IN ( 'pingback' )\n ),\n wp_posts.post_date ) as mcomment_date\n from\n $wpdb->posts wp_posts\n where\n post_type = 'post'\n and post_status = 'publish'\n and comment_count > '0'\n order by\n mcomment_date desc limit $limit\";\n</code></pre>\n"
}
] |
2017/01/01
|
[
"https://wordpress.stackexchange.com/questions/250931",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110017/"
] |
I am still a bit new to wordpress development and I am facing a issue that I cant figure out.
My wordpress website theme uses the following code to display 3 categorys that show a image, category name and a link.
```
<?php echo do_shortcode('[product_categories number="' . $number . '" parent="0" columns="3"]'); ?>
```
This code outputs in:
```
<div class="woocommerce columns-3">
<ul class="products">
<li class="product-category product first"><a href="#">Cat1</a><li>
<li class="product-category product"><a href="#">Cat2</a><li>
<li class="product-category product last"><a href="#">Cat2</a></li>
</ul>
</div>
```
My question is where can I find the code that outputs the html? I want to add a href before the li instead of after it. Because now it only links to the category page when you click on the word but I want it to link when you also click anywhere on the image.
I've looked in the short\_code.php file but it was really hard to follow the code to find where it get's outputted.
Thanks.
|
You can achieve this by excluding `pingback` from the `comment_type` column of wordpress [**comments table**](https://codex.wordpress.org/Database_Description#Table:_wp_comments)
```
$query = "select
wp_posts.*,
coalesce((
select
max(comment_date)
from
$wpdb->comments wpc
where
wpc.comment_post_id = wp_posts.id
AND comment_approved = 1
AND post_password = ''
AND comment_type NOT IN ( 'pingback' )
),
wp_posts.post_date ) as mcomment_date
from
$wpdb->posts wp_posts
where
post_type = 'post'
and post_status = 'publish'
and comment_count > '0'
order by
mcomment_date desc limit $limit";
```
|
250,940 |
<p>I have a wordpress page that i'm trying to gain access to. I currently have access to the phpadmin database and I can easily create a new password. But I'm actually looking to see what the actual password is. There is only one user account, which is the admin. But i'm able to create other users accounts if needed. Is there anyway i'm able to crack the md5 salt password?</p>
|
[
{
"answer_id": 250887,
"author": "iguanarama",
"author_id": 109807,
"author_profile": "https://wordpress.stackexchange.com/users/109807",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"https://codex.wordpress.org/Database_Description#Table:_wp_comments\" rel=\"nofollow noreferrer\">wp_comments table</a> has a field 'comment_type' which indicates pingback etc. So while my SQL knowledge is not great, I think you just need one extra line in your query where you're selecting from the comments table:</p>\n\n<pre><code>[...]\nwhere\n wpc.comment_post_id = wp_posts.id\n AND wpc.comment_type != 'pingback'\n [...]\n</code></pre>\n"
},
{
"answer_id": 250894,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": true,
"text": "<p>You can achieve this by excluding <code>pingback</code> from the <code>comment_type</code> column of wordpress <a href=\"https://codex.wordpress.org/Database_Description#Table:_wp_comments\" rel=\"nofollow noreferrer\"><strong>comments table</strong></a></p>\n\n<pre><code>$query = \"select\n wp_posts.*,\n coalesce((\n select\n max(comment_date)\n from\n $wpdb->comments wpc\n where\n wpc.comment_post_id = wp_posts.id\n AND comment_approved = 1\n AND post_password = ''\n AND comment_type NOT IN ( 'pingback' )\n ),\n wp_posts.post_date ) as mcomment_date\n from\n $wpdb->posts wp_posts\n where\n post_type = 'post'\n and post_status = 'publish'\n and comment_count > '0'\n order by\n mcomment_date desc limit $limit\";\n</code></pre>\n"
}
] |
2017/01/01
|
[
"https://wordpress.stackexchange.com/questions/250940",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107806/"
] |
I have a wordpress page that i'm trying to gain access to. I currently have access to the phpadmin database and I can easily create a new password. But I'm actually looking to see what the actual password is. There is only one user account, which is the admin. But i'm able to create other users accounts if needed. Is there anyway i'm able to crack the md5 salt password?
|
You can achieve this by excluding `pingback` from the `comment_type` column of wordpress [**comments table**](https://codex.wordpress.org/Database_Description#Table:_wp_comments)
```
$query = "select
wp_posts.*,
coalesce((
select
max(comment_date)
from
$wpdb->comments wpc
where
wpc.comment_post_id = wp_posts.id
AND comment_approved = 1
AND post_password = ''
AND comment_type NOT IN ( 'pingback' )
),
wp_posts.post_date ) as mcomment_date
from
$wpdb->posts wp_posts
where
post_type = 'post'
and post_status = 'publish'
and comment_count > '0'
order by
mcomment_date desc limit $limit";
```
|
250,952 |
<p>I'd like to display the sale price of a product before the regular (discounted) price. I know this has something to do with <code>get_price_html</code>. By default, this outputs something like:</p>
<pre><code><del>regular price</del>
<ins>sale price</ins>
</code></pre>
<p>I want to change the output so it looks like this (basically, the two prices are shown in a different order):</p>
<pre><code><ins>sale price</ins>
<del>regular price</del>
</code></pre>
<p>How can I do this?</p>
<p>Thank you!</p>
|
[
{
"answer_id": 267169,
"author": "Tushar Satani",
"author_id": 119866,
"author_profile": "https://wordpress.stackexchange.com/users/119866",
"pm_score": 0,
"selected": false,
"text": "<p>Price is come from <code>price.php</code> file in woocommerce plugin. inside this file there is function like</p>\n\n<pre><code>$price_html = $product->get_price_html();\n</code></pre>\n\n<p>You have to comment it and put following code instead of this function.</p>\n\n<pre><code>// Sale Price\n<span class=\"price\"><?php echo \"Sale Price :\". \" \" . get_woocommerce_currency_symbol().$product->get_sale_price(); ?></span>\n// Regular Price\n<span class=\"price\"><?php echo \"Regular Price :\". \" \" . get_woocommerce_currency_symbol().$product->get_regular_price(); ?></span> \n</code></pre>\n\n<p>and add classes as per your requirements.</p>\n"
},
{
"answer_id": 267461,
"author": "jtermaat",
"author_id": 118779,
"author_profile": "https://wordpress.stackexchange.com/users/118779",
"pm_score": 1,
"selected": false,
"text": "<p>You have to change this in functions.php</p>\n\n<pre><code>if (!function_exists('my_commonPriceHtml')) {\n\nfunction my_commonPriceHtml($price_amt, $regular_price, $sale_price) {\n $html_price = '<p class=\"price\">';\n //if product is in sale\n if (($price_amt == $sale_price) && ($sale_price != 0)) {\n $html_price .= '<ins>' . wc_price($sale_price) . '</ins>';\n $html_price .= '&nbsp;&nbsp;<del>' . wc_price($regular_price) . '</del>';\n }\n //in sale but free\n else if (($price_amt == $sale_price) && ($sale_price == 0)) {\n $html_price .= '<ins>Free!</ins>';\n $html_price .= '<del>' . wc_price($regular_price) . '</del>';\n }\n //not is sale\n else if (($price_amt == $regular_price) && ($regular_price != 0)) {\n $html_price .= '<ins>' . wc_price($regular_price) . '</ins>';\n }\n //for free product\n else if (($price_amt == $regular_price) && ($regular_price == 0)) {\n $html_price .= '<ins>Free!</ins>';\n }\n $html_price .= '</p>';\n return $html_price;\n}\n\n}\n\nadd_filter('woocommerce_get_price_html', 'my_simple_product_price_html', 100, 2);\n\nfunction my_simple_product_price_html($price, $product) {\nif ($product->is_type('simple')) {\n $regular_price = $product->regular_price;\n $sale_price = $product->sale_price;\n $price_amt = $product->price;\n return my_commonPriceHtml($price_amt, $regular_price, $sale_price);\n} else {\n return $price;\n}\n}\n\nadd_filter('woocommerce_variation_sale_price_html', 'my_variable_product_price_html', 10, 2);\nadd_filter('woocommerce_variation_price_html', 'my_variable_product_price_html', 10, 2);\n\nfunction my_variable_product_price_html($price, $variation) {\n$variation_id = $variation->variation_id;\n//creating the product object\n$variable_product = new WC_Product($variation_id);\n\n$regular_price = $variable_product->regular_price;\n$sale_price = $variable_product->sale_price;\n$price_amt = $variable_product->price;\n\n return my_commonPriceHtml($price_amt, $regular_price, $sale_price);\n }\n\nadd_filter('woocommerce_variable_sale_price_html', 'my_variable_product_minmax_price_html', 10, 2);\nadd_filter('woocommerce_variable_price_html', 'my_variable_product_minmax_price_html', 10, 2);\n\nfunction my_variable_product_minmax_price_html($price, $product) {\n$variation_min_price = $product->get_variation_price('min', true);\n$variation_max_price = $product->get_variation_price('max', true);\n$variation_min_regular_price = $product->get_variation_regular_price('min', true);\n$variation_max_regular_price = $product->get_variation_regular_price('max', true);\n\nif (($variation_min_price == $variation_min_regular_price) && ($variation_max_price == $variation_max_regular_price)) {\n $html_min_max_price = $price;\n} else {\n $html_price = '<p class=\"price\">';\n $html_price .= '<ins>' . wc_price($variation_min_price) . '-' . wc_price($variation_max_price) . '</ins>';\n $html_price .= '<del>' . wc_price($variation_min_regular_price) . '-' . wc_price($variation_max_regular_price) . '</del>';\n $html_min_max_price = $html_price;\n}\n\nreturn $html_min_max_price;\n}\n</code></pre>\n"
},
{
"answer_id": 406435,
"author": "Westzone Solution",
"author_id": 116707,
"author_profile": "https://wordpress.stackexchange.com/users/116707",
"pm_score": 1,
"selected": false,
"text": "<p>I have tried it myself and this is my price.php code. You just need to add some css as per your need.</p>\n<p><strong>First, remove the existing code</strong></p>\n<pre><code>'<p class="'.esc_attr( apply_filters( 'woocommerce_product_price_class', 'price' ) ).'">'.$product->get_price_html().'</p>';\n</code></pre>\n<p><strong>Then put this code :</strong></p>\n<pre><code>global $product;\n$product_id = $product->get_id();\n\nif( $product->is_type( 'simple' ) ){\n $regular_price = $product->get_regular_price();\n $sale_price = $product->get_sale_price();\n $discount = ($sale_price/$regular_price)*100;\n\necho '<ul class="'.esc_attr( apply_filters( 'woocommerce_product_price_class', 'price')).'">\n <li class="sale_price"><span class="woocommerce-Price-currencySymbol">'.get_woocommerce_currency_symbol().'</span>'.$sale_price.'</li>\n <li class="regular_price"><span class="woocommerce-Price-currencySymbol">'.get_woocommerce_currency_symbol().'</span>'.$regular_price.'</li>\n <li class="disc">'.round($discount,0).'% Off</li>\n <div class="clear"></div>\n </ul>';\n} elseif( $product->is_type( 'variable' ) ){\n // Regular price min and max\n $min_regular_price = $product->get_variation_regular_price( 'min' );\n $max_regular_price = $product->get_variation_regular_price( 'max' );\n\n // Sale price min and max\n $min_sale_price = $product->get_variation_sale_price( 'min' );\n $max_sale_price = $product->get_variation_sale_price( 'max' );\n\n // The active price min and max\n $min_price = $product->get_variation_price( 'min' );\n $max_price = $product->get_variation_price( 'max' );\n $var_discount = ($min_sale_price/$min_regular_price)*100;\n\necho '<ul class="'.esc_attr( apply_filters( 'woocommerce_product_price_class', 'price')).'">\n <li class="sale_price"><span class="woocommerce-Price-currencySymbol">'.get_woocommerce_currency_symbol().'</span>'.$min_sale_price.'</li>\n <li class="regular_price"><span class="woocommerce-Price-currencySymbol">'.get_woocommerce_currency_symbol().'</span>'.$max_regular_price.'</li>\n <li class="disc">'.round($var_discount,0).'% Off</li>\n <div class="clear"></div>\n </ul>';\n }\n</code></pre>\n<p>The output is\n<a href=\"https://i.stack.imgur.com/QqOpQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QqOpQ.png\" alt=\"enter image description here\" /></a></p>\n"
}
] |
2017/01/01
|
[
"https://wordpress.stackexchange.com/questions/250952",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106693/"
] |
I'd like to display the sale price of a product before the regular (discounted) price. I know this has something to do with `get_price_html`. By default, this outputs something like:
```
<del>regular price</del>
<ins>sale price</ins>
```
I want to change the output so it looks like this (basically, the two prices are shown in a different order):
```
<ins>sale price</ins>
<del>regular price</del>
```
How can I do this?
Thank you!
|
You have to change this in functions.php
```
if (!function_exists('my_commonPriceHtml')) {
function my_commonPriceHtml($price_amt, $regular_price, $sale_price) {
$html_price = '<p class="price">';
//if product is in sale
if (($price_amt == $sale_price) && ($sale_price != 0)) {
$html_price .= '<ins>' . wc_price($sale_price) . '</ins>';
$html_price .= ' <del>' . wc_price($regular_price) . '</del>';
}
//in sale but free
else if (($price_amt == $sale_price) && ($sale_price == 0)) {
$html_price .= '<ins>Free!</ins>';
$html_price .= '<del>' . wc_price($regular_price) . '</del>';
}
//not is sale
else if (($price_amt == $regular_price) && ($regular_price != 0)) {
$html_price .= '<ins>' . wc_price($regular_price) . '</ins>';
}
//for free product
else if (($price_amt == $regular_price) && ($regular_price == 0)) {
$html_price .= '<ins>Free!</ins>';
}
$html_price .= '</p>';
return $html_price;
}
}
add_filter('woocommerce_get_price_html', 'my_simple_product_price_html', 100, 2);
function my_simple_product_price_html($price, $product) {
if ($product->is_type('simple')) {
$regular_price = $product->regular_price;
$sale_price = $product->sale_price;
$price_amt = $product->price;
return my_commonPriceHtml($price_amt, $regular_price, $sale_price);
} else {
return $price;
}
}
add_filter('woocommerce_variation_sale_price_html', 'my_variable_product_price_html', 10, 2);
add_filter('woocommerce_variation_price_html', 'my_variable_product_price_html', 10, 2);
function my_variable_product_price_html($price, $variation) {
$variation_id = $variation->variation_id;
//creating the product object
$variable_product = new WC_Product($variation_id);
$regular_price = $variable_product->regular_price;
$sale_price = $variable_product->sale_price;
$price_amt = $variable_product->price;
return my_commonPriceHtml($price_amt, $regular_price, $sale_price);
}
add_filter('woocommerce_variable_sale_price_html', 'my_variable_product_minmax_price_html', 10, 2);
add_filter('woocommerce_variable_price_html', 'my_variable_product_minmax_price_html', 10, 2);
function my_variable_product_minmax_price_html($price, $product) {
$variation_min_price = $product->get_variation_price('min', true);
$variation_max_price = $product->get_variation_price('max', true);
$variation_min_regular_price = $product->get_variation_regular_price('min', true);
$variation_max_regular_price = $product->get_variation_regular_price('max', true);
if (($variation_min_price == $variation_min_regular_price) && ($variation_max_price == $variation_max_regular_price)) {
$html_min_max_price = $price;
} else {
$html_price = '<p class="price">';
$html_price .= '<ins>' . wc_price($variation_min_price) . '-' . wc_price($variation_max_price) . '</ins>';
$html_price .= '<del>' . wc_price($variation_min_regular_price) . '-' . wc_price($variation_max_regular_price) . '</del>';
$html_min_max_price = $html_price;
}
return $html_min_max_price;
}
```
|
250,959 |
<p>I've been trying to find a decent solution to a problem for a while now. In the theme I'm building I have a top "admin bar" menu with some contact links and below that my "logo area" and a main menu.</p>
<p>I would like to merge these menus into one single menu in mobile view but still keep some form of control over each separate menu when merged (different font size in each menu, etc).</p>
<p>Of course I could build a fourth menu with all the links I need to only display in mobile view and hide my regular menus but is that really the best way to go about this scenario?</p>
<p>This is my complete header markup:</p>
<pre><code><header id="masthead" class="site-header" role="banner">
<?php if ( has_nav_menu( 'admin' ) ) : ?>
<nav id="top-nav" class="top-bar menues" role="navigation">
<?php wp_nav_menu( array( 'theme_location' => 'admin' ) ); ?>
</nav><!-- #top-nav -->
<?php endif; ?>
<div class="site-branding wrap">
<figure class="site-logo">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
<img class="inject-me" src="<?php echo esc_url( get_template_directory_uri() ); ?>/icons/logo.svg" alt="logo">
</a>
</figure><!-- .site-logo -->
</div><!-- .site-branding -->
<?php if ( has_nav_menu( 'primary' ) ) : ?>
<nav id="site-navigation" class="main-navigation menues" role="navigation">
<button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false"><?php esc_html_e( 'Menu', 'testsite' ); ?></button>
<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_id' => 'primary-menu', 'menu_class' => 'nav-menu' ) ); ?>
</nav><!-- #site-navigation -->
<?php endif; ?>
</header><!-- #masthead -->
</code></pre>
<p>I've seen some code tips that use jquery? to clone one menu into another, but never anything WordPress specific. The result I'm trying to achieve is to tag along the "admin bar" under the main menu in mobile view so you get one long list of links.</p>
<p>Anybody working with a similar problem?</p>
|
[
{
"answer_id": 250965,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": -1,
"selected": false,
"text": "<p>I think you just need coaching. I would go with creating the 4-th menu automatically based on the other two. </p>\n\n<p>How and Why? </p>\n\n<p>As lazy as possible, and because it can help you think more physical way.\nSo you need to update the 4-th menu when you update the other two menus. This is lazy.</p>\n\n<p>What about mobile? You are good, you will be able to create a class for your 4-th menu that would work only on mobile.</p>\n"
},
{
"answer_id": 299921,
"author": "AstralProgrammer",
"author_id": 118120,
"author_profile": "https://wordpress.stackexchange.com/users/118120",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem. The solution I chose was to \"merge\" the menus by placing them under a single div wrapper but have them on separate div class.</p>\n\n<p>Something like this:</p>\n\n<pre><code><div class=\"menu-wrapper\">\n <div class=\"menu1\">\n <?php\n wp_nav_menu( array(\n 'theme_location' => 'menu-1',\n 'menu_id' => 'top-menu',\n ) );\n ?>\n </div>\n <div class=\"menu2\">\n <?php\n wp_nav_menu( array(\n 'theme_location' => 'menu-2',\n 'menu_id' => 'main-menu',\n ) );\n ?>\n </div>\n</div>\n</code></pre>\n\n<p>If you want to \"merge\" the actual menu objects, try placing menu item on variables via <code>wp_get_nav_menu_items()</code> then <code>array_merge($menu1, $menu2)</code>. As for the control over the elements, maybe you can add an identifier while creating the new menu HTML with the merge list.</p>\n\n<p>I'm not sure if this is the answer you are looking for nor if its the best approach. Hope it helps.</p>\n"
}
] |
2017/01/01
|
[
"https://wordpress.stackexchange.com/questions/250959",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94259/"
] |
I've been trying to find a decent solution to a problem for a while now. In the theme I'm building I have a top "admin bar" menu with some contact links and below that my "logo area" and a main menu.
I would like to merge these menus into one single menu in mobile view but still keep some form of control over each separate menu when merged (different font size in each menu, etc).
Of course I could build a fourth menu with all the links I need to only display in mobile view and hide my regular menus but is that really the best way to go about this scenario?
This is my complete header markup:
```
<header id="masthead" class="site-header" role="banner">
<?php if ( has_nav_menu( 'admin' ) ) : ?>
<nav id="top-nav" class="top-bar menues" role="navigation">
<?php wp_nav_menu( array( 'theme_location' => 'admin' ) ); ?>
</nav><!-- #top-nav -->
<?php endif; ?>
<div class="site-branding wrap">
<figure class="site-logo">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
<img class="inject-me" src="<?php echo esc_url( get_template_directory_uri() ); ?>/icons/logo.svg" alt="logo">
</a>
</figure><!-- .site-logo -->
</div><!-- .site-branding -->
<?php if ( has_nav_menu( 'primary' ) ) : ?>
<nav id="site-navigation" class="main-navigation menues" role="navigation">
<button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false"><?php esc_html_e( 'Menu', 'testsite' ); ?></button>
<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_id' => 'primary-menu', 'menu_class' => 'nav-menu' ) ); ?>
</nav><!-- #site-navigation -->
<?php endif; ?>
</header><!-- #masthead -->
```
I've seen some code tips that use jquery? to clone one menu into another, but never anything WordPress specific. The result I'm trying to achieve is to tag along the "admin bar" under the main menu in mobile view so you get one long list of links.
Anybody working with a similar problem?
|
I had the same problem. The solution I chose was to "merge" the menus by placing them under a single div wrapper but have them on separate div class.
Something like this:
```
<div class="menu-wrapper">
<div class="menu1">
<?php
wp_nav_menu( array(
'theme_location' => 'menu-1',
'menu_id' => 'top-menu',
) );
?>
</div>
<div class="menu2">
<?php
wp_nav_menu( array(
'theme_location' => 'menu-2',
'menu_id' => 'main-menu',
) );
?>
</div>
</div>
```
If you want to "merge" the actual menu objects, try placing menu item on variables via `wp_get_nav_menu_items()` then `array_merge($menu1, $menu2)`. As for the control over the elements, maybe you can add an identifier while creating the new menu HTML with the merge list.
I'm not sure if this is the answer you are looking for nor if its the best approach. Hope it helps.
|
250,961 |
<p>I want to customize my individual posts. I have an example of what I'm trying to achieve below. Would I make a custom post template for this? If so how would I do this? Or should I add to my single.php? Thanks in advance.</p>
<p>What I want my individual post pages to look like. I want two pictures side by side that are the full width of the page. Text. One picture that is the full width of the page. Text. One picture thats starts at the left edge of the page and has text next to it. And then one full width picture. <a href="https://i.stack.imgur.com/vnkJJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vnkJJ.jpg" alt="enter image description here"></a></p>
<p>Here is my single.php</p>
<pre class="lang-html prettyprint-override"><code><?php
get_header();
the_post_thumbnail('banner-image');
if (have_posts()) :
while (have_posts()) : the_post(); ?>
<article class="post">
<?php wpb_set_post_views(get_the_ID()); ?>
<div class="post-info">
<h1 class="post-title"><?php the_title(); ?></h1>
<h2 class="post-date"><?php echo strip_tags(get_the_term_list( $post->ID, 'location', 'Location: ', ', ', ' • ' ));?><?php the_date('F m, Y'); ?></h2>
</div>
<div class="post-content"><?php the_content(); ?></div>
<?php comments_template(); ?>
</article>
<?php endwhile;
else :
echo '<p>No content found</p>';
endif;
get_footer();
?>
</code></pre>
<p>Any insight would help. I know how I want it to look, I just don't exactly know how to achieve it.</p>
|
[
{
"answer_id": 250965,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": -1,
"selected": false,
"text": "<p>I think you just need coaching. I would go with creating the 4-th menu automatically based on the other two. </p>\n\n<p>How and Why? </p>\n\n<p>As lazy as possible, and because it can help you think more physical way.\nSo you need to update the 4-th menu when you update the other two menus. This is lazy.</p>\n\n<p>What about mobile? You are good, you will be able to create a class for your 4-th menu that would work only on mobile.</p>\n"
},
{
"answer_id": 299921,
"author": "AstralProgrammer",
"author_id": 118120,
"author_profile": "https://wordpress.stackexchange.com/users/118120",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem. The solution I chose was to \"merge\" the menus by placing them under a single div wrapper but have them on separate div class.</p>\n\n<p>Something like this:</p>\n\n<pre><code><div class=\"menu-wrapper\">\n <div class=\"menu1\">\n <?php\n wp_nav_menu( array(\n 'theme_location' => 'menu-1',\n 'menu_id' => 'top-menu',\n ) );\n ?>\n </div>\n <div class=\"menu2\">\n <?php\n wp_nav_menu( array(\n 'theme_location' => 'menu-2',\n 'menu_id' => 'main-menu',\n ) );\n ?>\n </div>\n</div>\n</code></pre>\n\n<p>If you want to \"merge\" the actual menu objects, try placing menu item on variables via <code>wp_get_nav_menu_items()</code> then <code>array_merge($menu1, $menu2)</code>. As for the control over the elements, maybe you can add an identifier while creating the new menu HTML with the merge list.</p>\n\n<p>I'm not sure if this is the answer you are looking for nor if its the best approach. Hope it helps.</p>\n"
}
] |
2017/01/01
|
[
"https://wordpress.stackexchange.com/questions/250961",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101743/"
] |
I want to customize my individual posts. I have an example of what I'm trying to achieve below. Would I make a custom post template for this? If so how would I do this? Or should I add to my single.php? Thanks in advance.
What I want my individual post pages to look like. I want two pictures side by side that are the full width of the page. Text. One picture that is the full width of the page. Text. One picture thats starts at the left edge of the page and has text next to it. And then one full width picture. [](https://i.stack.imgur.com/vnkJJ.jpg)
Here is my single.php
```html
<?php
get_header();
the_post_thumbnail('banner-image');
if (have_posts()) :
while (have_posts()) : the_post(); ?>
<article class="post">
<?php wpb_set_post_views(get_the_ID()); ?>
<div class="post-info">
<h1 class="post-title"><?php the_title(); ?></h1>
<h2 class="post-date"><?php echo strip_tags(get_the_term_list( $post->ID, 'location', 'Location: ', ', ', ' • ' ));?><?php the_date('F m, Y'); ?></h2>
</div>
<div class="post-content"><?php the_content(); ?></div>
<?php comments_template(); ?>
</article>
<?php endwhile;
else :
echo '<p>No content found</p>';
endif;
get_footer();
?>
```
Any insight would help. I know how I want it to look, I just don't exactly know how to achieve it.
|
I had the same problem. The solution I chose was to "merge" the menus by placing them under a single div wrapper but have them on separate div class.
Something like this:
```
<div class="menu-wrapper">
<div class="menu1">
<?php
wp_nav_menu( array(
'theme_location' => 'menu-1',
'menu_id' => 'top-menu',
) );
?>
</div>
<div class="menu2">
<?php
wp_nav_menu( array(
'theme_location' => 'menu-2',
'menu_id' => 'main-menu',
) );
?>
</div>
</div>
```
If you want to "merge" the actual menu objects, try placing menu item on variables via `wp_get_nav_menu_items()` then `array_merge($menu1, $menu2)`. As for the control over the elements, maybe you can add an identifier while creating the new menu HTML with the merge list.
I'm not sure if this is the answer you are looking for nor if its the best approach. Hope it helps.
|
250,962 |
<p>I creating website and I need to have different homepages for logged in and logged off users. I have page 'Home page' which is set as home page and is filled with information about my site and pictures and simple page 'Home logged in' which was set as BuddyPress activity stream. What I need is:
- User A is visiting website but he is not logged in and can see 'Home page' as homepage
- User B is visiting website and he is logged in and can see 'Home page logged in' as homepage.
I have tried to reach it with this code, by inserting it to my theme functions.php :</p>
<pre><code>function switch_homepage() {
if ( is_user_logged_in() ) {
$page = get_page_by_title( 'Home page logged in' );
update_option( 'page_on_front', $page->ID );
update_option( 'show_on_front', 'page' );
} else {
$page = get_page_by_title( 'Home page' );
update_option( 'page_on_front', $page->ID );
update_option( 'show_on_front', 'page' );
}
}
add_action( 'init', 'switch_homepage' );
</code></pre>
<p>But this code sometimes when refreshing page or logging off started to show 'Home page logged in' for logged off users. As I readed this happening because this code change homepage in database. So now my question is how to have separate home page for logged off users without changing database every time?</p>
|
[
{
"answer_id": 251016,
"author": "Pete",
"author_id": 37346,
"author_profile": "https://wordpress.stackexchange.com/users/37346",
"pm_score": 2,
"selected": false,
"text": "<p>Can you use this to redirect the logged out users?</p>\n\n<pre><code><?php if ( !is_user_logged_in() { ?>\n<?php wp_redirect( 'https://yourdomain.com.au/logoutpage', 302 ); exit; ?>\n<?php } ?>\n</code></pre>\n\n<p>or this solution?\n<a href=\"https://wordpress.stackexchange.com/questions/225040/setting-a-specific-home-page-for-logged-in-users?rq=1\">setting a specific home page for logged in users</a></p>\n"
},
{
"answer_id": 277729,
"author": "Daniel Gronow",
"author_id": 126348,
"author_profile": "https://wordpress.stackexchange.com/users/126348",
"pm_score": -1,
"selected": false,
"text": "<p>I am currently using the following code to display a different homepage for logged in and logged out users. You simply need to change the page id to your chosen page within wordpress and add this to your functions.php file:</p>\n\n<pre><code>function switch_homepage() {\n if ( is_user_logged_in() ) {\n $page = 898; // for logged in users\n update_option( 'page_on_front', $page );\n update_option( 'show_on_front', 'page' );\n\n } else {\n $page = 615; // for logged out users\n update_option( 'page_on_front', $page );\n update_option( 'show_on_front', 'page' );\n }\n}\nadd_action( 'init', 'switch_homepage' );\n</code></pre>\n\n<p>I would like to set a different homepage by user role however am struggling to get the solution I need.</p>\n"
}
] |
2017/01/01
|
[
"https://wordpress.stackexchange.com/questions/250962",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86168/"
] |
I creating website and I need to have different homepages for logged in and logged off users. I have page 'Home page' which is set as home page and is filled with information about my site and pictures and simple page 'Home logged in' which was set as BuddyPress activity stream. What I need is:
- User A is visiting website but he is not logged in and can see 'Home page' as homepage
- User B is visiting website and he is logged in and can see 'Home page logged in' as homepage.
I have tried to reach it with this code, by inserting it to my theme functions.php :
```
function switch_homepage() {
if ( is_user_logged_in() ) {
$page = get_page_by_title( 'Home page logged in' );
update_option( 'page_on_front', $page->ID );
update_option( 'show_on_front', 'page' );
} else {
$page = get_page_by_title( 'Home page' );
update_option( 'page_on_front', $page->ID );
update_option( 'show_on_front', 'page' );
}
}
add_action( 'init', 'switch_homepage' );
```
But this code sometimes when refreshing page or logging off started to show 'Home page logged in' for logged off users. As I readed this happening because this code change homepage in database. So now my question is how to have separate home page for logged off users without changing database every time?
|
Can you use this to redirect the logged out users?
```
<?php if ( !is_user_logged_in() { ?>
<?php wp_redirect( 'https://yourdomain.com.au/logoutpage', 302 ); exit; ?>
<?php } ?>
```
or this solution?
[setting a specific home page for logged in users](https://wordpress.stackexchange.com/questions/225040/setting-a-specific-home-page-for-logged-in-users?rq=1)
|
250,989 |
<p>I need to show a new post marker for unread posts, placed after its date as is shown in the image below: </p>
<p><a href="https://i.stack.imgur.com/yebGg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yebGg.jpg" alt="enter image description here"></a></p>
<p>Any tips?</p>
|
[
{
"answer_id": 250991,
"author": "dgarceran",
"author_id": 109222,
"author_profile": "https://wordpress.stackexchange.com/users/109222",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"https://codex.wordpress.org/Function_Reference/update_user_meta\" rel=\"nofollow noreferrer\">update_user_meta()</a> and <a href=\"https://codex.wordpress.org/Function_Reference/get_user_meta\" rel=\"nofollow noreferrer\">get_user_meta()</a>, where you can store and retrieve a value related to a key and a user, like <code>'read_post_' . $post_id</code> for example.</p>\n\n<p>Inside <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">The Loop</a>, when you're going to print the article, you can add a condition: if the user has the user meta value <code>'read_post_' . $post_id</code> as false or not set, you could print that blue circle.</p>\n\n<pre><code>if(get_user_meta($user_id, 'read_post_' . $post_id, true) != \"\"){\n // show the notification\n}\n</code></pre>\n\n<p>And when you print the inside of the article you can update that value, so it will be set as true:</p>\n\n<pre><code>update_user_meta( $user_id, 'read_post_' . $post_id, true );\n</code></pre>\n"
},
{
"answer_id": 250995,
"author": "Pratik bhatt",
"author_id": 60922,
"author_profile": "https://wordpress.stackexchange.com/users/60922",
"pm_score": 0,
"selected": false,
"text": "<p>You may please follow this tutorial <a href=\"http://www.wpbeginner.com/wp-themes/how-to-highlight-new-posts-for-returning-visitors-in-wordpress/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-themes/how-to-highlight-new-posts-for-returning-visitors-in-wordpress/</a></p>\n"
}
] |
2017/01/02
|
[
"https://wordpress.stackexchange.com/questions/250989",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33903/"
] |
I need to show a new post marker for unread posts, placed after its date as is shown in the image below:
[](https://i.stack.imgur.com/yebGg.jpg)
Any tips?
|
You can use [update\_user\_meta()](https://codex.wordpress.org/Function_Reference/update_user_meta) and [get\_user\_meta()](https://codex.wordpress.org/Function_Reference/get_user_meta), where you can store and retrieve a value related to a key and a user, like `'read_post_' . $post_id` for example.
Inside [The Loop](https://codex.wordpress.org/The_Loop), when you're going to print the article, you can add a condition: if the user has the user meta value `'read_post_' . $post_id` as false or not set, you could print that blue circle.
```
if(get_user_meta($user_id, 'read_post_' . $post_id, true) != ""){
// show the notification
}
```
And when you print the inside of the article you can update that value, so it will be set as true:
```
update_user_meta( $user_id, 'read_post_' . $post_id, true );
```
|
250,999 |
<p>I'm trying to get 2 php functions with my custom field to work together with a custom field. they both work by themselves great but I can't get them to work together.</p>
<p>The first function hides the last X characters of a custom field</p>
<pre><code><?php $custom_field = (string) get_post_meta( $post->ID, "XYZ", true ); echo substr( $custom_field, 0, -6 ); ?>
</code></pre>
<p>The second function removes the spaces of a custom field</p>
<pre><code><?php $custom_field = (string) get_post_meta( $post->ID, "XYZ", true ); echo str_replace(' ', '', $custom_field); ?>
</code></pre>
<p>My optimistically simple attempt at a solution was/is a disaster...</p>
<pre><code><?php $custom_field = (string) get_post_meta( $post->ID, "XYZ", true ); echo str_replace(' ', '', $custom_field); echo substr( $custom_field, 0, -6 ); ?>
</code></pre>
|
[
{
"answer_id": 251004,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 2,
"selected": true,
"text": "<p>I had the same problem.</p>\n\n<pre><code>echo substr( $custom_field, 0, -6 );\necho str_replace(' ', '', $custom_field);\n</code></pre>\n\n<p>I think I solved it this way.</p>\n\n<pre><code>echo substr( str_replace(' ', '', $custom_field), 0, -6 );\n</code></pre>\n"
},
{
"answer_id": 251005,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://wordpress.stackexchange.com/users/88606/prosti\"><strong>@prosti</strong></a> is right, if you're looking for a function though, you can wrap both calls in a single reusable function.</p>\n\n<pre><code>function wpse250999_combine( $string ) {\n $output = substr( $string, 0, -6 );\n $output = str_replace(' ', '', $output );\n return $output;\n}\n</code></pre>\n\n<p><strong>USAGE:</strong></p>\n\n<pre><code>$custom_field = wpse250999_combine( (string) get_post_meta( $post->ID, \"XYZ\", true ) );\necho $custom_field;\n</code></pre>\n"
}
] |
2017/01/02
|
[
"https://wordpress.stackexchange.com/questions/250999",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
] |
I'm trying to get 2 php functions with my custom field to work together with a custom field. they both work by themselves great but I can't get them to work together.
The first function hides the last X characters of a custom field
```
<?php $custom_field = (string) get_post_meta( $post->ID, "XYZ", true ); echo substr( $custom_field, 0, -6 ); ?>
```
The second function removes the spaces of a custom field
```
<?php $custom_field = (string) get_post_meta( $post->ID, "XYZ", true ); echo str_replace(' ', '', $custom_field); ?>
```
My optimistically simple attempt at a solution was/is a disaster...
```
<?php $custom_field = (string) get_post_meta( $post->ID, "XYZ", true ); echo str_replace(' ', '', $custom_field); echo substr( $custom_field, 0, -6 ); ?>
```
|
I had the same problem.
```
echo substr( $custom_field, 0, -6 );
echo str_replace(' ', '', $custom_field);
```
I think I solved it this way.
```
echo substr( str_replace(' ', '', $custom_field), 0, -6 );
```
|
251,007 |
<p>I need to replace featured images on pages with a video if certain posts contain a video from YouTube, Vimeo, other video hosting services allowed by WordPress. </p>
<p>Here's the pseudo code that I want to use on a custom page:</p>
<pre><code>if ( has_post_thumbnail( get_the_ID() {
if has_video(pseudocode to check whether the single post contains youtube video) {
// show video player
} else {
// show post thumbnail
}
}
</code></pre>
<p>Any tips?</p>
|
[
{
"answer_id": 251056,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 3,
"selected": true,
"text": "<p>Let's say for simplicity that you're using <a href=\"https://www.advancedcustomfields.com/\" rel=\"nofollow noreferrer\">ACF</a>. You need to create a video link field once ACF is installed and assign it to posts. Then, in the post you want a video to show up, add the url. I usually assign this field as a text field and then have users enter the youtube id (last string of text after the <code>youtube.com</code> link. </p>\n\n<p>For example, if the video link was: <code>https://www.youtube.com/J-ek8drxFJA</code></p>\n\n<p>the user would enter just <code>J-ek8drxFJA</code> in the field.</p>\n\n<p>Now add this code to your single.php copy that is in your child theme folder</p>\n\n<p>Notice that I changed the <code>if</code> statement. No need to look for the thumbnail if you're going to use a video:</p>\n\n<pre><code>if( get_field( 'video_link' ) ) {\n echo 'this is my video link id ' . get_field( 'video_link' ); // or show video player (see below)\n} else {\n if( has_post_thumbnail( get_the_ID() {\n // show post thumbnail\n }\n\n //no video or photo\n}\n</code></pre>\n\n<p>Now of course if you want to show the video you'll want to do something like this instead:</p>\n\n<pre><code>if( get_field( 'video_link' ) ) {\n $videoid = get_field( 'video_link' );\n echo '<h2>Video Link</h2><p>see our video:</p><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/' . $videoid . '\" frameborder=\"0\" allowfullscreen></iframe>';\n} else {\n if( has_post_thumbnail( get_the_ID() ) ) {\n // show post thumbnail\n }\n\n //no video or photo\n}\n</code></pre>\n\n<p>Obviously you can change the code up a bit to suit your needs.</p>\n"
},
{
"answer_id": 300536,
"author": "Milan Bastola",
"author_id": 137372,
"author_profile": "https://wordpress.stackexchange.com/users/137372",
"pm_score": 1,
"selected": false,
"text": "<p>I think you should give a try to this plugin : \n<a href=\"https://wordpress.org/plugins/featured-video-plus/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/featured-video-plus/</a></p>\n\n<p>If you don't like to use extra plugin then you should definitely look into their code for reference. you can look into their code and customize them as per your requirements.</p>\n"
}
] |
2017/01/02
|
[
"https://wordpress.stackexchange.com/questions/251007",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33903/"
] |
I need to replace featured images on pages with a video if certain posts contain a video from YouTube, Vimeo, other video hosting services allowed by WordPress.
Here's the pseudo code that I want to use on a custom page:
```
if ( has_post_thumbnail( get_the_ID() {
if has_video(pseudocode to check whether the single post contains youtube video) {
// show video player
} else {
// show post thumbnail
}
}
```
Any tips?
|
Let's say for simplicity that you're using [ACF](https://www.advancedcustomfields.com/). You need to create a video link field once ACF is installed and assign it to posts. Then, in the post you want a video to show up, add the url. I usually assign this field as a text field and then have users enter the youtube id (last string of text after the `youtube.com` link.
For example, if the video link was: `https://www.youtube.com/J-ek8drxFJA`
the user would enter just `J-ek8drxFJA` in the field.
Now add this code to your single.php copy that is in your child theme folder
Notice that I changed the `if` statement. No need to look for the thumbnail if you're going to use a video:
```
if( get_field( 'video_link' ) ) {
echo 'this is my video link id ' . get_field( 'video_link' ); // or show video player (see below)
} else {
if( has_post_thumbnail( get_the_ID() {
// show post thumbnail
}
//no video or photo
}
```
Now of course if you want to show the video you'll want to do something like this instead:
```
if( get_field( 'video_link' ) ) {
$videoid = get_field( 'video_link' );
echo '<h2>Video Link</h2><p>see our video:</p><iframe width="420" height="315" src="https://www.youtube.com/embed/' . $videoid . '" frameborder="0" allowfullscreen></iframe>';
} else {
if( has_post_thumbnail( get_the_ID() ) ) {
// show post thumbnail
}
//no video or photo
}
```
Obviously you can change the code up a bit to suit your needs.
|
251,023 |
<p>Which is better...</p>
<pre><code><?php if (is_page()): ?>
<?php else: ?>
<?php endif; ?>
</code></pre>
<p>or</p>
<pre><code><?php if (is_page()) { ?>
<?php } else { ?>
<?php } ?>
</code></pre>
|
[
{
"answer_id": 251027,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>I really don't know which is better. Exploring the different conditional statements syntax.</p>\n\n<p>I believe they are all just <strong>alternative syntax</strong> and have no real performance difference.\n<strong>You can have:</strong></p>\n\n<pre><code><?php if (is_page()): ?>\n<?php else: ?>\n<?php endif; ?>\n</code></pre>\n\n<p><strong>OR:</strong></p>\n\n<pre><code><?php if ( is_page() ) { ?>\n<?php } else { ?>\n<?php } ?>\n</code></pre>\n\n<p><strong>also ternary operator:</strong></p>\n\n<pre><code><?php echo is_page() ? \"Is page\" : \"Not a page\"; ?>\n</code></pre>\n"
},
{
"answer_id": 251031,
"author": "Celso Bessa",
"author_id": 22694,
"author_profile": "https://wordpress.stackexchange.com/users/22694",
"pm_score": 3,
"selected": true,
"text": "<p>As far as I can tell, there's no performance difference. And both styles are acceptable by <a href=\"https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#brace-style\" rel=\"nofollow noreferrer\">WordPress Coding Standards</a> as you can read in:</p>\n\n<blockquote>\n <p>Braces should always be used, even when they are not required:</p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n <p>Note that requiring the use of braces just means that single-statement\n inline control structures are prohibited. You are free to use the\n alternative syntax for control structures (e.g. if/endif,\n while/endwhile)—especially in your templates where PHP code is\n embedded within HTML</p>\n</blockquote>\n\n<p>I always use the brace styles beucause I think is more widely known by PHP programmers of different levels and makes the block \"hierarchy\" much clearer and easier to understand.</p>\n\n<p>Bottom line: you should choose what is more convenient to you. And whichever you choose, be consistent and stick to it.</p>\n"
}
] |
2017/01/02
|
[
"https://wordpress.stackexchange.com/questions/251023",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
] |
Which is better...
```
<?php if (is_page()): ?>
<?php else: ?>
<?php endif; ?>
```
or
```
<?php if (is_page()) { ?>
<?php } else { ?>
<?php } ?>
```
|
As far as I can tell, there's no performance difference. And both styles are acceptable by [WordPress Coding Standards](https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#brace-style) as you can read in:
>
> Braces should always be used, even when they are not required:
>
>
>
and
>
> Note that requiring the use of braces just means that single-statement
> inline control structures are prohibited. You are free to use the
> alternative syntax for control structures (e.g. if/endif,
> while/endwhile)—especially in your templates where PHP code is
> embedded within HTML
>
>
>
I always use the brace styles beucause I think is more widely known by PHP programmers of different levels and makes the block "hierarchy" much clearer and easier to understand.
Bottom line: you should choose what is more convenient to you. And whichever you choose, be consistent and stick to it.
|
251,025 |
<p>i would like to to add an AdSense activation code to my Wordpress site. </p>
<p>Google says it needs to be inserted right AFTER the tag</p>
<p>I have tried the plugin Snippets, yet it seems not to be working.</p>
<p>The code is:</p>
<pre><code><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>
<script>
(adsbygoogle = window.adsbygoogle || []).push(
{ google_ad_client: "ca-pub-5316020100281676",
enable_page_level_ads: true });
</script>
</code></pre>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 251029,
"author": "Jami Gibbs",
"author_id": 75524,
"author_profile": "https://wordpress.stackexchange.com/users/75524",
"pm_score": 2,
"selected": false,
"text": "<p>Without using a plugin, the WordPress way would be to use the <code>wp_head</code> action to insert the script and then enqueue the script file:</p>\n\n<pre><code>function mytextdomain_adsense() {\n $output=\"\n <script>\n (adsbygoogle = window.adsbygoogle || []).push({ \n google_ad_client: 'ca-pub-5316020100281676',\n enable_page_level_ads: true \n });\n </script>\";\n\n echo $output;\n}\nadd_action('wp_head','mytextdomain_adsense');\n\nfunction mytextdomain_adense_script() {\n wp_enqueue_script( 'my-adsense', '//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js', array(), '1.0.0', false );\n}\nadd_action( 'wp_enqueue_scripts', 'mytextdomain_adense_script' );\n</code></pre>\n\n<p>And to add the <code>async</code> attribute to the script link:</p>\n\n<pre><code>function mytextdomain_add_async_attribute($tag, $handle) {\n if ( 'my-adsense' !== $handle ) {\n return $tag;\n }\n return str_replace( ' src', ' async src', $tag );\n}\nadd_filter('script_loader_tag', 'mytextdomain_add_async_attribute', 10, 2);\n</code></pre>\n\n<p>This should be placed in the theme's <code>functions.php</code> file (preferably a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child theme</a> so that it doesn't get overwritten if there's a theme update).</p>\n"
},
{
"answer_id": 296692,
"author": "Peter",
"author_id": 138252,
"author_profile": "https://wordpress.stackexchange.com/users/138252",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe they changed their requirements? Google says it needs to be inserted BETWEEN the tags. See here: </p>\n\n<p><a href=\"https://i.stack.imgur.com/OtcSQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OtcSQ.png\" alt=\"Implementing code into WordPress page (Google manual (GER)\"></a></p>\n\n<p>There are two ways to realize it: </p>\n\n<ul>\n<li>Use a plugin to paste code into section. </li>\n<li>Or do it manually: create copy of header.php and save it securely. Then open header.php in a text editor and paste AdSense code just BEFORE closing tag. </li>\n</ul>\n"
}
] |
2017/01/02
|
[
"https://wordpress.stackexchange.com/questions/251025",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110060/"
] |
i would like to to add an AdSense activation code to my Wordpress site.
Google says it needs to be inserted right AFTER the tag
I have tried the plugin Snippets, yet it seems not to be working.
The code is:
```
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>
<script>
(adsbygoogle = window.adsbygoogle || []).push(
{ google_ad_client: "ca-pub-5316020100281676",
enable_page_level_ads: true });
</script>
```
Thanks in advance.
|
Without using a plugin, the WordPress way would be to use the `wp_head` action to insert the script and then enqueue the script file:
```
function mytextdomain_adsense() {
$output="
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: 'ca-pub-5316020100281676',
enable_page_level_ads: true
});
</script>";
echo $output;
}
add_action('wp_head','mytextdomain_adsense');
function mytextdomain_adense_script() {
wp_enqueue_script( 'my-adsense', '//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js', array(), '1.0.0', false );
}
add_action( 'wp_enqueue_scripts', 'mytextdomain_adense_script' );
```
And to add the `async` attribute to the script link:
```
function mytextdomain_add_async_attribute($tag, $handle) {
if ( 'my-adsense' !== $handle ) {
return $tag;
}
return str_replace( ' src', ' async src', $tag );
}
add_filter('script_loader_tag', 'mytextdomain_add_async_attribute', 10, 2);
```
This should be placed in the theme's `functions.php` file (preferably a [child theme](https://codex.wordpress.org/Child_Themes) so that it doesn't get overwritten if there's a theme update).
|
251,032 |
<p>I am new to web design. </p>
<p>I know how to use themes with wordpress.</p>
<p>But I am interested in directly downloading the files from e.g. <a href="http://accesspressthemes.com/theme-demos/?theme=storevilla" rel="nofollow noreferrer">http://accesspressthemes.com/theme-demos/?theme=storevilla</a> and edit the contents using wordpress. How can I edit the downloaded files directly using wordpress?</p>
|
[
{
"answer_id": 251029,
"author": "Jami Gibbs",
"author_id": 75524,
"author_profile": "https://wordpress.stackexchange.com/users/75524",
"pm_score": 2,
"selected": false,
"text": "<p>Without using a plugin, the WordPress way would be to use the <code>wp_head</code> action to insert the script and then enqueue the script file:</p>\n\n<pre><code>function mytextdomain_adsense() {\n $output=\"\n <script>\n (adsbygoogle = window.adsbygoogle || []).push({ \n google_ad_client: 'ca-pub-5316020100281676',\n enable_page_level_ads: true \n });\n </script>\";\n\n echo $output;\n}\nadd_action('wp_head','mytextdomain_adsense');\n\nfunction mytextdomain_adense_script() {\n wp_enqueue_script( 'my-adsense', '//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js', array(), '1.0.0', false );\n}\nadd_action( 'wp_enqueue_scripts', 'mytextdomain_adense_script' );\n</code></pre>\n\n<p>And to add the <code>async</code> attribute to the script link:</p>\n\n<pre><code>function mytextdomain_add_async_attribute($tag, $handle) {\n if ( 'my-adsense' !== $handle ) {\n return $tag;\n }\n return str_replace( ' src', ' async src', $tag );\n}\nadd_filter('script_loader_tag', 'mytextdomain_add_async_attribute', 10, 2);\n</code></pre>\n\n<p>This should be placed in the theme's <code>functions.php</code> file (preferably a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child theme</a> so that it doesn't get overwritten if there's a theme update).</p>\n"
},
{
"answer_id": 296692,
"author": "Peter",
"author_id": 138252,
"author_profile": "https://wordpress.stackexchange.com/users/138252",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe they changed their requirements? Google says it needs to be inserted BETWEEN the tags. See here: </p>\n\n<p><a href=\"https://i.stack.imgur.com/OtcSQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OtcSQ.png\" alt=\"Implementing code into WordPress page (Google manual (GER)\"></a></p>\n\n<p>There are two ways to realize it: </p>\n\n<ul>\n<li>Use a plugin to paste code into section. </li>\n<li>Or do it manually: create copy of header.php and save it securely. Then open header.php in a text editor and paste AdSense code just BEFORE closing tag. </li>\n</ul>\n"
}
] |
2017/01/02
|
[
"https://wordpress.stackexchange.com/questions/251032",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110062/"
] |
I am new to web design.
I know how to use themes with wordpress.
But I am interested in directly downloading the files from e.g. <http://accesspressthemes.com/theme-demos/?theme=storevilla> and edit the contents using wordpress. How can I edit the downloaded files directly using wordpress?
|
Without using a plugin, the WordPress way would be to use the `wp_head` action to insert the script and then enqueue the script file:
```
function mytextdomain_adsense() {
$output="
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: 'ca-pub-5316020100281676',
enable_page_level_ads: true
});
</script>";
echo $output;
}
add_action('wp_head','mytextdomain_adsense');
function mytextdomain_adense_script() {
wp_enqueue_script( 'my-adsense', '//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js', array(), '1.0.0', false );
}
add_action( 'wp_enqueue_scripts', 'mytextdomain_adense_script' );
```
And to add the `async` attribute to the script link:
```
function mytextdomain_add_async_attribute($tag, $handle) {
if ( 'my-adsense' !== $handle ) {
return $tag;
}
return str_replace( ' src', ' async src', $tag );
}
add_filter('script_loader_tag', 'mytextdomain_add_async_attribute', 10, 2);
```
This should be placed in the theme's `functions.php` file (preferably a [child theme](https://codex.wordpress.org/Child_Themes) so that it doesn't get overwritten if there's a theme update).
|
251,037 |
<p>I'm requesting posts with the WP REST API and need to sort them according to an ACF field. It's value represents a date (numeric, jQuery date format yymmdd). I know how to do it with a normal WP_Query and tried to do the same using the rest api:</p>
<pre><code>mydomain.com/wp-json/wp/v2/posts?filter[orderby]=meta_value_num&filter[meta_key]=my_field_name&filter[order]=DESC
</code></pre>
<p>In fact I'm using a custom post type that's registered with the rest api and everything else is working perfectly, so I think its not a cpt specific issue?</p>
<p>But the posts show up in default order (their creation date, latest to oldest). What am I missing? Is this orderby parameter not supported by the rest api? If so, how can I implement it myself?</p>
<p>Any other workarounds, suggestions? Really looking for a solution! Thankful for any hints!</p>
|
[
{
"answer_id": 251047,
"author": "iguanarama",
"author_id": 109807,
"author_profile": "https://wordpress.stackexchange.com/users/109807",
"pm_score": 3,
"selected": true,
"text": "<p>I'm guessing you haven't exposed meta_key and meta_value to the REST API with the rest_query_vars filter, so this should do it:</p>\n\n<pre><code>function my_add_meta_vars ($current_vars) {\n $current_vars = array_merge ($current_vars, array ('meta_key', 'meta_value'));\n return $current_vars;\n}\nadd_filter ('rest_query_vars', 'my_add_meta_vars');\n</code></pre>\n\n<p>Then you can refer to meta_key and meta_value in your query.</p>\n\n<p>Be aware that this obviously exposes all your post metadata to the API, which has potential security implications; I believe that's why it's not activated by default.</p>\n"
},
{
"answer_id": 375512,
"author": "Amjad",
"author_id": 195250,
"author_profile": "https://wordpress.stackexchange.com/users/195250",
"pm_score": 0,
"selected": false,
"text": "<pre><code>add_filter( 'rest_post_query', function ( $args, $request ) {\n if ( isset( $request['meta_key']) && !empty($request['meta_key'] ) ) {\n $args['meta_key'] = $request['meta_key'];\n }\n return $args;\n}, 10, 2);\n\nadd_filter( "rest_post_collection_params", function($query_params, $post_type){\n\n array_push($query_params['orderby']['enum'],'meta_value' );\n\n return $query_params;\n}, 10, 2);\n</code></pre>\n"
}
] |
2017/01/02
|
[
"https://wordpress.stackexchange.com/questions/251037",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104835/"
] |
I'm requesting posts with the WP REST API and need to sort them according to an ACF field. It's value represents a date (numeric, jQuery date format yymmdd). I know how to do it with a normal WP\_Query and tried to do the same using the rest api:
```
mydomain.com/wp-json/wp/v2/posts?filter[orderby]=meta_value_num&filter[meta_key]=my_field_name&filter[order]=DESC
```
In fact I'm using a custom post type that's registered with the rest api and everything else is working perfectly, so I think its not a cpt specific issue?
But the posts show up in default order (their creation date, latest to oldest). What am I missing? Is this orderby parameter not supported by the rest api? If so, how can I implement it myself?
Any other workarounds, suggestions? Really looking for a solution! Thankful for any hints!
|
I'm guessing you haven't exposed meta\_key and meta\_value to the REST API with the rest\_query\_vars filter, so this should do it:
```
function my_add_meta_vars ($current_vars) {
$current_vars = array_merge ($current_vars, array ('meta_key', 'meta_value'));
return $current_vars;
}
add_filter ('rest_query_vars', 'my_add_meta_vars');
```
Then you can refer to meta\_key and meta\_value in your query.
Be aware that this obviously exposes all your post metadata to the API, which has potential security implications; I believe that's why it's not activated by default.
|
251,045 |
<p>Have allowed users to register their own website and at the same time this adds them as a user to that site.</p>
<p>However, is there a way to default them to a subscriber of the site they are signing up for rather than automatically adding them as a administrator.</p>
<p>I've looked around in the mess that is wp-signup.php and wp-activate.php and it doesn't look to specify them as an admin anywhere.</p>
<p>Thanks,
Tom</p>
|
[
{
"answer_id": 251052,
"author": "codiiv",
"author_id": 91561,
"author_profile": "https://wordpress.stackexchange.com/users/91561",
"pm_score": 0,
"selected": false,
"text": "<p>You will need something like the <a href=\"https://en-ca.wordpress.org/plugins/multisite-user-role-manager/\" rel=\"nofollow noreferrer\">multisite role management plugin</a>. It allows you to define the user roles to have by default on a per blog basis, in a multisite setting</p>\n"
},
{
"answer_id": 251074,
"author": "CHEWX",
"author_id": 109779,
"author_profile": "https://wordpress.stackexchange.com/users/109779",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, so this isn't possible to do by default.</p>\n<p>As I already had a hook for <code>wpmu_activate_blog()</code> I just created another with a lower priority which will be fired after. This function also has the 2 parameters I need. So upon activation of the account I simply remove Admin role and set a new role based of the subscription service level.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'wpmu_activate_blog', array( $this,'set_new_user_role' ), 15, 2 );\n\npublic function set_new_user_role( $blog_id, $user_id ) {\n $user = new WP_User( $user_id, '', $blog_id );\n\n $user->remove_role( 'administrator' );\n\n // @NOTE - Set this role depending on user subscription level.\n $user->add_role( 'subscriber' );\n}\n</code></pre>\n"
}
] |
2017/01/02
|
[
"https://wordpress.stackexchange.com/questions/251045",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109779/"
] |
Have allowed users to register their own website and at the same time this adds them as a user to that site.
However, is there a way to default them to a subscriber of the site they are signing up for rather than automatically adding them as a administrator.
I've looked around in the mess that is wp-signup.php and wp-activate.php and it doesn't look to specify them as an admin anywhere.
Thanks,
Tom
|
Ok, so this isn't possible to do by default.
As I already had a hook for `wpmu_activate_blog()` I just created another with a lower priority which will be fired after. This function also has the 2 parameters I need. So upon activation of the account I simply remove Admin role and set a new role based of the subscription service level.
```php
add_action( 'wpmu_activate_blog', array( $this,'set_new_user_role' ), 15, 2 );
public function set_new_user_role( $blog_id, $user_id ) {
$user = new WP_User( $user_id, '', $blog_id );
$user->remove_role( 'administrator' );
// @NOTE - Set this role depending on user subscription level.
$user->add_role( 'subscriber' );
}
```
|
251,049 |
<p>The theme I am using places the menu next to the logo (see the attached image). But I prefer to have the menu under the logo. How can I do it?
<a href="https://i.stack.imgur.com/HcHCa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HcHCa.png" alt="menu"></a></p>
|
[
{
"answer_id": 251052,
"author": "codiiv",
"author_id": 91561,
"author_profile": "https://wordpress.stackexchange.com/users/91561",
"pm_score": 0,
"selected": false,
"text": "<p>You will need something like the <a href=\"https://en-ca.wordpress.org/plugins/multisite-user-role-manager/\" rel=\"nofollow noreferrer\">multisite role management plugin</a>. It allows you to define the user roles to have by default on a per blog basis, in a multisite setting</p>\n"
},
{
"answer_id": 251074,
"author": "CHEWX",
"author_id": 109779,
"author_profile": "https://wordpress.stackexchange.com/users/109779",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, so this isn't possible to do by default.</p>\n<p>As I already had a hook for <code>wpmu_activate_blog()</code> I just created another with a lower priority which will be fired after. This function also has the 2 parameters I need. So upon activation of the account I simply remove Admin role and set a new role based of the subscription service level.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'wpmu_activate_blog', array( $this,'set_new_user_role' ), 15, 2 );\n\npublic function set_new_user_role( $blog_id, $user_id ) {\n $user = new WP_User( $user_id, '', $blog_id );\n\n $user->remove_role( 'administrator' );\n\n // @NOTE - Set this role depending on user subscription level.\n $user->add_role( 'subscriber' );\n}\n</code></pre>\n"
}
] |
2017/01/02
|
[
"https://wordpress.stackexchange.com/questions/251049",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110062/"
] |
The theme I am using places the menu next to the logo (see the attached image). But I prefer to have the menu under the logo. How can I do it?
[](https://i.stack.imgur.com/HcHCa.png)
|
Ok, so this isn't possible to do by default.
As I already had a hook for `wpmu_activate_blog()` I just created another with a lower priority which will be fired after. This function also has the 2 parameters I need. So upon activation of the account I simply remove Admin role and set a new role based of the subscription service level.
```php
add_action( 'wpmu_activate_blog', array( $this,'set_new_user_role' ), 15, 2 );
public function set_new_user_role( $blog_id, $user_id ) {
$user = new WP_User( $user_id, '', $blog_id );
$user->remove_role( 'administrator' );
// @NOTE - Set this role depending on user subscription level.
$user->add_role( 'subscriber' );
}
```
|
251,076 |
<p>I recently made up simple Minecraft site about one starting server, instaled plugin called:Minestatus, and getting these errors. Exact same error for one other plugin.
I am running <strong>WP <em>3.19.4</em></strong></p>
<pre><code>Warning: Declaration of Minestatus_Widget::widget(array $args, $instance) should be compatible with WP_Widget::widget($args, $instance) in /data/web/virtuals/151993/virtual/www/domains/clashofcraft.eu/wp-content/plugins/minestatus/widget.php on line 6
Warning: Declaration of Minestatus_Widget::form(array $instance) should be compatible with WP_Widget::form($instance) in /data/web/virtuals/151993/virtual/www/domains/clashofcraft.eu/wp-content/plugins/minestatus/widget.php on line 6
</code></pre>
<p>Below is the code in widget.php</p>
<pre><code><?php
require dirname(__FILE__) . '/libs/Widgetize.php';
require dirname(__FILE__) . '/libs/ApiClient.php';
class Minestatus_Widget extends Widgetize
{
/**
* Construct
*/
public function __construct()
{
parent::__construct('Minestatus', array(
'title' => 'Server status',
'host' => 'server.yourserver.com',
'port' => '25565',
'show_status' => 'on',
'show_latency' => 'on',
'show_players_max' => 'on',
'show_players_online' => 'on',
'show_host' => 'on',
'show_ip' => 'on',
'show_port' => 'on',
'show_version' => 'on',
'show_protocol' => 'on',
));
}
/**
* @param array $args
* @param array $instance
*/
public function widget(array $args, $instance)
{
$instance = $this->hydrate($instance);
// Get ip if localhost
if (in_array($instance['host'], array('127.0.0.1', 'localhost'))) {
$instance['host'] = $_SERVER['SERVER_ADDR'];
}
$client = new ApiClient($instance['host'], $instance['port']);
$status = $client->call();
require dirname(__FILE__) . '/templates/widget.phtml';
}
/**
* @param array $instance
* @return string|void
*/
public function form(array $instance)
{
$instance = $this->hydrate($instance);
require dirname(__FILE__) . '/templates/form.phtml';
}
/**
* @param $newInstance
* @param $oldInstance
* @return array
*/
public function update($newInstance, $oldInstance)
{
$instance = array();
foreach ($newInstance as $option => $value) {
if((int) $value > 0 && !in_array($option, array('host'))) {
$value = (int) $value;
}
$instance[$option] = strip_tags(trim($value));
}
return $instance;
}
}
Widgetize::add('Minestatus_Widget');
</code></pre>
|
[
{
"answer_id": 251078,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>The class you should extend may be better <code>Widget</code> not <code>Widgetize</code>.</p>\n\n<pre><code>class Minestatus_Widget extends Widgetize\n</code></pre>\n"
},
{
"answer_id": 342812,
"author": "Jamy",
"author_id": 171280,
"author_profile": "https://wordpress.stackexchange.com/users/171280",
"pm_score": 1,
"selected": false,
"text": "<p>Remove \"array\" from your arguments declaration:</p>\n\n<p><code>public function widget(array $args, $instance)</code> should be <code>public function widget($args, $instance)</code></p>\n"
}
] |
2017/01/03
|
[
"https://wordpress.stackexchange.com/questions/251076",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110082/"
] |
I recently made up simple Minecraft site about one starting server, instaled plugin called:Minestatus, and getting these errors. Exact same error for one other plugin.
I am running **WP *3.19.4***
```
Warning: Declaration of Minestatus_Widget::widget(array $args, $instance) should be compatible with WP_Widget::widget($args, $instance) in /data/web/virtuals/151993/virtual/www/domains/clashofcraft.eu/wp-content/plugins/minestatus/widget.php on line 6
Warning: Declaration of Minestatus_Widget::form(array $instance) should be compatible with WP_Widget::form($instance) in /data/web/virtuals/151993/virtual/www/domains/clashofcraft.eu/wp-content/plugins/minestatus/widget.php on line 6
```
Below is the code in widget.php
```
<?php
require dirname(__FILE__) . '/libs/Widgetize.php';
require dirname(__FILE__) . '/libs/ApiClient.php';
class Minestatus_Widget extends Widgetize
{
/**
* Construct
*/
public function __construct()
{
parent::__construct('Minestatus', array(
'title' => 'Server status',
'host' => 'server.yourserver.com',
'port' => '25565',
'show_status' => 'on',
'show_latency' => 'on',
'show_players_max' => 'on',
'show_players_online' => 'on',
'show_host' => 'on',
'show_ip' => 'on',
'show_port' => 'on',
'show_version' => 'on',
'show_protocol' => 'on',
));
}
/**
* @param array $args
* @param array $instance
*/
public function widget(array $args, $instance)
{
$instance = $this->hydrate($instance);
// Get ip if localhost
if (in_array($instance['host'], array('127.0.0.1', 'localhost'))) {
$instance['host'] = $_SERVER['SERVER_ADDR'];
}
$client = new ApiClient($instance['host'], $instance['port']);
$status = $client->call();
require dirname(__FILE__) . '/templates/widget.phtml';
}
/**
* @param array $instance
* @return string|void
*/
public function form(array $instance)
{
$instance = $this->hydrate($instance);
require dirname(__FILE__) . '/templates/form.phtml';
}
/**
* @param $newInstance
* @param $oldInstance
* @return array
*/
public function update($newInstance, $oldInstance)
{
$instance = array();
foreach ($newInstance as $option => $value) {
if((int) $value > 0 && !in_array($option, array('host'))) {
$value = (int) $value;
}
$instance[$option] = strip_tags(trim($value));
}
return $instance;
}
}
Widgetize::add('Minestatus_Widget');
```
|
Remove "array" from your arguments declaration:
`public function widget(array $args, $instance)` should be `public function widget($args, $instance)`
|
251,081 |
<p>I'm not an expert at much, so please excuse me if this is an easy question... but it's got my head spinning.</p>
<p>I have an archive template (adapted from a standard 'enfold' theme template) which I am using to display a simple list of books. Following a tutorial I found elsewhere, I created the loop below.</p>
<p>If I understand the code correctly, the first part of the block below is used to fetch and sort the taxonomy values for the custom post type. So, it finds 'Romance', 'Horror', 'Humour' etc. It then displays posts with those taxonomy values together. So, I have a little table with a taxonomy value as a heading, and the posts with that taxonomy value in the table. Then I have a table for the next taxonomy type, and the relevant posts, one for each taxonomy value.</p>
<p>The 'orderby' in the original code sorts the taxonomy values by name.</p>
<p>It works perfectly, except the posts inside each 'taxonomy-table/group' are in random order, and I need to sort them by post title.</p>
<p>I want to sort the posts (inside their taxonomy-sorted tables) by title. How do I do this? I've tried copying every bit of code I can find on the subject but nothing has come close to working. </p>
<p>The loop used is;</p>
<pre><code><?php //start by fetching the terms for the booktype taxonomy
$terms = get_terms( 'booktype', array(
'orderby' => 'name',
'order' => 'DESC',
'hide_empty' => 0
) );
?>
<?php
foreach( $terms as $term ) {
// Define the query
$args = array(
'post_type' => 'fiction',
'booktype' => $term->slug
);
$query = new WP_Query( $args );
// output the book type in a heading tag
echo'<h4>Book Type ' . $term->name . '</h4>';
echo '<table>';
echo '<tr>';
echo '<th>Title</th>';
echo '<th>Author</th> ';
echo '<th>Published</th>';
echo '<th>ISBN</th>';
echo '<th>Sales</th>';
echo '</tr>';
while ( $query->have_posts() ) : $query->the_post();
?>
<tr>
<td><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></td>
<td><?php the_field( 'book-author' ); ?></td>
<td><?php the_field( 'book-published' ); ?></td>
<td><?php the_field( 'book-isbn' ); ?></td>
<td><?php the_field( 'book-sales' ); ?></td>
</tr>
<?php endwhile;
echo '</table>';
wp_reset_postdata();
} ?>
</code></pre>
<p>If I try to edit the array in the second block (below) and add an orderby to that, it appears to kill the first block. I just get empty tables with headings but no posts. </p>
<pre><code> // Define the query
$args = array(
'post_type' => 'fiction',
'booktype' => $term->slug
);
$query = new WP_Query( $args );
</code></pre>
<p>What else can I try?</p>
|
[
{
"answer_id": 251078,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>The class you should extend may be better <code>Widget</code> not <code>Widgetize</code>.</p>\n\n<pre><code>class Minestatus_Widget extends Widgetize\n</code></pre>\n"
},
{
"answer_id": 342812,
"author": "Jamy",
"author_id": 171280,
"author_profile": "https://wordpress.stackexchange.com/users/171280",
"pm_score": 1,
"selected": false,
"text": "<p>Remove \"array\" from your arguments declaration:</p>\n\n<p><code>public function widget(array $args, $instance)</code> should be <code>public function widget($args, $instance)</code></p>\n"
}
] |
2017/01/03
|
[
"https://wordpress.stackexchange.com/questions/251081",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110085/"
] |
I'm not an expert at much, so please excuse me if this is an easy question... but it's got my head spinning.
I have an archive template (adapted from a standard 'enfold' theme template) which I am using to display a simple list of books. Following a tutorial I found elsewhere, I created the loop below.
If I understand the code correctly, the first part of the block below is used to fetch and sort the taxonomy values for the custom post type. So, it finds 'Romance', 'Horror', 'Humour' etc. It then displays posts with those taxonomy values together. So, I have a little table with a taxonomy value as a heading, and the posts with that taxonomy value in the table. Then I have a table for the next taxonomy type, and the relevant posts, one for each taxonomy value.
The 'orderby' in the original code sorts the taxonomy values by name.
It works perfectly, except the posts inside each 'taxonomy-table/group' are in random order, and I need to sort them by post title.
I want to sort the posts (inside their taxonomy-sorted tables) by title. How do I do this? I've tried copying every bit of code I can find on the subject but nothing has come close to working.
The loop used is;
```
<?php //start by fetching the terms for the booktype taxonomy
$terms = get_terms( 'booktype', array(
'orderby' => 'name',
'order' => 'DESC',
'hide_empty' => 0
) );
?>
<?php
foreach( $terms as $term ) {
// Define the query
$args = array(
'post_type' => 'fiction',
'booktype' => $term->slug
);
$query = new WP_Query( $args );
// output the book type in a heading tag
echo'<h4>Book Type ' . $term->name . '</h4>';
echo '<table>';
echo '<tr>';
echo '<th>Title</th>';
echo '<th>Author</th> ';
echo '<th>Published</th>';
echo '<th>ISBN</th>';
echo '<th>Sales</th>';
echo '</tr>';
while ( $query->have_posts() ) : $query->the_post();
?>
<tr>
<td><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></td>
<td><?php the_field( 'book-author' ); ?></td>
<td><?php the_field( 'book-published' ); ?></td>
<td><?php the_field( 'book-isbn' ); ?></td>
<td><?php the_field( 'book-sales' ); ?></td>
</tr>
<?php endwhile;
echo '</table>';
wp_reset_postdata();
} ?>
```
If I try to edit the array in the second block (below) and add an orderby to that, it appears to kill the first block. I just get empty tables with headings but no posts.
```
// Define the query
$args = array(
'post_type' => 'fiction',
'booktype' => $term->slug
);
$query = new WP_Query( $args );
```
What else can I try?
|
Remove "array" from your arguments declaration:
`public function widget(array $args, $instance)` should be `public function widget($args, $instance)`
|
251,102 |
<p>Just another basic question of wordpress development.
I have a custom post created using the functions.php on theme folder that I am currently developing.
I simply want to display all post from it. </p>
<pre><code>function people() {
register_post_type( 'people',
array(
'labels' => array(
'name' => __( 'People' ),
'singular_name' => __( 'People' ),
),
'public' => true,
'has_archive' => true,
'supports' => array(
'title',
'editor',
'thumbnail',
'custom-fields'
)
));
}
add_action( 'init', 'people' );
</code></pre>
<p>That is the function I have to put it on the wp-admin.
and I tried to display it with this on <code>content-people.php</code> that is located in </p>
<p><code>theme/my-theme/content-templates/content-people.php</code></p>
<p>this is how I did it on my a section of my <code>index.php</code>: </p>
<pre><code><?php
if( have_posts( ) ): while( have_posts( ) ): the_post('people');
get_template_part( 'content-templates/content', 'people');
endwhile;
endif;
?>
</code></pre>
<p>and this is what I have on <code>**content-people.php</code> </p>
<pre><code><div class="col-lg-3 col-md-6 text-center">
<div class="service-box">
<i class="fa fa-4x fa-diamond text-primary sr-icons"></i>
<h3><?php the_title(); ?></h3>
</div>
</div>
</code></pre>
<p>But, it shows just the standard/default post from WordPress not the one that I have defined.
I have tried to find it on WordPress codex guide, but still cannot find the exact solution for it. </p>
|
[
{
"answer_id": 251078,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>The class you should extend may be better <code>Widget</code> not <code>Widgetize</code>.</p>\n\n<pre><code>class Minestatus_Widget extends Widgetize\n</code></pre>\n"
},
{
"answer_id": 342812,
"author": "Jamy",
"author_id": 171280,
"author_profile": "https://wordpress.stackexchange.com/users/171280",
"pm_score": 1,
"selected": false,
"text": "<p>Remove \"array\" from your arguments declaration:</p>\n\n<p><code>public function widget(array $args, $instance)</code> should be <code>public function widget($args, $instance)</code></p>\n"
}
] |
2017/01/03
|
[
"https://wordpress.stackexchange.com/questions/251102",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110106/"
] |
Just another basic question of wordpress development.
I have a custom post created using the functions.php on theme folder that I am currently developing.
I simply want to display all post from it.
```
function people() {
register_post_type( 'people',
array(
'labels' => array(
'name' => __( 'People' ),
'singular_name' => __( 'People' ),
),
'public' => true,
'has_archive' => true,
'supports' => array(
'title',
'editor',
'thumbnail',
'custom-fields'
)
));
}
add_action( 'init', 'people' );
```
That is the function I have to put it on the wp-admin.
and I tried to display it with this on `content-people.php` that is located in
`theme/my-theme/content-templates/content-people.php`
this is how I did it on my a section of my `index.php`:
```
<?php
if( have_posts( ) ): while( have_posts( ) ): the_post('people');
get_template_part( 'content-templates/content', 'people');
endwhile;
endif;
?>
```
and this is what I have on `**content-people.php`
```
<div class="col-lg-3 col-md-6 text-center">
<div class="service-box">
<i class="fa fa-4x fa-diamond text-primary sr-icons"></i>
<h3><?php the_title(); ?></h3>
</div>
</div>
```
But, it shows just the standard/default post from WordPress not the one that I have defined.
I have tried to find it on WordPress codex guide, but still cannot find the exact solution for it.
|
Remove "array" from your arguments declaration:
`public function widget(array $args, $instance)` should be `public function widget($args, $instance)`
|
251,111 |
<p>i have tags, and for some tags i want to load a different stylesheet
But i don't know how</p>
<p>i have....</p>
<pre><code>function customstyles()
{
if ( is_tag( 'circulair' ) ) {
//Register and enqueue the stylesheet for tag-circulair.
wp_register_style( 'tag-circulair', get_stylesheet_directory_uri() . '/layout-circulair' );
wp_enqueue_style( 'tag-circulair' );
} else {
//Register and enqueue the default stylesheet.
wp_register_style( 'styles', get_stylesheet_uri() );
wp_enqueue_style( 'styles' );
}
}
add_action( 'wp_enqueue_scripts', 'customstyles' );
</code></pre>
<p>But it won't do</p>
<p>Thanks Bets</p>
|
[
{
"answer_id": 251078,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>The class you should extend may be better <code>Widget</code> not <code>Widgetize</code>.</p>\n\n<pre><code>class Minestatus_Widget extends Widgetize\n</code></pre>\n"
},
{
"answer_id": 342812,
"author": "Jamy",
"author_id": 171280,
"author_profile": "https://wordpress.stackexchange.com/users/171280",
"pm_score": 1,
"selected": false,
"text": "<p>Remove \"array\" from your arguments declaration:</p>\n\n<p><code>public function widget(array $args, $instance)</code> should be <code>public function widget($args, $instance)</code></p>\n"
}
] |
2017/01/03
|
[
"https://wordpress.stackexchange.com/questions/251111",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109390/"
] |
i have tags, and for some tags i want to load a different stylesheet
But i don't know how
i have....
```
function customstyles()
{
if ( is_tag( 'circulair' ) ) {
//Register and enqueue the stylesheet for tag-circulair.
wp_register_style( 'tag-circulair', get_stylesheet_directory_uri() . '/layout-circulair' );
wp_enqueue_style( 'tag-circulair' );
} else {
//Register and enqueue the default stylesheet.
wp_register_style( 'styles', get_stylesheet_uri() );
wp_enqueue_style( 'styles' );
}
}
add_action( 'wp_enqueue_scripts', 'customstyles' );
```
But it won't do
Thanks Bets
|
Remove "array" from your arguments declaration:
`public function widget(array $args, $instance)` should be `public function widget($args, $instance)`
|
251,114 |
<p>I have a plugin that I do not want to be activated if it doesn't meet a certain WP version number then show error message in admin_notices action hook. As far as I have researched, the code below is the best that I can achieve this goal:</p>
<pre><code>$wp_version = get_bloginfo('version');
if ( $wp_version < 4.5 ) {
add_action( 'admin_init', 'deactivate_plugin_now' );
add_action( 'admin_notices', 'errormsg' ) );
}
public function deactivate_plugin_now() {
if ( is_plugin_active('myplugin/myplugin.php') ) {
deactivate_plugins('myplugin/myplugin.php');
}
}
public function errormsg () {
$class = 'notice notice-error';
$message = __( 'Error you did not meet the WP minimum version', 'text-domain' );
printf( '<div class="%1$s"><p>%2$s</p></div>', $class, $message );
}
</code></pre>
<p>But I think I am still doing it wrong because I'm getting the plugin activated message at the same time with the error notice that I assigned. </p>
<p><a href="https://i.stack.imgur.com/NkQtn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NkQtn.png" alt="Stop a plugin in the activation process when a certain WP version is not met"></a></p>
<p>What would be the proper action hook / filter to properly stop the plugin activation process so I will only get the error message?</p>
|
[
{
"answer_id": 251117,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Essentialy, you can not do it the way you want. All wordpress form are redirecting after completing their process and do not generate output by themself and therefor the error message is generated on a different page request. If your plugin will not be active at that point, there will be no message displayed.\nFurther complication is that plugins might be activated by Ajax.</p>\n\n<p>An ugly but working way is to fail the activation by generating an php error, or IIRC any output will do, so you can just output something like \"version mismatch\" in the plugin activation hook, which will be displayed in the error output box that is being displayed when activation fails.</p>\n\n<p>Something to think about: people might include your plugin files, or somehow activate it forcefully by bypassing the UI, or using wp-cli. depending on the reasons you want to fail the activation, just having the error message might be better than trying to fail the activation </p>\n"
},
{
"answer_id": 251124,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": false,
"text": "<p>How about this code to suppress hello.php (Hello Dolly) if WP < 8.5:</p>\n\n<pre><code> add_action( 'activate_plugin', '_20170113_superess_activate' , 10, 2);\n\n function _20170113_superess_activate($plugin, $network_wide){\n global $wp_version;\n\n if ( $wp_version < 8.5 && 'hello.php' == $plugin ) {\n error_log( 'WordPress need to be at least 8.5' ); \n $args = var_export( func_get_args(), true );\n error_log( $args );\n wp_die( 'WordPress need to be at least 8.5 to activate this plugin' );\n }\n }\n</code></pre>\n\n<p>I think this is good because it doesn't force you to create admin notices. You will simply get the feedback about the reason for abortion of the plugin install.</p>\n\n<p>I added this code for HelloDolly, but you will need to adjust.</p>\n"
},
{
"answer_id": 251172,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": false,
"text": "<p>Since you updated the title I need to provide the another answer, the previous one please don't ignore because it is even more simple than this one.</p>\n\n<pre><code>add_action( 'admin_notices', 'my_plugin_admin_notices' );\n\nfunction my_plugin_admin_notices() {\n if ( ! is_plugin_active( 'hello.php' ) && isset( $_GET['customhello'] ) ) {\n echo '<div class=\"error\"><p>WordPress need to be at least 8.5 to activate this plugin</p></div>';\n }\n}\n\nadd_action( 'activate_plugin', '_20170113_superess_activate', 10, 2 );\n\nfunction _20170113_superess_activate( $plugin, $network_wide ) {\n global $wp_version;\n if ( $wp_version < 8.5 && 'hello.php' == $plugin ) {\n $redirect = self_admin_url( 'plugins.php?customhello=1' );\n wp_redirect( $redirect );\n exit;\n }\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/1E8Xz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1E8Xz.png\" alt=\"enter image description here\"></a></p>\n\n<p>Please note that when you try to activate the plugin you interact with plugins.php file. In there you have a big switch of actions that you can run.</p>\n\n<p>And in case you have the error set <code>$_GET['error']</code> at the moment you have just the predefined error messages — you cannot create your own custom message. This is why I proposed you the solution like this.</p>\n\n<p><a href=\"https://i.stack.imgur.com/JabAH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JabAH.png\" alt=\"enter image description here\"></a></p>\n\n<p>One may propose the custom messages as admin notices to the WordPress core in cases plugins do not meet some requirements.</p>\n"
},
{
"answer_id": 296278,
"author": "Pascal Roget",
"author_id": 114505,
"author_profile": "https://wordpress.stackexchange.com/users/114505",
"pm_score": 3,
"selected": false,
"text": "<p>I may be late to this party, but to stop plugin activation and have WordPress show an error message where the admin notices go, I simply output an error message and terminate execution. This has the added advantage of playing nice with <a href=\"https://wp-cli.org/\" rel=\"noreferrer\">wp-cli</a>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/A93jt.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/A93jt.png\" alt=\"Plugin activation failed\"></a></p>\n\n<p>Example:</p>\n\n<pre><code>class testPlugin() {\n\n ...\n\n static function activate() {\n\n //[do some stuff here]\n\n if ($error) {\n die('Plugin NOT activated: ' . $error);\n }\n\n}\n\nregister_activation_hook( __FILE__, array( 'testPlugin', 'activate' ));\n</code></pre>\n"
},
{
"answer_id": 400560,
"author": "Suraj Wasnik",
"author_id": 146684,
"author_profile": "https://wordpress.stackexchange.com/users/146684",
"pm_score": 0,
"selected": false,
"text": "<p>I know I am too late to post the reply on this but it may help someone.\nYou could just unset the <code>$_GET</code> variable which triggers the message:</p>\n<pre><code>$wp_version = get_bloginfo('version');\nif ( $wp_version < 4.5 ) {\n add_action( 'admin_init', 'deactivate_plugin_now' );\n add_action( 'admin_notices', 'errormsg' ) );\n}\n\npublic function deactivate_plugin_now() {\n if ( is_plugin_active('myplugin/myplugin.php') ) {\n deactivate_plugins('myplugin/myplugin.php');\n unset($_GET['activate']);\n }\n}\n\npublic function errormsg () {\n $class = 'notice notice-error';\n $message = __( 'Error you did not meet the WP minimum version', 'text-domain' );\n printf( '<div class="%1$s"><p>%2$s</p></div>', $class, $message );\n}\n</code></pre>\n"
}
] |
2017/01/03
|
[
"https://wordpress.stackexchange.com/questions/251114",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60720/"
] |
I have a plugin that I do not want to be activated if it doesn't meet a certain WP version number then show error message in admin\_notices action hook. As far as I have researched, the code below is the best that I can achieve this goal:
```
$wp_version = get_bloginfo('version');
if ( $wp_version < 4.5 ) {
add_action( 'admin_init', 'deactivate_plugin_now' );
add_action( 'admin_notices', 'errormsg' ) );
}
public function deactivate_plugin_now() {
if ( is_plugin_active('myplugin/myplugin.php') ) {
deactivate_plugins('myplugin/myplugin.php');
}
}
public function errormsg () {
$class = 'notice notice-error';
$message = __( 'Error you did not meet the WP minimum version', 'text-domain' );
printf( '<div class="%1$s"><p>%2$s</p></div>', $class, $message );
}
```
But I think I am still doing it wrong because I'm getting the plugin activated message at the same time with the error notice that I assigned.
[](https://i.stack.imgur.com/NkQtn.png)
What would be the proper action hook / filter to properly stop the plugin activation process so I will only get the error message?
|
I may be late to this party, but to stop plugin activation and have WordPress show an error message where the admin notices go, I simply output an error message and terminate execution. This has the added advantage of playing nice with [wp-cli](https://wp-cli.org/):
[](https://i.stack.imgur.com/A93jt.png)
Example:
```
class testPlugin() {
...
static function activate() {
//[do some stuff here]
if ($error) {
die('Plugin NOT activated: ' . $error);
}
}
register_activation_hook( __FILE__, array( 'testPlugin', 'activate' ));
```
|
251,115 |
<p>The logo is being requested over http rather than https.</p>
<p>I assume this is the code affecting it:</p>
<pre><code><?php echo esc_url( home_url( '/' ) ); ?>
</code></pre>
<p>any advice would be appreciated</p>
|
[
{
"answer_id": 251117,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Essentialy, you can not do it the way you want. All wordpress form are redirecting after completing their process and do not generate output by themself and therefor the error message is generated on a different page request. If your plugin will not be active at that point, there will be no message displayed.\nFurther complication is that plugins might be activated by Ajax.</p>\n\n<p>An ugly but working way is to fail the activation by generating an php error, or IIRC any output will do, so you can just output something like \"version mismatch\" in the plugin activation hook, which will be displayed in the error output box that is being displayed when activation fails.</p>\n\n<p>Something to think about: people might include your plugin files, or somehow activate it forcefully by bypassing the UI, or using wp-cli. depending on the reasons you want to fail the activation, just having the error message might be better than trying to fail the activation </p>\n"
},
{
"answer_id": 251124,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": false,
"text": "<p>How about this code to suppress hello.php (Hello Dolly) if WP < 8.5:</p>\n\n<pre><code> add_action( 'activate_plugin', '_20170113_superess_activate' , 10, 2);\n\n function _20170113_superess_activate($plugin, $network_wide){\n global $wp_version;\n\n if ( $wp_version < 8.5 && 'hello.php' == $plugin ) {\n error_log( 'WordPress need to be at least 8.5' ); \n $args = var_export( func_get_args(), true );\n error_log( $args );\n wp_die( 'WordPress need to be at least 8.5 to activate this plugin' );\n }\n }\n</code></pre>\n\n<p>I think this is good because it doesn't force you to create admin notices. You will simply get the feedback about the reason for abortion of the plugin install.</p>\n\n<p>I added this code for HelloDolly, but you will need to adjust.</p>\n"
},
{
"answer_id": 251172,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": false,
"text": "<p>Since you updated the title I need to provide the another answer, the previous one please don't ignore because it is even more simple than this one.</p>\n\n<pre><code>add_action( 'admin_notices', 'my_plugin_admin_notices' );\n\nfunction my_plugin_admin_notices() {\n if ( ! is_plugin_active( 'hello.php' ) && isset( $_GET['customhello'] ) ) {\n echo '<div class=\"error\"><p>WordPress need to be at least 8.5 to activate this plugin</p></div>';\n }\n}\n\nadd_action( 'activate_plugin', '_20170113_superess_activate', 10, 2 );\n\nfunction _20170113_superess_activate( $plugin, $network_wide ) {\n global $wp_version;\n if ( $wp_version < 8.5 && 'hello.php' == $plugin ) {\n $redirect = self_admin_url( 'plugins.php?customhello=1' );\n wp_redirect( $redirect );\n exit;\n }\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/1E8Xz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1E8Xz.png\" alt=\"enter image description here\"></a></p>\n\n<p>Please note that when you try to activate the plugin you interact with plugins.php file. In there you have a big switch of actions that you can run.</p>\n\n<p>And in case you have the error set <code>$_GET['error']</code> at the moment you have just the predefined error messages — you cannot create your own custom message. This is why I proposed you the solution like this.</p>\n\n<p><a href=\"https://i.stack.imgur.com/JabAH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JabAH.png\" alt=\"enter image description here\"></a></p>\n\n<p>One may propose the custom messages as admin notices to the WordPress core in cases plugins do not meet some requirements.</p>\n"
},
{
"answer_id": 296278,
"author": "Pascal Roget",
"author_id": 114505,
"author_profile": "https://wordpress.stackexchange.com/users/114505",
"pm_score": 3,
"selected": false,
"text": "<p>I may be late to this party, but to stop plugin activation and have WordPress show an error message where the admin notices go, I simply output an error message and terminate execution. This has the added advantage of playing nice with <a href=\"https://wp-cli.org/\" rel=\"noreferrer\">wp-cli</a>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/A93jt.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/A93jt.png\" alt=\"Plugin activation failed\"></a></p>\n\n<p>Example:</p>\n\n<pre><code>class testPlugin() {\n\n ...\n\n static function activate() {\n\n //[do some stuff here]\n\n if ($error) {\n die('Plugin NOT activated: ' . $error);\n }\n\n}\n\nregister_activation_hook( __FILE__, array( 'testPlugin', 'activate' ));\n</code></pre>\n"
},
{
"answer_id": 400560,
"author": "Suraj Wasnik",
"author_id": 146684,
"author_profile": "https://wordpress.stackexchange.com/users/146684",
"pm_score": 0,
"selected": false,
"text": "<p>I know I am too late to post the reply on this but it may help someone.\nYou could just unset the <code>$_GET</code> variable which triggers the message:</p>\n<pre><code>$wp_version = get_bloginfo('version');\nif ( $wp_version < 4.5 ) {\n add_action( 'admin_init', 'deactivate_plugin_now' );\n add_action( 'admin_notices', 'errormsg' ) );\n}\n\npublic function deactivate_plugin_now() {\n if ( is_plugin_active('myplugin/myplugin.php') ) {\n deactivate_plugins('myplugin/myplugin.php');\n unset($_GET['activate']);\n }\n}\n\npublic function errormsg () {\n $class = 'notice notice-error';\n $message = __( 'Error you did not meet the WP minimum version', 'text-domain' );\n printf( '<div class="%1$s"><p>%2$s</p></div>', $class, $message );\n}\n</code></pre>\n"
}
] |
2017/01/03
|
[
"https://wordpress.stackexchange.com/questions/251115",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110112/"
] |
The logo is being requested over http rather than https.
I assume this is the code affecting it:
```
<?php echo esc_url( home_url( '/' ) ); ?>
```
any advice would be appreciated
|
I may be late to this party, but to stop plugin activation and have WordPress show an error message where the admin notices go, I simply output an error message and terminate execution. This has the added advantage of playing nice with [wp-cli](https://wp-cli.org/):
[](https://i.stack.imgur.com/A93jt.png)
Example:
```
class testPlugin() {
...
static function activate() {
//[do some stuff here]
if ($error) {
die('Plugin NOT activated: ' . $error);
}
}
register_activation_hook( __FILE__, array( 'testPlugin', 'activate' ));
```
|
251,116 |
<p>I want to work with WordPress multisite, but I want to be able to use my own names. For example my main site is called <code>example.com</code>. If I want to add a new site to my multisite network it's gonna be called <code>newsite.example.com</code>. I want it to be <code>newsite.com</code> without <code>example</code>. Is there a way to achieve this? </p>
<p>I heard about domain mapping with a plugin, but I dont know if this is relevant to this question. If it is relevant I would like to know what exactly this is.</p>
|
[
{
"answer_id": 251120,
"author": "David",
"author_id": 31323,
"author_profile": "https://wordpress.stackexchange.com/users/31323",
"pm_score": 3,
"selected": false,
"text": "<p>It was made possible without using a plugin a few releases ago (can't remember the concrete release but the feature has been there for a while now). However, if you start from scratch, you should install WordPress multisite in the <em>subdomain</em> mode.</p>\n<p>You have to declare a main URL (probably <code>kevin123.example</code>) as the main URL for the network (multisite). This is stored in <code>wp-config.php</code> in the <code>DOMAIN_CURRENT_SITE</code> constant and the site (formerly known as »blog«) using this domain as home URL must have the ID stored in <code>BLOG_ID_CURRENT_SITE</code>. But this is pretty much default stuff during the standard installation process.</p>\n<p>WordPress allows you only to specify the sub-domain, <em>when you create</em> a new site. But after the site is created you can edit it and add a completely arbitrary value for the site URL. I described it some time ago in this answer with some screenshots: <a href=\"https://wordpress.stackexchange.com/questions/140767/are-nested-subdomains-possible-with-a-subdomain-multisite/184667#184667\">Are nested subdomains possible with a subdomain multisite?</a></p>\n<p>You might also need to set the constant <code>COOKIE_DOMAN</code> to an empty value in your <code>wp-config.php</code>:</p>\n<pre><code>define( 'COOKIE_DOMAIN', '' );\n</code></pre>\n"
},
{
"answer_id": 251146,
"author": "Michael Ecklund",
"author_id": 9579,
"author_profile": "https://wordpress.stackexchange.com/users/9579",
"pm_score": 6,
"selected": true,
"text": "<p>There seems to always be a bit on confusion on this topic. Perhaps WordPress could do a better job guiding it's users in this process. Although, I suppose Multi-site wasn't intended to be used for TLD's.</p>\n<p>So first of all, I would <a href=\"https://codex.wordpress.org/Installing_WordPress\" rel=\"nofollow noreferrer\">install WordPress</a>, <a href=\"https://wordpress.org/support/article/create-a-network/\" rel=\"nofollow noreferrer\">setup multisite</a>, and configure it as a subdomain network configuration.</p>\n<p>Here's a sample configuration for your <code>wp-config.php</code> file in the base directory of your WordPress installation:</p>\n<pre><code>/* Multisite */\ndefine( 'WP_ALLOW_MULTISITE', true );\ndefine( 'MULTISITE', true );\ndefine( 'SUBDOMAIN_INSTALL', true );\ndefine( 'DOMAIN_CURRENT_SITE', 'www.primary-domain.example' );\ndefine( 'PATH_CURRENT_SITE', '/' );\ndefine( 'SITE_ID_CURRENT_SITE', 1 );\ndefine( 'BLOG_ID_CURRENT_SITE', 1 );\n</code></pre>\n<p>Then, here's the basic configuration for your <code>.htaccess</code> file as a subdomain configuration, in the base directory of your WordPress installation:</p>\n<pre><code># BoF WordPress\n\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\n\n# add a trailing slash to /wp-admin\nRewriteRule ^wp-admin$ wp-admin/ [R=301,L]\n\nRewriteCond %{REQUEST_FILENAME} -f [OR]\nRewriteCond %{REQUEST_FILENAME} -d\nRewriteRule ^ - [L]\nRewriteRule ^(wp-(content|admin|includes).*) $1 [L]\nRewriteRule ^(.*\\.php)$ $1 [L]\nRewriteRule . index.php [L]\n\n# EoF WordPress\n</code></pre>\n<p>Now in order to get TLD's to work properly, I've had to make some additional configurations to the <code>wp-config.php</code> file like this:</p>\n<pre><code>define( 'COOKIE_DOMAIN', '' );\ndefine( 'ADMIN_COOKIE_PATH', '/' );\ndefine( 'COOKIEPATH', '/' );\ndefine( 'SITECOOKIEPATH', '/' );\n</code></pre>\n<p>That's it with the WordPress specific configurations.</p>\n<p>Personally, I like to have one Apache Virtual Host for the primary domain in the network and then configure that virtual host with alias domains. Each alias domain being one of the additional sites in your network.</p>\n<p>However you end up tweaking your setup, you need each domain's DNS to resolve to the same web server, and each domain to be pointed to the same directory the primary domain is installed with WordPress. Each domain in your network needs to point to the same web server with DNS records and share the same directory path for the files used by WordPress.</p>\n<p>Once you've got everything configured and setup properly as discussed above. Log into your WordPress administration area and navigate to the Network administration area to add a new site into your network.</p>\n<p>When you go to add a site, it will enforce you to add the website as if it were a sub domain under your primary domain. Just roll with it. Enter something temporary.</p>\n<p>Once the site has been added, then go find it under the list of sites in your network. Click edit on that specific site. Now, you can fully 100% change the domain name of that website. That's when you would put the actual domain name for this TLD site.</p>\n<p>I know it's a bit of trickery to do it that way, but it works and you don't need to use any plugins.</p>\n"
},
{
"answer_id": 359508,
"author": "rxmd",
"author_id": 183380,
"author_profile": "https://wordpress.stackexchange.com/users/183380",
"pm_score": 3,
"selected": false,
"text": "<p>WordPress now has a <a href=\"https://wordpress.org/support/article/wordpress-multisite-domain-mapping/\" rel=\"noreferrer\">support article</a> on this. Essentially the recommended steps are as outlined by David & Michael:</p>\n\n<ol>\n<li>Map the domain name in DNS to your server</li>\n<li>Make sure this domain is registered on your server with a virtual host pointing to the WordPress directory</li>\n<li>Generate and install a SSL certificate on your server that includes the intended domain (technically this is optional, but restricting users to HTTP is not a good idea, and is now regularly punished by bad SEO scores)</li>\n<li>Update the site URL in your WordPress blog to point to the new domain</li>\n<li>If problems with cookies persist, define the <code>COOKIE_DOMAIN</code> in <code>wp-config.php</code>. </li>\n</ol>\n\n<p>The main difference is that instead of leaving the cookie domain empty (<code>define( 'COOKIE_DOMAIN', '' );</code>), they recommend filling in the domain to which the HTTP request went:</p>\n\n<pre><code>define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST']);\n</code></pre>\n\n<p>This helps avoid cookie issues with multisite installations under different domain names, especially for subdirectory installations.</p>\n"
}
] |
2017/01/03
|
[
"https://wordpress.stackexchange.com/questions/251116",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102796/"
] |
I want to work with WordPress multisite, but I want to be able to use my own names. For example my main site is called `example.com`. If I want to add a new site to my multisite network it's gonna be called `newsite.example.com`. I want it to be `newsite.com` without `example`. Is there a way to achieve this?
I heard about domain mapping with a plugin, but I dont know if this is relevant to this question. If it is relevant I would like to know what exactly this is.
|
There seems to always be a bit on confusion on this topic. Perhaps WordPress could do a better job guiding it's users in this process. Although, I suppose Multi-site wasn't intended to be used for TLD's.
So first of all, I would [install WordPress](https://codex.wordpress.org/Installing_WordPress), [setup multisite](https://wordpress.org/support/article/create-a-network/), and configure it as a subdomain network configuration.
Here's a sample configuration for your `wp-config.php` file in the base directory of your WordPress installation:
```
/* Multisite */
define( 'WP_ALLOW_MULTISITE', true );
define( 'MULTISITE', true );
define( 'SUBDOMAIN_INSTALL', true );
define( 'DOMAIN_CURRENT_SITE', 'www.primary-domain.example' );
define( 'PATH_CURRENT_SITE', '/' );
define( 'SITE_ID_CURRENT_SITE', 1 );
define( 'BLOG_ID_CURRENT_SITE', 1 );
```
Then, here's the basic configuration for your `.htaccess` file as a subdomain configuration, in the base directory of your WordPress installation:
```
# BoF WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# add a trailing slash to /wp-admin
RewriteRule ^wp-admin$ wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule . index.php [L]
# EoF WordPress
```
Now in order to get TLD's to work properly, I've had to make some additional configurations to the `wp-config.php` file like this:
```
define( 'COOKIE_DOMAIN', '' );
define( 'ADMIN_COOKIE_PATH', '/' );
define( 'COOKIEPATH', '/' );
define( 'SITECOOKIEPATH', '/' );
```
That's it with the WordPress specific configurations.
Personally, I like to have one Apache Virtual Host for the primary domain in the network and then configure that virtual host with alias domains. Each alias domain being one of the additional sites in your network.
However you end up tweaking your setup, you need each domain's DNS to resolve to the same web server, and each domain to be pointed to the same directory the primary domain is installed with WordPress. Each domain in your network needs to point to the same web server with DNS records and share the same directory path for the files used by WordPress.
Once you've got everything configured and setup properly as discussed above. Log into your WordPress administration area and navigate to the Network administration area to add a new site into your network.
When you go to add a site, it will enforce you to add the website as if it were a sub domain under your primary domain. Just roll with it. Enter something temporary.
Once the site has been added, then go find it under the list of sites in your network. Click edit on that specific site. Now, you can fully 100% change the domain name of that website. That's when you would put the actual domain name for this TLD site.
I know it's a bit of trickery to do it that way, but it works and you don't need to use any plugins.
|
251,121 |
<p>I am wondering how to make a Link "Go to first post" While I have opened some post?</p>
<p>Any suggestion is welcome.</p>
<p>Thank you.</p>
|
[
{
"answer_id": 251125,
"author": "Mostafa Soufi",
"author_id": 106877,
"author_profile": "https://wordpress.stackexchange.com/users/106877",
"pm_score": 0,
"selected": false,
"text": "<p>Using bellow function in your theme for get first post link.</p>\n\n<pre><code><?php\nfunction get_first_post_link() {\n global $wpdb, $table_prefix;\n $result = $wpdb->get_row(\"select * from {$table_prefix}posts where post_type = 'post' and post_status = 'publish' ORDER BY `{$table_prefix}posts`.`ID` ASC LIMIT 1\");\n if($result) {\n return get_permalink( $result->ID );\n }\n}\n\necho get_first_post_link();\n</code></pre>\n"
},
{
"answer_id": 251128,
"author": "Magnus Guyra",
"author_id": 110059,
"author_profile": "https://wordpress.stackexchange.com/users/110059",
"pm_score": 2,
"selected": true,
"text": "<p>I'll assume by \"first\" you mean \"newest\", since if it's the oldest, then all you'd need would be the url of that post.</p>\n\n<pre><code>$latest = get_posts(array('numberposts' => 1));\n$url = get_permalink($latest[0]->ID);\necho \"<a href='\" . $url . \"'>Go to first post</a>\";\n</code></pre>\n\n<p>This should give you a link that always goes to whatever is the latest post on your site. Where you add the code is dependant on your theme, as well as your personal preferences.</p>\n"
}
] |
2017/01/03
|
[
"https://wordpress.stackexchange.com/questions/251121",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101369/"
] |
I am wondering how to make a Link "Go to first post" While I have opened some post?
Any suggestion is welcome.
Thank you.
|
I'll assume by "first" you mean "newest", since if it's the oldest, then all you'd need would be the url of that post.
```
$latest = get_posts(array('numberposts' => 1));
$url = get_permalink($latest[0]->ID);
echo "<a href='" . $url . "'>Go to first post</a>";
```
This should give you a link that always goes to whatever is the latest post on your site. Where you add the code is dependant on your theme, as well as your personal preferences.
|
251,129 |
<p>I have tried ticking comments and discussion but still don't seem to have a comments box. Even went through and ticked individually for each post. Help!</p>
|
[
{
"answer_id": 251125,
"author": "Mostafa Soufi",
"author_id": 106877,
"author_profile": "https://wordpress.stackexchange.com/users/106877",
"pm_score": 0,
"selected": false,
"text": "<p>Using bellow function in your theme for get first post link.</p>\n\n<pre><code><?php\nfunction get_first_post_link() {\n global $wpdb, $table_prefix;\n $result = $wpdb->get_row(\"select * from {$table_prefix}posts where post_type = 'post' and post_status = 'publish' ORDER BY `{$table_prefix}posts`.`ID` ASC LIMIT 1\");\n if($result) {\n return get_permalink( $result->ID );\n }\n}\n\necho get_first_post_link();\n</code></pre>\n"
},
{
"answer_id": 251128,
"author": "Magnus Guyra",
"author_id": 110059,
"author_profile": "https://wordpress.stackexchange.com/users/110059",
"pm_score": 2,
"selected": true,
"text": "<p>I'll assume by \"first\" you mean \"newest\", since if it's the oldest, then all you'd need would be the url of that post.</p>\n\n<pre><code>$latest = get_posts(array('numberposts' => 1));\n$url = get_permalink($latest[0]->ID);\necho \"<a href='\" . $url . \"'>Go to first post</a>\";\n</code></pre>\n\n<p>This should give you a link that always goes to whatever is the latest post on your site. Where you add the code is dependant on your theme, as well as your personal preferences.</p>\n"
}
] |
2017/01/03
|
[
"https://wordpress.stackexchange.com/questions/251129",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110119/"
] |
I have tried ticking comments and discussion but still don't seem to have a comments box. Even went through and ticked individually for each post. Help!
|
I'll assume by "first" you mean "newest", since if it's the oldest, then all you'd need would be the url of that post.
```
$latest = get_posts(array('numberposts' => 1));
$url = get_permalink($latest[0]->ID);
echo "<a href='" . $url . "'>Go to first post</a>";
```
This should give you a link that always goes to whatever is the latest post on your site. Where you add the code is dependant on your theme, as well as your personal preferences.
|
251,130 |
<p>I'm experiencing something really strange, that I just can't seem to figure out. I'm busy writing my own theme. It's nothing special or super advanced, just wanted a fun project and get a little custom. </p>
<p>On the homepage, I want the posts displayed in a masonry style, pinterest clone card UI. I've set up the HTML and the CSS using Foundation. Everything works 100% as it's supposed to before I use the WP loop to pull in posts. </p>
<p>Here is how it look when I hardcode the HTML: </p>
<p><a href="https://i.stack.imgur.com/B3y8x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B3y8x.png" alt="Hardcoded HTML"></a></p>
<p>Here is how it looks when I use the WP loop to pull in from content.php:</p>
<p><a href="https://i.stack.imgur.com/H3Dq8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H3Dq8.png" alt="With WP Loop"></a></p>
<p>I've also moved the contents of content.php inside the loop on index.php, and I get the same issue. Can't really figure this out. </p>
<p>Home Page Code: </p>
<pre><code><?php get_header(); ?>
<div class="row" id="content">
<div class="medium-9 columns">
<article>
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part( 'content' );
endwhile;
else :
echo wpautop( 'Sorry, no posts were found' );
endif;
?>
</article>
</div>
<?php get_sidebar(); ?>
</div><!-- End row-->
</code></pre>
<p>Content Code: </p>
<pre><code><section class="animated fadeIn">
<div class="ribbon"><span>Eat This</span></div>
<img src="<?php echo the_post_thumbnail(); ?>" />
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
<div class="cats-block">
<?php
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
echo '<span class="category label">' . $tag->name . '</span> ';
}
}
?>
</div>
</code></pre>
<p></p>
<p>CSS: </p>
<pre><code>.bob article {
-moz-column-width: 13em;
-webkit-column-width: 13em;
column-width: 13em;
-moz-column-gap: 1em;
-webkit-column-gap: 1em;
column-gap: 1em;
}
.bob section {
position: relative;
display: inline-block;
margin: 0.25rem;
padding: 1rem;
width: 100%;
background: #E5E5E5;
border-radius: 5px;
}
</code></pre>
<p>Getting a little frustrated. Any help would be much appreciated. </p>
|
[
{
"answer_id": 251125,
"author": "Mostafa Soufi",
"author_id": 106877,
"author_profile": "https://wordpress.stackexchange.com/users/106877",
"pm_score": 0,
"selected": false,
"text": "<p>Using bellow function in your theme for get first post link.</p>\n\n<pre><code><?php\nfunction get_first_post_link() {\n global $wpdb, $table_prefix;\n $result = $wpdb->get_row(\"select * from {$table_prefix}posts where post_type = 'post' and post_status = 'publish' ORDER BY `{$table_prefix}posts`.`ID` ASC LIMIT 1\");\n if($result) {\n return get_permalink( $result->ID );\n }\n}\n\necho get_first_post_link();\n</code></pre>\n"
},
{
"answer_id": 251128,
"author": "Magnus Guyra",
"author_id": 110059,
"author_profile": "https://wordpress.stackexchange.com/users/110059",
"pm_score": 2,
"selected": true,
"text": "<p>I'll assume by \"first\" you mean \"newest\", since if it's the oldest, then all you'd need would be the url of that post.</p>\n\n<pre><code>$latest = get_posts(array('numberposts' => 1));\n$url = get_permalink($latest[0]->ID);\necho \"<a href='\" . $url . \"'>Go to first post</a>\";\n</code></pre>\n\n<p>This should give you a link that always goes to whatever is the latest post on your site. Where you add the code is dependant on your theme, as well as your personal preferences.</p>\n"
}
] |
2017/01/03
|
[
"https://wordpress.stackexchange.com/questions/251130",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110118/"
] |
I'm experiencing something really strange, that I just can't seem to figure out. I'm busy writing my own theme. It's nothing special or super advanced, just wanted a fun project and get a little custom.
On the homepage, I want the posts displayed in a masonry style, pinterest clone card UI. I've set up the HTML and the CSS using Foundation. Everything works 100% as it's supposed to before I use the WP loop to pull in posts.
Here is how it look when I hardcode the HTML:
[](https://i.stack.imgur.com/B3y8x.png)
Here is how it looks when I use the WP loop to pull in from content.php:
[](https://i.stack.imgur.com/H3Dq8.png)
I've also moved the contents of content.php inside the loop on index.php, and I get the same issue. Can't really figure this out.
Home Page Code:
```
<?php get_header(); ?>
<div class="row" id="content">
<div class="medium-9 columns">
<article>
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part( 'content' );
endwhile;
else :
echo wpautop( 'Sorry, no posts were found' );
endif;
?>
</article>
</div>
<?php get_sidebar(); ?>
</div><!-- End row-->
```
Content Code:
```
<section class="animated fadeIn">
<div class="ribbon"><span>Eat This</span></div>
<img src="<?php echo the_post_thumbnail(); ?>" />
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
<div class="cats-block">
<?php
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
echo '<span class="category label">' . $tag->name . '</span> ';
}
}
?>
</div>
```
CSS:
```
.bob article {
-moz-column-width: 13em;
-webkit-column-width: 13em;
column-width: 13em;
-moz-column-gap: 1em;
-webkit-column-gap: 1em;
column-gap: 1em;
}
.bob section {
position: relative;
display: inline-block;
margin: 0.25rem;
padding: 1rem;
width: 100%;
background: #E5E5E5;
border-radius: 5px;
}
```
Getting a little frustrated. Any help would be much appreciated.
|
I'll assume by "first" you mean "newest", since if it's the oldest, then all you'd need would be the url of that post.
```
$latest = get_posts(array('numberposts' => 1));
$url = get_permalink($latest[0]->ID);
echo "<a href='" . $url . "'>Go to first post</a>";
```
This should give you a link that always goes to whatever is the latest post on your site. Where you add the code is dependant on your theme, as well as your personal preferences.
|
251,132 |
<p>Is there a way to get posts from a custom taxonomy <strong>without specifying a term</strong>?</p>
<p>I have a custom taxonomy called <code>media_category</code> and I want to get all the attachments which use this taxonomy since I have some attachments which doesnt use this taxonomy at all.</p>
|
[
{
"answer_id": 251143,
"author": "codiiv",
"author_id": 91561,
"author_profile": "https://wordpress.stackexchange.com/users/91561",
"pm_score": 0,
"selected": false,
"text": "<p>You need to create a taxonomy archive by doing something like this: </p>\n\n<p>1) In the theme directory create a file named <strong>taxonomy-media_category.php</strong> with the archive loop like... </p>\n\n<pre><code><?php\nget_header(); ?>\n\n<div id=\"container\">\n <div id=\"content\" role=\"main\">\n\n <?php the_post(); ?>\n <h1 class=\"entry-title\"><?php the_title(); ?></h1>\n\n <?php get_search_form(); ?>\n\n <h2>Archives by Month:</h2>\n <ul>\n <?php //SOME OF YOUR CODE HERE ?>\n </ul>\n\n </div><!-- #content -->\n<?php get_sidebar(); ?>\n<?php get_footer(); ?>\n</code></pre>\n\n<p>2) In the loop, you can change the code as needed</p>\n"
},
{
"answer_id": 251163,
"author": "Pro Wordpress Development",
"author_id": 103849,
"author_profile": "https://wordpress.stackexchange.com/users/103849",
"pm_score": 1,
"selected": false,
"text": "<p>You may do it by this method.</p>\n\n<hr>\n\n<p><pre>\n\n\n<p>$media_category = get_terms('media_category');\nforeach($media_category as $cat) {\n wp_reset_query();\n $args = array('post_type' => 'your_post_type',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'media_category',\n 'field' => 'slug',\n 'terms' => $cat->slug,\n ),\n ),\n );\n $loop = new WP_Query($args);\n if($loop->have_posts()) {\n // echo $cat->name;\n while($loop->have_posts()) : $loop->the_post();\n echo get_the_title();\n endwhile;\n }\n} </pre></p>\n"
},
{
"answer_id": 251166,
"author": "dheeraj Kumar",
"author_id": 110140,
"author_profile": "https://wordpress.stackexchange.com/users/110140",
"pm_score": 1,
"selected": false,
"text": "<pre><code><?php\n$args = array(\n 'post_type' => 'product',\n 'post_status' => 'publish',\n 'posts_per_page' => -1,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'taxonomy_name',\n 'field' => 'id',\n 'terms' => '22'\n )\n )\n);\n$the_query = new WP_Query( $args );\nwhile ( $the_query->have_posts() ) : $the_query->the_post();\n //content\nendwhile;\n?>\n</code></pre>\n\n<p><a href=\"http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">more check out here about Taxonomy Parameters </a></p>\n"
},
{
"answer_id": 251250,
"author": "Broshi",
"author_id": 110123,
"author_profile": "https://wordpress.stackexchange.com/users/110123",
"pm_score": 0,
"selected": false,
"text": "<p>Eventually I used this:</p>\n\n<pre><code>$taxonomy = 'MY_TAXONOMY_HERE';\n\n// Get all the terms of that taxonomy\n$terms = get_terms( $taxonomy, 'orderby=count&hide_empty=1' );\n\n$args = array_merge( $args, [\n 'tax_query' => array(\n array(\n 'taxonomy' => $taxonomy,\n 'field' => 'id',\n 'terms' => wp_list_pluck( $terms, 'term_id' )\n )\n )\n]);\n\n$query = new WP_Query( $args );\n</code></pre>\n"
}
] |
2017/01/03
|
[
"https://wordpress.stackexchange.com/questions/251132",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110123/"
] |
Is there a way to get posts from a custom taxonomy **without specifying a term**?
I have a custom taxonomy called `media_category` and I want to get all the attachments which use this taxonomy since I have some attachments which doesnt use this taxonomy at all.
|
You may do it by this method.
---
```
$media\_category = get\_terms('media\_category');
foreach($media\_category as $cat) {
wp\_reset\_query();
$args = array('post\_type' => 'your\_post\_type',
'tax\_query' => array(
array(
'taxonomy' => 'media\_category',
'field' => 'slug',
'terms' => $cat->slug,
),
),
);
$loop = new WP\_Query($args);
if($loop->have\_posts()) {
// echo $cat->name;
while($loop->have\_posts()) : $loop->the\_post();
echo get\_the\_title();
endwhile;
}
}
```
|
251,140 |
<p>Is there a way to avoid WordPress "flattening" the category tree when a child category is selected?</p>
<p>This applies to both custom taxonomies and WP's built in "category" taxonomy.</p>
<p>To explain further, say I have the following category tree:</p>
<pre><code>Parent
Child
Grandchild
Another parent
Another child
Another child
A third parent
</code></pre>
<p>If I then select "Grandchild" as my category, the tree will now look like this upon saving:</p>
<pre><code>Grandchild
Parent
Child
Another parent
Another child
Another child
A third parent
</code></pre>
<p>This makes it very hard for authors to remember which grandchild belongs to which parent and imo makes absolutely zero sense. I guess one reason for this might be so that the selected category is always in the top of the list, but I would very much like to disable this behaviour.</p>
<p>Also see attached image.</p>
<p><a href="https://i.stack.imgur.com/ij4al.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ij4al.png" alt="Flattened Categories"></a></p>
<p>Please note that this is not theme or plugin-related. I tried this with a completely fresh WP-install with zero plugins and the default theme.</p>
|
[
{
"answer_id": 251159,
"author": "Leora Deans",
"author_id": 94243,
"author_profile": "https://wordpress.stackexchange.com/users/94243",
"pm_score": 3,
"selected": true,
"text": "<p>I haven't fully tested this, but it may be helpful:\nCategories in Hierarchical Order plugin at <a href=\"https://wordpress.org/plugins/categories-in-hierarchical-order/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/categories-in-hierarchical-order/</a></p>\n"
},
{
"answer_id": 332858,
"author": "SequenceDigitale.com",
"author_id": 147338,
"author_profile": "https://wordpress.stackexchange.com/users/147338",
"pm_score": 3,
"selected": false,
"text": "<p>The plugin can be resumed to this simple code:</p>\n\n<pre><code>add_filter( 'wp_terms_checklist_args', function( $args ) {\n $args['checked_ontop'] = false;\n return $args;\n});\n</code></pre>\n"
}
] |
2017/01/03
|
[
"https://wordpress.stackexchange.com/questions/251140",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23714/"
] |
Is there a way to avoid WordPress "flattening" the category tree when a child category is selected?
This applies to both custom taxonomies and WP's built in "category" taxonomy.
To explain further, say I have the following category tree:
```
Parent
Child
Grandchild
Another parent
Another child
Another child
A third parent
```
If I then select "Grandchild" as my category, the tree will now look like this upon saving:
```
Grandchild
Parent
Child
Another parent
Another child
Another child
A third parent
```
This makes it very hard for authors to remember which grandchild belongs to which parent and imo makes absolutely zero sense. I guess one reason for this might be so that the selected category is always in the top of the list, but I would very much like to disable this behaviour.
Also see attached image.
[](https://i.stack.imgur.com/ij4al.png)
Please note that this is not theme or plugin-related. I tried this with a completely fresh WP-install with zero plugins and the default theme.
|
I haven't fully tested this, but it may be helpful:
Categories in Hierarchical Order plugin at <https://wordpress.org/plugins/categories-in-hierarchical-order/>
|
251,141 |
<p>I am using this css code on my theme in order to get the styling under an image in a post:</p>
<pre><code>.wp-caption .wp-caption-text {
font-size: 16px !important;
color: #000000;
text-align: center;
background-color: #F2F2F2;
padding-top: 1px;
margin: 1px;
}
</code></pre>
<p>When using it on mobile, the text is to big, and does not reduce size as the rest of the content. Any tips to how I can fix this? Maybe a media query in the code? How would the code look then?</p>
<p>Thanks a lot for all help!</p>
|
[
{
"answer_id": 251155,
"author": "iguanarama",
"author_id": 109807,
"author_profile": "https://wordpress.stackexchange.com/users/109807",
"pm_score": 0,
"selected": false,
"text": "<p>Here are the principles of what's probably going on. (Fixing it without guesswork would require access to all your CSS.)</p>\n\n<p>If (most of) your font sizes are automatically reducing on mobile, then you probably already have a media query in your CSS, something like this:</p>\n\n<pre><code>@media only screen and (max-width: 768px) {\n [some kind of CSS specifying font size]\n}\n</code></pre>\n\n<p>This lets you specify CSS variations specifically for devices with a max width of 768px, so most cellphones and portrait tablets.</p>\n\n<p>However, you have <code>!important</code> after your <code>font-size</code> for <code>.wp-caption .wp-caption-text</code>. This basically tells the browser to ignore any other CSS rules that would normally override it: your caption will be that font size, no matter what—and that includes ignoring any CSS that adjusts the font for mobile devices. <code>!important</code> is an ugly hack, and rarely needed.</p>\n\n<p>So how to fix it? You first need to remove <code>!important</code> from your <code>.wp-caption .wp-caption-text</code>. If your caption font size is no longer 16px on a standard desktop view, you need to find out which CSS rule is overriding it. One way is to use a live inspector in a browser, like Safari's web inspector (Command-Shift-I on any page, after Preferences > Advanced > Show develop menu), and investigate where it's getting the font size from. Alternatively, look through your CSS and see if a font size for captions is specified more specifically (e.g. <code>body #my-main-div .wp-caption .wp-caption-text</code>).</p>\n\n<p>Once you've found the culprit, and your font size is now 16px for captions on desktop view, then you can add a different captions font size to your <code>@media</code> query for mobile, and you should be all set.</p>\n"
},
{
"answer_id": 251161,
"author": "Pro Wordpress Development",
"author_id": 103849,
"author_profile": "https://wordpress.stackexchange.com/users/103849",
"pm_score": 0,
"selected": false,
"text": "<p>You can use css as below </p>\n\n<pre><code>@media screen and (max-width:480px) { \n .wp-caption .wp-caption-text { font-size: 14px !important } \n}\n</code></pre>\n"
},
{
"answer_id": 251167,
"author": "dheeraj Kumar",
"author_id": 110140,
"author_profile": "https://wordpress.stackexchange.com/users/110140",
"pm_score": 1,
"selected": false,
"text": "<p>Please Use </p>\n\n<p><strong>font-size: 2.5vw;</strong></p>\n\n<p>it is responsive and set according to size. </p>\n\n<pre><code>.wp-caption .wp-caption-text { **font-size: 16px** !important; color: #000000; text-align: center; background-color: #F2F2F2; padding-top: 1px; margin: 1px; }\n</code></pre>\n"
}
] |
2017/01/03
|
[
"https://wordpress.stackexchange.com/questions/251141",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109463/"
] |
I am using this css code on my theme in order to get the styling under an image in a post:
```
.wp-caption .wp-caption-text {
font-size: 16px !important;
color: #000000;
text-align: center;
background-color: #F2F2F2;
padding-top: 1px;
margin: 1px;
}
```
When using it on mobile, the text is to big, and does not reduce size as the rest of the content. Any tips to how I can fix this? Maybe a media query in the code? How would the code look then?
Thanks a lot for all help!
|
Please Use
**font-size: 2.5vw;**
it is responsive and set according to size.
```
.wp-caption .wp-caption-text { **font-size: 16px** !important; color: #000000; text-align: center; background-color: #F2F2F2; padding-top: 1px; margin: 1px; }
```
|
251,147 |
<p>I am creating an eBooks download website. There will be around 5000 eBooks. Each page/post will have a download link to the pdf file of the eBook. My question is, should I create 5000 pages or 5000 posts for these eBooks? </p>
|
[
{
"answer_id": 251155,
"author": "iguanarama",
"author_id": 109807,
"author_profile": "https://wordpress.stackexchange.com/users/109807",
"pm_score": 0,
"selected": false,
"text": "<p>Here are the principles of what's probably going on. (Fixing it without guesswork would require access to all your CSS.)</p>\n\n<p>If (most of) your font sizes are automatically reducing on mobile, then you probably already have a media query in your CSS, something like this:</p>\n\n<pre><code>@media only screen and (max-width: 768px) {\n [some kind of CSS specifying font size]\n}\n</code></pre>\n\n<p>This lets you specify CSS variations specifically for devices with a max width of 768px, so most cellphones and portrait tablets.</p>\n\n<p>However, you have <code>!important</code> after your <code>font-size</code> for <code>.wp-caption .wp-caption-text</code>. This basically tells the browser to ignore any other CSS rules that would normally override it: your caption will be that font size, no matter what—and that includes ignoring any CSS that adjusts the font for mobile devices. <code>!important</code> is an ugly hack, and rarely needed.</p>\n\n<p>So how to fix it? You first need to remove <code>!important</code> from your <code>.wp-caption .wp-caption-text</code>. If your caption font size is no longer 16px on a standard desktop view, you need to find out which CSS rule is overriding it. One way is to use a live inspector in a browser, like Safari's web inspector (Command-Shift-I on any page, after Preferences > Advanced > Show develop menu), and investigate where it's getting the font size from. Alternatively, look through your CSS and see if a font size for captions is specified more specifically (e.g. <code>body #my-main-div .wp-caption .wp-caption-text</code>).</p>\n\n<p>Once you've found the culprit, and your font size is now 16px for captions on desktop view, then you can add a different captions font size to your <code>@media</code> query for mobile, and you should be all set.</p>\n"
},
{
"answer_id": 251161,
"author": "Pro Wordpress Development",
"author_id": 103849,
"author_profile": "https://wordpress.stackexchange.com/users/103849",
"pm_score": 0,
"selected": false,
"text": "<p>You can use css as below </p>\n\n<pre><code>@media screen and (max-width:480px) { \n .wp-caption .wp-caption-text { font-size: 14px !important } \n}\n</code></pre>\n"
},
{
"answer_id": 251167,
"author": "dheeraj Kumar",
"author_id": 110140,
"author_profile": "https://wordpress.stackexchange.com/users/110140",
"pm_score": 1,
"selected": false,
"text": "<p>Please Use </p>\n\n<p><strong>font-size: 2.5vw;</strong></p>\n\n<p>it is responsive and set according to size. </p>\n\n<pre><code>.wp-caption .wp-caption-text { **font-size: 16px** !important; color: #000000; text-align: center; background-color: #F2F2F2; padding-top: 1px; margin: 1px; }\n</code></pre>\n"
}
] |
2017/01/03
|
[
"https://wordpress.stackexchange.com/questions/251147",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110129/"
] |
I am creating an eBooks download website. There will be around 5000 eBooks. Each page/post will have a download link to the pdf file of the eBook. My question is, should I create 5000 pages or 5000 posts for these eBooks?
|
Please Use
**font-size: 2.5vw;**
it is responsive and set according to size.
```
.wp-caption .wp-caption-text { **font-size: 16px** !important; color: #000000; text-align: center; background-color: #F2F2F2; padding-top: 1px; margin: 1px; }
```
|
251,171 |
<p>So, I'm building a new theme based on Underscores. So far, I've managed to get ACF Pro to call different header files from a dropdwon selction in the Options page but, now I am faced with the task of determining how best to handle the css for each of the custom header files and how to load widget areas based on which header file is loaded.</p>
<p>First the css bit: Since the Underscores theme has very minimal style rules out of the box, I was thinking that it might not be a bad idea to include header-specific css files based on the header file being called by ACF Pro in the Options page. For example, I'd create a header file called header-slim.php and in my functions file, do some sort of 'if' header=header-slim.php, then load header-slim.css. This way, i would only only be loading a small css file for the chosen header, a normal style.css file, and then, for different footers, a footer.css file (ex: footer-full-width.css).</p>
<p>If this is an acceptable way to go about the multiple header layout concept, then what, exactly would I put in my functions file? Another detail is that if no header layout option is chosen, the theme will run the normal get_header() as a default function.</p>
<p>Now for the header widgets: Correct if I am wrong (which is often) but, if I load header1.php file and it has 3 widget areas in it, then those three widgets would automatically appear in the available widgets on the widgets page in WP Admin, right? Of course, after loading a header I'd need to refresh the widgets page and, so long as those widgets areas have been registered in my functions file, they would load provided there is a header file that calls said registered widgets, correct?</p>
<p>I've done quite a lot of digging around here and on the web in general and I've yet to find anything that addresses my questions specifically. If there is something here and I've missed it, please forgive me. </p>
<p>I would love some specific help with what I'm trying to achieve if you guys don't mind.</p>
<p>Many thanks!
Ray</p>
<p>UPDATE: Here's some code bits for you to have a look at.</p>
<p>This is what I have at the top of my index.php file in order to print whichever header is selected in the ACF Pro options page:</p>
<pre><code><?php
$selectHeader = get_field( 'select_header_layout','option');
if($selectHeader == "black"){get_header('black');}
elseif($selectHeader == "gray"){get_header('gray');}
elseif($selectHeader == "red"){get_header('red');}
else {get_header();}
?>
</code></pre>
<p>And here's what I've added to my functions.php file - I edited the 'chosen_header' to 'select_header_layout' so as to match what I have in the index.php file. Here comes the mess...</p>
<pre><code>function my_header_css_scripts () {
switch (get_field ('select_header_layout', 'option')) {
case 'header-black.php':
$appropriateHeader = 'header-black.css';
break;
case 'header-gray.php':
$appropriateHeader = 'header-gray.css';
break;
case 'header-red.php':
$appropriateHeader = 'header-red.css';
break;
default:
$appropriateHeader = 'header-default.css';
break;
}
wp_enqueue_style ('my_header_css_scripts', get_theme_file_uri('/wp-content/themes/rm-acf1/hdr-styles/' . $appropriateHeader));
}
add_action ('wp_enqueue_scripts', 'my_header_css_scripts');
</code></pre>
<p><strong>Here's the code I have in my functions.php file right now (Jan 4, 2016 @ 4:30pm):</strong></p>
<pre><code>function my_header_css_scripts () {
switch (get_field ( 'chosen_header', 'option' )) {
case 'header-black.php':
$appropriateHeader = 'header-black.css';
break;
case 'header-gray.php':
$appropriateHeader = 'header-gray.css';
break;
case 'header-red.php':
$appropriateHeader = 'header-red.css';
break;
default:
$appropriateHeader = 'header-default.css';
break;
}
wp_enqueue_style( basename( $appropriateHeader ), get_template_directory_uri() . '/hdr-styles/' . $appropriateHeader );
}
add_action ('wp_enqueue_scripts', 'my_header_css_scripts');
</code></pre>
|
[
{
"answer_id": 251178,
"author": "iguanarama",
"author_id": 109807,
"author_profile": "https://wordpress.stackexchange.com/users/109807",
"pm_score": 0,
"selected": false,
"text": "<p>Yes your approach to loading header-specific CSS sounds fine. You could do something like this in functions.php:</p>\n\n<pre><code>function my_header_css_scripts () {\n switch (get_field ('chosen_header', 'option')) {\n case 'header-slim.php':\n $appropriateHeader = 'header-slim.css';\n break;\n case 'header-whatever.php':\n $appropriateHeader = 'whatever.css';\n break;\n default:\n $appropriateHeader = 'header.css';\n break;\n }\n wp_enqueue_style ('my_header_css', get_theme_file_uri ('/themepath/to/css/' . $appropriateHeader));\n}\nadd_action ('wp_enqueue_scripts', 'my_header_css_scripts');\n</code></pre>\n\n<p>For the widgets... it's not entirely clear what you're asking, but to recap: you can place specific widgets using <a href=\"https://codex.wordpress.org/Function_Reference/the_widget\" rel=\"nofollow noreferrer\">the_widget</a> or ones specified in the admin area using <a href=\"https://codex.wordpress.org/Function_Reference/dynamic_sidebar\" rel=\"nofollow noreferrer\">dynamic_sidebar</a>. Your selected header php file can't change the widget selections in the admin area, because it's only for outputting a page header. Instead, you could define multiple new widget areas, as shown in <a href=\"https://buckleupstudios.com/add-a-new-widget-area-to-a-wordpress-theme/\" rel=\"nofollow noreferrer\">this post from buckleupstudios.com</a>, one for each header type, and then each header's widgets would be customizable in the admin area. If, in the admin area, you only want to show the widget area for the currently selected header then I'm guessing you'd have to hook into the admin widgets page somehow and hide the other widget areas.</p>\n"
},
{
"answer_id": 251305,
"author": "Michael Ecklund",
"author_id": 9579,
"author_profile": "https://wordpress.stackexchange.com/users/9579",
"pm_score": 3,
"selected": true,
"text": "<p>That's not how you use <code>get_theme_file_uri();</code> </p>\n\n<p>You need to specify the directory RELATIVE to your currently active theme's directory. </p>\n\n<p>So for example, if your currently activated theme is <code>rm-acf1</code>, and all of your custom header CSS files are located in the subfolder <code>hdr-styles</code>. </p>\n\n<ul>\n<li>This is your theme directory: <code>./wp-content/rm-acf1/</code> </li>\n<li>This is your header styles directory:\n<code>./wp-content/rm-acf1/hdr-styles/</code></li>\n</ul>\n\n<p>So when you use <code>get_theme_file_uri();</code> with no parameters, it should default you to <code>./wp-content/rm-acf1/</code>.</p>\n\n<p>Now in your situation, you want to target files in a subdirectory within your currently activated theme directory so you would need to specify the relative path. </p>\n\n<p>You would use it like this: <code>get_theme_file_uri( 'hdr-styles/' . $appropriateHeader );</code></p>\n\n<hr>\n\n<p><strong>EDIT in regards to your error:</strong> <code>Fatal error: Call to undefined function get_theme_file_uri()</code></p>\n\n<p><strong>Try the following instead:</strong> </p>\n\n<p><code>wp_enqueue_style( 'my_header_css_scripts', get_template_directory_uri() . '/hdr-styles/' . $appropriateHeader );</code></p>\n\n<p>and actually the style handle should probably be reflective of the style sheet being loaded. So instead of generically using \"my_header_css_scripts\" for the loaded style sheet, perhaps something like <code>basename($appropriateHeader)</code></p>\n\n<p><strong>Example:</strong></p>\n\n<p><code>wp_enqueue_style( basename( $appropriateHeader ), get_template_directory_uri() . '/hdr-styles/' . $appropriateHeader );</code></p>\n"
},
{
"answer_id": 251333,
"author": "AlonsoF1",
"author_id": 110141,
"author_profile": "https://wordpress.stackexchange.com/users/110141",
"pm_score": 0,
"selected": false,
"text": "<p>So, after scratching my head and trying a few things, I am happy to report that thanks to @iguanarama and @Michael Ecklund, the multiple headers calling stylesheets conditionally is now up and running! :) I want to thank you both for all your help...seriously! I've pasted the code that's working now in my functions.php file below for you guys to have a look at. Now, I have to figure out how to show corresponding widgets in the widget admin page in WP-Admin. What I mean by this is when I load header say, header-1, the only available header widgets in the widget admin page are widgets that will show in header-1 on the front-end. </p>\n\n<p><strong>Here's the code that's working:</strong></p>\n\n<pre><code>function my_header_css_scripts () {\nswitch (get_field ( 'select_header_layout', 'option' )) {\n case 'black':\n $appropriateHeader = 'header-black.css';\n break;\n case 'gray':\n $appropriateHeader = 'header-gray.css';\n break;\n case 'red':\n $appropriateHeader = 'header-red.css';\n break;\n default:\n $appropriateHeader = 'header-default.css';\n break;\n}\nwp_enqueue_style( basename( $appropriateHeader ), get_template_directory_uri() . '/hdr-styles/' . $appropriateHeader ); }\nadd_action ('wp_enqueue_scripts', 'my_header_css_scripts');\n</code></pre>\n"
}
] |
2017/01/03
|
[
"https://wordpress.stackexchange.com/questions/251171",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110141/"
] |
So, I'm building a new theme based on Underscores. So far, I've managed to get ACF Pro to call different header files from a dropdwon selction in the Options page but, now I am faced with the task of determining how best to handle the css for each of the custom header files and how to load widget areas based on which header file is loaded.
First the css bit: Since the Underscores theme has very minimal style rules out of the box, I was thinking that it might not be a bad idea to include header-specific css files based on the header file being called by ACF Pro in the Options page. For example, I'd create a header file called header-slim.php and in my functions file, do some sort of 'if' header=header-slim.php, then load header-slim.css. This way, i would only only be loading a small css file for the chosen header, a normal style.css file, and then, for different footers, a footer.css file (ex: footer-full-width.css).
If this is an acceptable way to go about the multiple header layout concept, then what, exactly would I put in my functions file? Another detail is that if no header layout option is chosen, the theme will run the normal get\_header() as a default function.
Now for the header widgets: Correct if I am wrong (which is often) but, if I load header1.php file and it has 3 widget areas in it, then those three widgets would automatically appear in the available widgets on the widgets page in WP Admin, right? Of course, after loading a header I'd need to refresh the widgets page and, so long as those widgets areas have been registered in my functions file, they would load provided there is a header file that calls said registered widgets, correct?
I've done quite a lot of digging around here and on the web in general and I've yet to find anything that addresses my questions specifically. If there is something here and I've missed it, please forgive me.
I would love some specific help with what I'm trying to achieve if you guys don't mind.
Many thanks!
Ray
UPDATE: Here's some code bits for you to have a look at.
This is what I have at the top of my index.php file in order to print whichever header is selected in the ACF Pro options page:
```
<?php
$selectHeader = get_field( 'select_header_layout','option');
if($selectHeader == "black"){get_header('black');}
elseif($selectHeader == "gray"){get_header('gray');}
elseif($selectHeader == "red"){get_header('red');}
else {get_header();}
?>
```
And here's what I've added to my functions.php file - I edited the 'chosen\_header' to 'select\_header\_layout' so as to match what I have in the index.php file. Here comes the mess...
```
function my_header_css_scripts () {
switch (get_field ('select_header_layout', 'option')) {
case 'header-black.php':
$appropriateHeader = 'header-black.css';
break;
case 'header-gray.php':
$appropriateHeader = 'header-gray.css';
break;
case 'header-red.php':
$appropriateHeader = 'header-red.css';
break;
default:
$appropriateHeader = 'header-default.css';
break;
}
wp_enqueue_style ('my_header_css_scripts', get_theme_file_uri('/wp-content/themes/rm-acf1/hdr-styles/' . $appropriateHeader));
}
add_action ('wp_enqueue_scripts', 'my_header_css_scripts');
```
**Here's the code I have in my functions.php file right now (Jan 4, 2016 @ 4:30pm):**
```
function my_header_css_scripts () {
switch (get_field ( 'chosen_header', 'option' )) {
case 'header-black.php':
$appropriateHeader = 'header-black.css';
break;
case 'header-gray.php':
$appropriateHeader = 'header-gray.css';
break;
case 'header-red.php':
$appropriateHeader = 'header-red.css';
break;
default:
$appropriateHeader = 'header-default.css';
break;
}
wp_enqueue_style( basename( $appropriateHeader ), get_template_directory_uri() . '/hdr-styles/' . $appropriateHeader );
}
add_action ('wp_enqueue_scripts', 'my_header_css_scripts');
```
|
That's not how you use `get_theme_file_uri();`
You need to specify the directory RELATIVE to your currently active theme's directory.
So for example, if your currently activated theme is `rm-acf1`, and all of your custom header CSS files are located in the subfolder `hdr-styles`.
* This is your theme directory: `./wp-content/rm-acf1/`
* This is your header styles directory:
`./wp-content/rm-acf1/hdr-styles/`
So when you use `get_theme_file_uri();` with no parameters, it should default you to `./wp-content/rm-acf1/`.
Now in your situation, you want to target files in a subdirectory within your currently activated theme directory so you would need to specify the relative path.
You would use it like this: `get_theme_file_uri( 'hdr-styles/' . $appropriateHeader );`
---
**EDIT in regards to your error:** `Fatal error: Call to undefined function get_theme_file_uri()`
**Try the following instead:**
`wp_enqueue_style( 'my_header_css_scripts', get_template_directory_uri() . '/hdr-styles/' . $appropriateHeader );`
and actually the style handle should probably be reflective of the style sheet being loaded. So instead of generically using "my\_header\_css\_scripts" for the loaded style sheet, perhaps something like `basename($appropriateHeader)`
**Example:**
`wp_enqueue_style( basename( $appropriateHeader ), get_template_directory_uri() . '/hdr-styles/' . $appropriateHeader );`
|
251,175 |
<p>Hi is there anybody who can help me how to find all posts without category and assign the "Uncategorized"? I have more than 7000 posts and 300 of them are without category, how I could assing one?</p>
<p>And another question, how I can assign category to all posts (except bulk edit which doesnt work well with this amount of posts)?</p>
|
[
{
"answer_id": 251209,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't set any category to your post then it'll automatically be assigned to <strong>Uncategorized</strong>. You don't need to assign it manually to <strong>Uncategorized</strong></p>\n<p>And for assigning category to bulk posts you can use <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_post_categories\" rel=\"nofollow noreferrer\"><code>wp_set_post_categories()</code></a> function. Get all of your posts(which you need to assign category) in an array and run a loop theough the array with\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_set_post_categories\" rel=\"nofollow noreferrer\"><code>wp_set_post_categories( $post_ID, $post_categories, $append )</code></a> passing needed parameter. It will assign the category to your posts.</p>\n"
},
{
"answer_id": 333480,
"author": "alex",
"author_id": 164455,
"author_profile": "https://wordpress.stackexchange.com/users/164455",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it through sql query. Add your category id instead 37.</p>\n\n<pre><code>INSERT IGNORE INTO wp_term_relationships\n(object_id, term_taxonomy_id, term_order)\nSELECT \n wp_posts.ID as object_id,\n 37 as term_taxonomy_id,\n 0 as term_order\nFROM wp_posts\nLEFT JOIN \n wp_term_relationships rel\nON wp_posts.ID = rel.object_id \nLEFT JOIN \n wp_term_taxonomy tax\nON tax.term_taxonomy_id = rel.term_taxonomy_id \n AND tax.taxonomy = 'category' \nLEFT JOIN \n wp_terms term\nON term.term_id = tax.term_id\nWHERE wp_posts.post_type = 'post' \n AND wp_posts.post_status = 'publish' \n AND term.term_id is null\n</code></pre>\n"
},
{
"answer_id": 358114,
"author": "MartiNuker",
"author_id": 182357,
"author_profile": "https://wordpress.stackexchange.com/users/182357",
"pm_score": 3,
"selected": true,
"text": "<p>The current accepted takes posts out of range too. Since it LEFT JOIN on wp_term_relationships without knowing that the first join might be a Category or a Post_tag, it gives false-positive, hence affecting posts that might not be without category.</p>\n\n<p>Inspired from the current accepted answer, change the \"37\" for your actual wanted category:</p>\n\n<pre><code>INSERT IGNORE INTO wp_term_relationships\n(object_id, term_taxonomy_id, term_order)\nSELECT p.ID as `object_id`, 37 as `term_taxonomy_id`, 0 as `term_order`\n FROM wp_posts p \n WHERE p.post_type=\"post\" \n AND p.post_status='publish'\n AND NOT EXISTS\n (\n SELECT *\n FROM wp_term_relationships rel\n JOIN wp_term_taxonomy tax\n ON tax.term_taxonomy_id = rel.term_taxonomy_id \n AND tax.taxonomy = 'category' \n JOIN wp_terms term\n ON term.term_id = tax.term_id\n WHERE p.ID = rel.object_id \n )\n</code></pre>\n"
}
] |
2017/01/03
|
[
"https://wordpress.stackexchange.com/questions/251175",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64771/"
] |
Hi is there anybody who can help me how to find all posts without category and assign the "Uncategorized"? I have more than 7000 posts and 300 of them are without category, how I could assing one?
And another question, how I can assign category to all posts (except bulk edit which doesnt work well with this amount of posts)?
|
The current accepted takes posts out of range too. Since it LEFT JOIN on wp\_term\_relationships without knowing that the first join might be a Category or a Post\_tag, it gives false-positive, hence affecting posts that might not be without category.
Inspired from the current accepted answer, change the "37" for your actual wanted category:
```
INSERT IGNORE INTO wp_term_relationships
(object_id, term_taxonomy_id, term_order)
SELECT p.ID as `object_id`, 37 as `term_taxonomy_id`, 0 as `term_order`
FROM wp_posts p
WHERE p.post_type="post"
AND p.post_status='publish'
AND NOT EXISTS
(
SELECT *
FROM wp_term_relationships rel
JOIN wp_term_taxonomy tax
ON tax.term_taxonomy_id = rel.term_taxonomy_id
AND tax.taxonomy = 'category'
JOIN wp_terms term
ON term.term_id = tax.term_id
WHERE p.ID = rel.object_id
)
```
|
251,177 |
<p>I want to ask a question: I have a source code, it only works for the post-new, but not edit post. So how to disable Publish button on Edit post if post title exists?</p>
<pre><code>add_action('wp_ajax_check-posts-by-title', function(){
$title = isset( $_REQUEST['title'] ) ? esc_attr( $_REQUEST['title'] ) : null;
// check for title
if ( !$title ) {
return wp_send_json(array(
'enable_btn' => false,
'message' => 'No title specified!'
));
}
$post = get_page_by_title($title, OBJECT, 'post');
// check for post
if ( isset($post->ID) && 'publish' === $post->post_status ) {
return wp_send_json(array(
'enable_btn' => false
));
}
// nothing caught
return wp_send_json(array(
'enable_btn' => true
));
// kill response
wp_die();
});
add_action('admin_footer', function() {
global $pagenow;
if ( !$pagenow || !in_array($pagenow, array( 'post-new.php' )) )
return; // only enqueue when writing/editing posts
?>
<script>
jQuery(document).ready(function($){
$(document).on("change", "#titlediv #title", function(e){
var i = $(this)
, f = i.closest('form')
, t = i.val()
, b = $('input[name="publish"]', f).first();
if ( self.xhr ) {
self.xhr.abort();
} else {
var xhr;
}
if ( !b.length ) return;
b.attr('disabled','disabled');
if ( $.trim( t ) ) {
self.xhr = $.ajax({type: 'post', url: 'admin-ajax.php', data: {
action: 'check-posts-by-title',
title: t
}, success: function(res){
if ( res && res.enable_btn ) {
b.removeAttr('disabled');
} else {
if ( res.message ) {
alert(res.message);
}
}
}, error: function(){
i.trigger('change'); // roll over
}});
}
});
$('#titlediv #title').trigger('change');
});
</script>
<?php
});
</code></pre>
<p>Thanks! <3</p>
|
[
{
"answer_id": 251209,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't set any category to your post then it'll automatically be assigned to <strong>Uncategorized</strong>. You don't need to assign it manually to <strong>Uncategorized</strong></p>\n<p>And for assigning category to bulk posts you can use <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_post_categories\" rel=\"nofollow noreferrer\"><code>wp_set_post_categories()</code></a> function. Get all of your posts(which you need to assign category) in an array and run a loop theough the array with\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_set_post_categories\" rel=\"nofollow noreferrer\"><code>wp_set_post_categories( $post_ID, $post_categories, $append )</code></a> passing needed parameter. It will assign the category to your posts.</p>\n"
},
{
"answer_id": 333480,
"author": "alex",
"author_id": 164455,
"author_profile": "https://wordpress.stackexchange.com/users/164455",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it through sql query. Add your category id instead 37.</p>\n\n<pre><code>INSERT IGNORE INTO wp_term_relationships\n(object_id, term_taxonomy_id, term_order)\nSELECT \n wp_posts.ID as object_id,\n 37 as term_taxonomy_id,\n 0 as term_order\nFROM wp_posts\nLEFT JOIN \n wp_term_relationships rel\nON wp_posts.ID = rel.object_id \nLEFT JOIN \n wp_term_taxonomy tax\nON tax.term_taxonomy_id = rel.term_taxonomy_id \n AND tax.taxonomy = 'category' \nLEFT JOIN \n wp_terms term\nON term.term_id = tax.term_id\nWHERE wp_posts.post_type = 'post' \n AND wp_posts.post_status = 'publish' \n AND term.term_id is null\n</code></pre>\n"
},
{
"answer_id": 358114,
"author": "MartiNuker",
"author_id": 182357,
"author_profile": "https://wordpress.stackexchange.com/users/182357",
"pm_score": 3,
"selected": true,
"text": "<p>The current accepted takes posts out of range too. Since it LEFT JOIN on wp_term_relationships without knowing that the first join might be a Category or a Post_tag, it gives false-positive, hence affecting posts that might not be without category.</p>\n\n<p>Inspired from the current accepted answer, change the \"37\" for your actual wanted category:</p>\n\n<pre><code>INSERT IGNORE INTO wp_term_relationships\n(object_id, term_taxonomy_id, term_order)\nSELECT p.ID as `object_id`, 37 as `term_taxonomy_id`, 0 as `term_order`\n FROM wp_posts p \n WHERE p.post_type=\"post\" \n AND p.post_status='publish'\n AND NOT EXISTS\n (\n SELECT *\n FROM wp_term_relationships rel\n JOIN wp_term_taxonomy tax\n ON tax.term_taxonomy_id = rel.term_taxonomy_id \n AND tax.taxonomy = 'category' \n JOIN wp_terms term\n ON term.term_id = tax.term_id\n WHERE p.ID = rel.object_id \n )\n</code></pre>\n"
}
] |
2017/01/03
|
[
"https://wordpress.stackexchange.com/questions/251177",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109872/"
] |
I want to ask a question: I have a source code, it only works for the post-new, but not edit post. So how to disable Publish button on Edit post if post title exists?
```
add_action('wp_ajax_check-posts-by-title', function(){
$title = isset( $_REQUEST['title'] ) ? esc_attr( $_REQUEST['title'] ) : null;
// check for title
if ( !$title ) {
return wp_send_json(array(
'enable_btn' => false,
'message' => 'No title specified!'
));
}
$post = get_page_by_title($title, OBJECT, 'post');
// check for post
if ( isset($post->ID) && 'publish' === $post->post_status ) {
return wp_send_json(array(
'enable_btn' => false
));
}
// nothing caught
return wp_send_json(array(
'enable_btn' => true
));
// kill response
wp_die();
});
add_action('admin_footer', function() {
global $pagenow;
if ( !$pagenow || !in_array($pagenow, array( 'post-new.php' )) )
return; // only enqueue when writing/editing posts
?>
<script>
jQuery(document).ready(function($){
$(document).on("change", "#titlediv #title", function(e){
var i = $(this)
, f = i.closest('form')
, t = i.val()
, b = $('input[name="publish"]', f).first();
if ( self.xhr ) {
self.xhr.abort();
} else {
var xhr;
}
if ( !b.length ) return;
b.attr('disabled','disabled');
if ( $.trim( t ) ) {
self.xhr = $.ajax({type: 'post', url: 'admin-ajax.php', data: {
action: 'check-posts-by-title',
title: t
}, success: function(res){
if ( res && res.enable_btn ) {
b.removeAttr('disabled');
} else {
if ( res.message ) {
alert(res.message);
}
}
}, error: function(){
i.trigger('change'); // roll over
}});
}
});
$('#titlediv #title').trigger('change');
});
</script>
<?php
});
```
Thanks! <3
|
The current accepted takes posts out of range too. Since it LEFT JOIN on wp\_term\_relationships without knowing that the first join might be a Category or a Post\_tag, it gives false-positive, hence affecting posts that might not be without category.
Inspired from the current accepted answer, change the "37" for your actual wanted category:
```
INSERT IGNORE INTO wp_term_relationships
(object_id, term_taxonomy_id, term_order)
SELECT p.ID as `object_id`, 37 as `term_taxonomy_id`, 0 as `term_order`
FROM wp_posts p
WHERE p.post_type="post"
AND p.post_status='publish'
AND NOT EXISTS
(
SELECT *
FROM wp_term_relationships rel
JOIN wp_term_taxonomy tax
ON tax.term_taxonomy_id = rel.term_taxonomy_id
AND tax.taxonomy = 'category'
JOIN wp_terms term
ON term.term_id = tax.term_id
WHERE p.ID = rel.object_id
)
```
|
251,260 |
<p>I have a custom theme that for the latest posts displays the posts thumbnail. What I am looking to do is to check and if there is no thumbnail set then use the category's featured image. I could upload the images and use this:</p>
<pre><code>if (!$photo) :
$uploads = wp_upload_dir();
$photo = '<div class="related-content-box__photo" style="background-image: url(' . $uploads['baseurl'] . '/2017/01/' . $category_name . '.jpg' . ')"></div>';
endif;
</code></pre>
<p>What I don't like about this is that if I want to change one image of a category I have to upload all of them again and change the year/month of the folder.</p>
<p>So I have uploaded the images as featured images for the category themselves but how can I display them?</p>
|
[
{
"answer_id": 251206,
"author": "iguanarama",
"author_id": 109807,
"author_profile": "https://wordpress.stackexchange.com/users/109807",
"pm_score": 0,
"selected": false,
"text": "<p>Going to cover several bases in my answer. :)</p>\n\n<p>If you are creating your own theme, and want to change the default presentation of some types of pages (e.g. the category archive page, or a single blog post page), then check out the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#visual-overview\" rel=\"nofollow noreferrer\">diagram of the WordPress template hierarchy</a>. It shows which files in your theme directory are used to display which types of post.</p>\n\n<p>By having a php file in your theme that matches a file in that hierarchy, it will be automatically used by WordPress—such as <code>single.php</code> for displaying a single post. If you have a theme with that file already there, then obviously you can change the file and it will be reflected on the site.</p>\n\n<p>Separately, if you want to have custom page templates but only want an admin to be able to change them (on a post-by-post basis), then you need to do some checks on roles and capabilities; <a href=\"https://wordpress.stackexchange.com/questions/124683/removing-or-restricting-access-to-page-templates-for-editor-role\">this StackExchange answer</a> may be helpful. (You'd still need to create those custom page templates, see <a href=\"https://www.smashingmagazine.com/2015/06/wordpress-custom-page-templates/\" rel=\"nofollow noreferrer\">this Smashing Magazine article</a>).</p>\n\n<p>Otherwise, if you want an admin to more globally choose page/post templates based on certain criteria, or to choose custom page templates for the entire site, then you'll need to add an admin-area option to your theme, and some custom code in your theme to display the right page based on that option. Adding an option to the admin area is easily done with one of the many plugins but also can be done by hand (see, for example, <a href=\"https://www.sitepoint.com/create-a-wordpress-theme-settings-page-with-the-settings-api/\" rel=\"nofollow noreferrer\">this article on SitePoint</a>).</p>\n"
},
{
"answer_id": 251220,
"author": "Akram ul haq",
"author_id": 110188,
"author_profile": "https://wordpress.stackexchange.com/users/110188",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, you mean you want to create your own template page to show blog posts, right ?</p>\n\n<p>Then go this way create a php file named <code>blog-template.php</code></p>\n\n<p>Inside that file put this code on top of every thing. </p>\n\n<pre><code><?php \n/*\n* Template Name: Blog Post\n*/\n?>\n</code></pre>\n\n<p>Then below above given code, put all your code from <code>index.php/home.php</code> page to this above page, save the file and now create a page from <code>dashboard</code>, say as name of that page is <code>\"Blog\"</code> Now from right side <code>chose page template</code> which we just created as <code>Blog Post</code> from that drop-down of templates.</p>\n\n<p>Publish the page and you are good to go for having your own page to show your posts.</p>\n\n<p>Let me know if any thing else needed.</p>\n"
},
{
"answer_id": 308850,
"author": "Orun",
"author_id": 18228,
"author_profile": "https://wordpress.stackexchange.com/users/18228",
"pm_score": 4,
"selected": false,
"text": "<p>Don't forget that Wordpress was primarily designed to be a blogging CMS, so when it comes to theme development, developers often opt for a non-standard approach in exchange for the potential for more features.</p>\n\n<p>Theme developers have three options when they approach this, one of which (#2 below) you mentioned.</p>\n\n<ol>\n<li><p>Directly edit the <code>index.php</code> to modify the blog index. This is not a good option because <code>index.php</code> should be the a fallback in case another part of your template is missing.</p>\n\n<ul>\n<li>Pros: fast and easy</li>\n<li>Cons: error prone and against object oriented principles</li>\n</ul></li>\n<li><p>Create a page template for the blog index. Like you said, many theme developers elect to go this route because it's a fast way to give you control over the blog index, and it actually gives you the ability to play around with different blog index templates (which is useful when developing a versatile theme). </p>\n\n<ul>\n<li>Pros: Versatile, allows for building a robust theme</li>\n<li>Cons: you lose the ability to call Wordpress' native functionality that pertains to the blog index.</li>\n</ul></li>\n<li><p>Create a <code>front-page.php</code>, <code>home.php</code> and <code>index.php</code> in your theme. The <code>front-page</code> will be the home page for the theme. <code>home</code> will default to your blog index and <code>index</code> will be your fallback for all templates.</p>\n\n<ul>\n<li>Pros: Clean and makes full use of Wordpress' native objects and methods</li>\n<li>Cons: Limited by Wordpress: not ideal for many of the kinds of option-rich themes you see today</li>\n</ul></li>\n</ol>\n\n<p>Personally I like to go with #2, because most of my Wordpress development projects these days are not just blogs: they're entire sites with deep information architecture and complex interactivity.</p>\n"
}
] |
2017/01/04
|
[
"https://wordpress.stackexchange.com/questions/251260",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110131/"
] |
I have a custom theme that for the latest posts displays the posts thumbnail. What I am looking to do is to check and if there is no thumbnail set then use the category's featured image. I could upload the images and use this:
```
if (!$photo) :
$uploads = wp_upload_dir();
$photo = '<div class="related-content-box__photo" style="background-image: url(' . $uploads['baseurl'] . '/2017/01/' . $category_name . '.jpg' . ')"></div>';
endif;
```
What I don't like about this is that if I want to change one image of a category I have to upload all of them again and change the year/month of the folder.
So I have uploaded the images as featured images for the category themselves but how can I display them?
|
Don't forget that Wordpress was primarily designed to be a blogging CMS, so when it comes to theme development, developers often opt for a non-standard approach in exchange for the potential for more features.
Theme developers have three options when they approach this, one of which (#2 below) you mentioned.
1. Directly edit the `index.php` to modify the blog index. This is not a good option because `index.php` should be the a fallback in case another part of your template is missing.
* Pros: fast and easy
* Cons: error prone and against object oriented principles
2. Create a page template for the blog index. Like you said, many theme developers elect to go this route because it's a fast way to give you control over the blog index, and it actually gives you the ability to play around with different blog index templates (which is useful when developing a versatile theme).
* Pros: Versatile, allows for building a robust theme
* Cons: you lose the ability to call Wordpress' native functionality that pertains to the blog index.
3. Create a `front-page.php`, `home.php` and `index.php` in your theme. The `front-page` will be the home page for the theme. `home` will default to your blog index and `index` will be your fallback for all templates.
* Pros: Clean and makes full use of Wordpress' native objects and methods
* Cons: Limited by Wordpress: not ideal for many of the kinds of option-rich themes you see today
Personally I like to go with #2, because most of my Wordpress development projects these days are not just blogs: they're entire sites with deep information architecture and complex interactivity.
|
251,278 |
<p>I'm using the <a href="https://wordpress.org/plugins/json-api-user/" rel="nofollow noreferrer">JSON REST User plugin</a> which extends <a href="https://wordpress.org/plugins/json-api/" rel="nofollow noreferrer">JSON REST Api</a>. I'm sending http data to-from the api up to 4 times back to back in some cases which is dragging network performance.</p>
<p>How can I call</p>
<p><code>http://localhost/wp-json/fb_connect?x&y&z</code></p>
<p>from php without using curl? (I'll use curl if it makes the most sense)</p>
<p><em>the main plugin file, where the fb_connect function is:</em></p>
<p><strong>/wp-content/plugins/json-api-user/controllers/User.php</strong></p>
<p>
<pre><code>/*
Controller name: User
Controller description: User Registration, Authentication, User Info, User Meta, FB Login, BuddyPress xProfile Fields methods
Controller Author: Ali Qureshi
Controller Author Twitter: @parorrey
Controller Author Website: parorrey.com
*/
class JSON_API_User_Controller {
/**
* Returns an Array with registered userid & valid cookie
* @param String username: username to register
* @param String email: email address for user registration
* @param String user_pass: user_pass to be set (optional)
* @param String display_name: display_name for user
*/
public function __construct() {
global $json_api;
// allow only connection over https. because, well, you care about your passwords and sniffing.
// turn this sanity-check off if you feel safe inside your localhost or intranet.
// send an extra POST parameter: insecure=cool
if (empty($_SERVER['HTTPS']) ||
(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'off')) {
if (empty($_REQUEST['insecure']) || $_REQUEST['insecure'] != 'cool') {
$json_api->error("SSL is not enabled. Either use _https_ or provide 'insecure' var as insecure=cool to confirm you want to use http protocol.");
}
}
}
public function info(){
global $json_api;
return array(
"version" => JAU_VERSION
);
}
public function register(){
global $json_api;
if (!get_option('users_can_register')) {
$json_api->error("User registration is disabled. Please enable it in Settings > Gereral.");
}
if (!$json_api->query->username) {
$json_api->error("You must include 'username' var in your request. ");
}
else $username = sanitize_user( $json_api->query->username );
if (!$json_api->query->email) {
$json_api->error("You must include 'email' var in your request. ");
}
else $email = sanitize_email( $json_api->query->email );
if (!$json_api->query->nonce) {
$json_api->error("You must include 'nonce' var in your request. Use the 'get_nonce' Core API method. ");
}
else $nonce = sanitize_text_field( $json_api->query->nonce ) ;
if (!$json_api->query->display_name) {
$json_api->error("You must include 'display_name' var in your request. ");
}
else $display_name = sanitize_text_field( $json_api->query->display_name );
$user_pass = sanitize_text_field( $_REQUEST['user_pass'] );
if ($json_api->query->seconds) $seconds = (int) $json_api->query->seconds;
else $seconds = 1209600;//14 days
//Add usernames we don't want used
$invalid_usernames = array( 'admin' );
//Do username validation
$nonce_id = $json_api->get_nonce_id('user', 'register');
if( !wp_verify_nonce($json_api->query->nonce, $nonce_id) ) {
$json_api->error("Invalid access, unverifiable 'nonce' value. Use the 'get_nonce' Core API method. ");
}
else {
if ( !validate_username( $username ) || in_array( $username, $invalid_usernames ) ) {
$json_api->error("Username is invalid.");
}
elseif ( username_exists( $username ) ) {
$json_api->error("Username already exists.");
}
else{
if ( !is_email( $email ) ) {
$json_api->error("E-mail address is invalid.");
}
elseif (email_exists($email)) {
$json_api->error("E-mail address is already in use.");
}
else {
//Everything has been validated, proceed with creating the user
//Create the user
if( !isset($_REQUEST['user_pass']) ) {
$user_pass = wp_generate_password();
$_REQUEST['user_pass'] = $user_pass;
}
$_REQUEST['user_login'] = $username;
$_REQUEST['user_email'] = $email;
$allowed_params = array('user_login', 'user_email', 'user_pass', 'display_name', 'user_nicename', 'user_url', 'nickname', 'first_name',
'last_name', 'description', 'rich_editing', 'user_registered', 'role', 'jabber', 'aim', 'yim',
'comment_shortcuts', 'admin_color', 'use_ssl', 'show_admin_bar_front'
);
foreach($_REQUEST as $field => $value){
if( in_array($field, $allowed_params) ) $user[$field] = trim(sanitize_text_field($value));
}
$user['role'] = get_option('default_role');
$user_id = wp_insert_user( $user );
/*Send e-mail to admin and new user -
You could create your own e-mail instead of using this function*/
if( isset($_REQUEST['user_pass']) && $_REQUEST['notify']=='no') {
$notify = '';
}elseif($_REQUEST['notify']!='no') $notify = $_REQUEST['notify'];
if($user_id) wp_new_user_notification( $user_id, '',$notify );
}
}
}
$expiration = time() + apply_filters('auth_cookie_expiration', $seconds, $user_id, true);
$cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in');
return array(
"cookie" => $cookie,
"user_id" => $user_id
);
}
public function get_avatar(){
global $json_api;
if (function_exists('bp_is_active')) {
if (!$json_api->query->user_id) {
$json_api->error("You must include 'user_id' var in your request. ");
}
if (!$json_api->query->type) {
$json_api->error("You must include 'type' var in your request. possible values 'full' or 'thumb' ");
}
$avatar = bp_core_fetch_avatar ( array( 'item_id' => $json_api->query->user_id, 'type' => $json_api->query->type, 'html'=>false ));
return array('avatar'=>$avatar);
} else {
$json_api->error("You must install and activate BuddyPress plugin to use this method.");
}
}
public function get_userinfo(){
global $json_api;
if (!$json_api->query->user_id) {
$json_api->error("You must include 'user_id' var in your request. ");
}
$user = get_userdata($json_api->query->user_id);
preg_match('|src="(.+?)"|', get_avatar( $user->ID, 32 ), $avatar);
return array(
"id" => $user->ID,
//"username" => $user->user_login,
"nicename" => $user->user_nicename,
//"email" => $user->user_email,
"url" => $user->user_url,
"displayname" => $user->display_name,
"firstname" => $user->user_firstname,
"lastname" => $user->last_name,
"nickname" => $user->nickname,
"avatar" => $avatar[1]
);
}
public function retrieve_password(){
global $wpdb, $json_api, $wp_hasher;
if (!$json_api->query->user_login) {
$json_api->error("You must include 'user_login' var in your request. ");
}
$user_login = $json_api->query->user_login;
if ( strpos( $user_login, '@' ) ) {
$user_data = get_user_by( 'email', trim( $user_login ) );
if ( empty( $user_data ) )
$json_api->error("Your email address not found! ");
} else {
$login = trim($user_login);
$user_data = get_user_by('login', $login);
}
// redefining user_login ensures we return the right case in the email
$user_login = $user_data->user_login;
$user_email = $user_data->user_email;
do_action('retrieve_password', $user_login);
$allow = apply_filters('allow_password_reset', true, $user_data->ID);
if ( ! $allow ) $json_api->error("password reset not allowed! ");
elseif ( is_wp_error($allow) ) $json_api->error("An error occured! ");
$key = wp_generate_password( 20, false );
do_action( 'retrieve_password_key', $user_login, $key );
if ( empty( $wp_hasher ) ) {
require_once ABSPATH . 'wp-includes/class-phpass.php';
$wp_hasher = new PasswordHash( 8, true );
}
$hashed = time() . ':' . $wp_hasher->HashPassword( $key );
$wpdb->update( $wpdb->users, array( 'user_activation_key' => $hashed ), array( 'user_login' => $user_login ) );
$message = __('Someone requested that the password be reset for the following account:') . "\r\n\r\n";
$message .= network_home_url( '/' ) . "\r\n\r\n";
$message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
$message .= __('If this was a mistake, just ignore this email and nothing will happen.') . "\r\n\r\n";
$message .= __('To reset your password, visit the following address:') . "\r\n\r\n";
$message .= '<' . network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login') . ">\r\n";
if ( is_multisite() )
$blogname = $GLOBALS['current_site']->site_name;
else
$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
$title = sprintf( __('[%s] Password Reset'), $blogname );
$title = apply_filters('retrieve_password_title', $title);
$message = apply_filters('retrieve_password_message', $message, $key);
if ( $message && !wp_mail($user_email, $title, $message) )
$json_api->error("The e-mail could not be sent. Possible reason: your host may have disabled the mail() function...");
else
return array(
"msg" => 'Link for password reset has been emailed to you. Please check your email.',
);
}
public function validate_auth_cookie() {
global $json_api;
if (!$json_api->query->cookie) {
$json_api->error("You must include a 'cookie' authentication cookie. Use the `create_auth_cookie` method.");
}
$valid = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in') ? true : false;
return array(
"valid" => $valid
);
}
public function generate_auth_cookie() {
global $json_api;
foreach($_POST as $k=>$val) {
if (isset($_POST[$k])) {
$json_api->query->$k = $val;
}
}
if (!$json_api->query->username && !$json_api->query->email) {
$json_api->error("You must include 'username' or 'email' var in your request to generate cookie.");
}
if (!$json_api->query->password) {
$json_api->error("You must include a 'password' var in your request.");
}
if ($json_api->query->seconds) $seconds = (int) $json_api->query->seconds;
else $seconds = 1209600;//14 days
if ( $json_api->query->email ) {
if ( is_email( $json_api->query->email ) ) {
if( !email_exists( $json_api->query->email)) {
$json_api->error("email does not exist.");
}
}else $json_api->error("Invalid email address.");
$user_obj = get_user_by( 'email', $json_api->query->email );
$user = wp_authenticate($user_obj->data->user_login, $json_api->query->password);
}else {
$user = wp_authenticate($json_api->query->username, $json_api->query->password);
}
if (is_wp_error($user)) {
$json_api->error("Invalid username/email and/or password.", 'error', '401');
remove_action('wp_login_failed', $json_api->query->username);
}
$expiration = time() + apply_filters('auth_cookie_expiration', $seconds, $user->ID, true);
$cookie = wp_generate_auth_cookie($user->ID, $expiration, 'logged_in');
preg_match('|src="(.+?)"|', get_avatar( $user->ID, 512 ), $avatar);
return array(
"cookie" => $cookie,
"cookie_name" => LOGGED_IN_COOKIE,
"user" => array(
"id" => $user->ID,
"username" => $user->user_login,
"nicename" => $user->user_nicename,
"email" => $user->user_email,
"url" => $user->user_url,
"registered" => $user->user_registered,
"displayname" => $user->display_name,
"firstname" => $user->user_firstname,
"lastname" => $user->last_name,
"nickname" => $user->nickname,
"description" => $user->user_description,
"capabilities" => $user->wp_capabilities,
"avatar" => $avatar[1]
),
);
}
public function get_currentuserinfo() {
global $json_api;
if (!$json_api->query->cookie) {
$json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` Auth API method.");
}
$user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
if (!$user_id) {
$json_api->error("Invalid authentication cookie. Use the `generate_auth_cookie` method.");
}
$user = get_userdata($user_id);
preg_match('|src="(.+?)"|', get_avatar( $user->ID, 32 ), $avatar);
return array(
"user" => array(
"id" => $user->ID,
"username" => $user->user_login,
"nicename" => $user->user_nicename,
"email" => $user->user_email,
"url" => $user->user_url,
"registered" => $user->user_registered,
"displayname" => $user->display_name,
"firstname" => $user->user_firstname,
"lastname" => $user->last_name,
"nickname" => $user->nickname,
"description" => $user->user_description,
"capabilities" => $user->wp_capabilities,
"avatar" => $avatar[1]
)
);
}
public function get_user_meta() {
global $json_api;
if (!$json_api->query->cookie) {
$json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
}
$user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
if (!$user_id) $json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
$meta_key = sanitize_text_field($json_api->query->meta_key);
if($meta_key) $data[$meta_key] = get_user_meta( $user_id, $meta_key);
else {
// Get all user meta data for $user_id
$meta = get_user_meta( $user_id );
// Filter out empty meta data
$data = array_filter( array_map( function( $a ) {
return $a[0];
}, $meta ) );
}
//d($data);
return $data;
}
public function update_user_meta() {
global $json_api;
if (!$json_api->query->cookie) {
$json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
}
$user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
if (!$user_id) $json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
if (!$json_api->query->meta_key) $json_api->error("You must include a 'meta_key' var in your request.");
else $meta_key = $json_api->query->meta_key;
if (!$json_api->query->meta_value) {
$json_api->error("You must include a 'meta_value' var in your request. You may provide multiple values separated by comma for 'meta_value' var.");
}
else $meta_value = sanitize_text_field($json_api->query->meta_value);
if( strpos($meta_value,',') !== false ) {
$meta_values = explode(",", $meta_value);
$meta_values = array_map('trim',$meta_values);
$data['updated'] = update_user_meta( $user_id, $meta_key, $meta_values);
}
else $data['updated'] = update_user_meta( $user_id, $meta_key, $meta_value);
return $data;
}
public function delete_user_meta() {
global $json_api;
if (!$json_api->query->cookie) {
$json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
}
$user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
if (!$user_id) $json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
if (!$json_api->query->meta_key) $json_api->error("You must include a 'meta_key' var in your request.");
else $meta_key = $json_api->query->meta_key;
if (!$json_api->query->meta_value) {
$json_api->error("You must include a 'meta_value' var in your request.");
}
else $meta_value = sanitize_text_field($json_api->query->meta_value);
$data['deleted'] = delete_user_meta( $user_id, $meta_key, $meta_value);
return $data;
}
public function update_user_meta_vars() {
global $json_api;
if (!$json_api->query->cookie) {
$json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
}
$user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
// echo '$user_id: '.$user_id;
if (!$user_id) {
$json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
}
if( sizeof($_REQUEST) <=1) $json_api->error("You must include one or more vars in your request to add or update as user_meta. e.g. 'name', 'website', 'skills'. You must provide multiple meta_key vars in this format: &name=Ali&website=parorrey.com&skills=php,css,js,web design. If any field has the possibility to hold more than one value for any multi-select fields or check boxes, you must provide ending comma even when it has only one value so that it could be added in correct array format to distinguish it from simple string var. e.g. &skills=php,");
//d($_REQUEST);
foreach($_REQUEST as $field => $value){
if($field=='cookie') continue;
$field_label = str_replace('_',' ',$field);
if( strpos($value,',') !== false ) {
$values = explode(",", $value);
$values = array_map('trim',$values);
}
else $values = trim($value);
//echo 'field-values: '.$field.'=>'.$value;
//d($values);
$result[$field_label]['updated'] = update_user_meta( $user_id, $field, $values);
}
return $result;
}
public function xprofile() {
global $json_api;
if (function_exists('bp_is_active')) {
if (!$json_api->query->user_id) {
$json_api->error("You must include a 'user_id' var in your request.");
}
else $user_id = $json_api->query->user_id;
if (!$json_api->query->field) {
$json_api->error("You must include a 'field' var in your request. Use 'field=default' for all default fields.");
}
elseif ($json_api->query->field=='default') {
$field_label='First Name, Last Name, Bio';/*you should add your own field labels here for quick viewing*/
}
else $field_label = sanitize_text_field($json_api->query->field);
$fields = explode(",", $field_label);
if(is_array($fields)){
foreach($fields as $k){
$fields_data[$k] = xprofile_get_field_data( $k, $user_id );
}
return $fields_data;
}
}
else {
$json_api->error("You must install and activate BuddyPress plugin to use this method.");
}
}
public function xprofile_update() {
global $json_api;
if (function_exists('bp_is_active')) {
if (!$json_api->query->cookie) {
$json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
}
$user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
// echo '$user_id: '.$user_id;
if (!$user_id) {
$json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
}
foreach($_REQUEST as $field => $value){
if($field=='cookie') continue;
$field_label = str_replace('_',' ',$field);
if( strpos($value,',') !== false ) {
$values = explode(",", $value);
$values = array_map('trim',$values);
}
else $values = trim($value);
//echo 'field-values: '.$field.'=>'.$value;
//d($values);
$result[$field_label]['updated'] = xprofile_set_field_data( $field_label, $user_id, $values, $is_required = true );
}
return $result;
}
else {
$json_api->error("You must install and activate BuddyPress plugin to use this method.");
}
}
public function fb_connect(){
global $json_api;
if ($json_api->query->fields) {
$fields = $json_api->query->fields;
}else $fields = 'id,name,first_name,last_name,email';
if ($json_api->query->ssl) {
$enable_ssl = $json_api->query->ssl;
}else $enable_ssl = true;
if (!$json_api->query->access_token) {
$json_api->error("You must include a 'access_token' variable. Get the valid access_token for this app from Facebook API.");
}else{
$url='https://graph.facebook.com/me/?fields='.$fields.'&access_token='.$json_api->query->access_token;
// Initiate curl
$ch = curl_init();
// Enable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $enable_ssl);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
$result = json_decode($result, true);
if(isset($result["email"])){
$user_email = $result["email"];
$email_exists = email_exists($user_email);
if($email_exists) {
$user = get_user_by( 'email', $user_email );
$user_id = $user->ID;
$user_name = $user->user_login;
}
if ( !$user_id && $email_exists == false ) {
$user_name = strtolower($result['first_name'].'.'.$result['last_name']);
while(username_exists($user_name)){
$i++;
$user_name = strtolower($result['first_name'].'.'.$result['last_name']).'.'.$i;
}
$random_password = wp_generate_password( $length=12, $include_standard_special_chars=false );
$userdata = array(
'user_login' => $user_name,
'user_email' => $user_email,
'user_pass' => $random_password,
'display_name' => $result["name"],
'first_name' => $result['first_name'],
'last_name' => $result['last_name']
);
$user_id = wp_insert_user( $userdata ) ;
if($user_id) $user_account = 'user registered.';
} else {
if($user_id) $user_account = 'user logged in.';
}
$expiration = time() + apply_filters('auth_cookie_expiration', 1209600, $user_id, true);
$cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in');
$response['msg'] = $user_account;
$response['wp_user_id'] = $user_id;
$response['cookie'] = $cookie;
$response['user_login'] = $user_name;
}
else {
$response['msg'] = "Your 'access_token' did not return email of the user. Without 'email' user can't be logged in or registered. Get user email extended permission while joining the Facebook app.";
}
}
return $response;
}
public function post_comment(){
global $json_api;
if (!$json_api->query->cookie) {
$json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
}
$user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
if (!$user_id) {
$json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
}
if ( !$json_api->query->post_id ) {
$json_api->error("No post specified. Include 'post_id' var in your request.");
} elseif (!$json_api->query->content ) {
$json_api->error("Please include 'content' var in your request.");
}
if (!$json_api->query->comment_status ) {
$json_api->error("Please include 'comment_status' var in your request. Possible values are '1' (approved) or '0' (not-approved)");
}else $comment_approved = $json_api->query->comment_status;
$user_info = get_userdata( $user_id );
$time = current_time('mysql');
$agent = $_SERVER['HTTP_USER_AGENT'];
$ip=$_SERVER['REMOTE_ADDR'];
$data = array(
'comment_post_ID' => $json_api->query->post_id,
'comment_author' => $user_info->user_login,
'comment_author_email' => $user_info->user_email,
'comment_author_url' => $user_info->user_url,
'comment_content' => $json_api->query->content,
'comment_type' => '',
'comment_parent' => 0,
'user_id' => $user_info->ID,
'comment_author_IP' => $ip,
'comment_agent' => $agent,
'comment_date' => $time,
'comment_approved' => $comment_approved,
);
//print_r($data);
$comment_id = wp_insert_comment($data);
return array(
"comment_id" => $comment_id
);
}
}
</code></pre>
|
[
{
"answer_id": 251282,
"author": "Nathan Crause",
"author_id": 81384,
"author_profile": "https://wordpress.stackexchange.com/users/81384",
"pm_score": 0,
"selected": false,
"text": "<p>This comes down to a server configuration - if you have enabled \"allow_url_fopen\" in your php.ini you could simply open the URLs using fopen, but from your example using this method might cause some issues with SSL so you may want to look here for how to deal with that <a href=\"https://stackoverflow.com/questions/32820376/fopen-accept-self-signed-certificate\">https://stackoverflow.com/questions/32820376/fopen-accept-self-signed-certificate</a></p>\n"
},
{
"answer_id": 251352,
"author": "Ryan McCue",
"author_id": 11497,
"author_profile": "https://wordpress.stackexchange.com/users/11497",
"pm_score": 2,
"selected": false,
"text": "<p>You can internally route REST API requests using <a href=\"https://developer.wordpress.org/reference/functions/rest_do_request/\" rel=\"nofollow noreferrer\"><code>rest_do_request</code></a> and a <a href=\"https://developer.wordpress.org/reference/classes/wp_rest_request/\" rel=\"nofollow noreferrer\"><code>WP_REST_Request</code> object</a>.</p>\n\n<pre><code>$request = new WP_REST_Request( 'GET', '/fb_connect' );\n$request->set_param( 'x', true );\n// You can also use it this way:\n$request['y'] = true;\n$request['z'] = true;\n\n$response = rest_do_request( $request );\n</code></pre>\n"
}
] |
2017/01/04
|
[
"https://wordpress.stackexchange.com/questions/251278",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13170/"
] |
I'm using the [JSON REST User plugin](https://wordpress.org/plugins/json-api-user/) which extends [JSON REST Api](https://wordpress.org/plugins/json-api/). I'm sending http data to-from the api up to 4 times back to back in some cases which is dragging network performance.
How can I call
`http://localhost/wp-json/fb_connect?x&y&z`
from php without using curl? (I'll use curl if it makes the most sense)
*the main plugin file, where the fb\_connect function is:*
**/wp-content/plugins/json-api-user/controllers/User.php**
```
/*
Controller name: User
Controller description: User Registration, Authentication, User Info, User Meta, FB Login, BuddyPress xProfile Fields methods
Controller Author: Ali Qureshi
Controller Author Twitter: @parorrey
Controller Author Website: parorrey.com
*/
class JSON_API_User_Controller {
/**
* Returns an Array with registered userid & valid cookie
* @param String username: username to register
* @param String email: email address for user registration
* @param String user_pass: user_pass to be set (optional)
* @param String display_name: display_name for user
*/
public function __construct() {
global $json_api;
// allow only connection over https. because, well, you care about your passwords and sniffing.
// turn this sanity-check off if you feel safe inside your localhost or intranet.
// send an extra POST parameter: insecure=cool
if (empty($_SERVER['HTTPS']) ||
(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'off')) {
if (empty($_REQUEST['insecure']) || $_REQUEST['insecure'] != 'cool') {
$json_api->error("SSL is not enabled. Either use _https_ or provide 'insecure' var as insecure=cool to confirm you want to use http protocol.");
}
}
}
public function info(){
global $json_api;
return array(
"version" => JAU_VERSION
);
}
public function register(){
global $json_api;
if (!get_option('users_can_register')) {
$json_api->error("User registration is disabled. Please enable it in Settings > Gereral.");
}
if (!$json_api->query->username) {
$json_api->error("You must include 'username' var in your request. ");
}
else $username = sanitize_user( $json_api->query->username );
if (!$json_api->query->email) {
$json_api->error("You must include 'email' var in your request. ");
}
else $email = sanitize_email( $json_api->query->email );
if (!$json_api->query->nonce) {
$json_api->error("You must include 'nonce' var in your request. Use the 'get_nonce' Core API method. ");
}
else $nonce = sanitize_text_field( $json_api->query->nonce ) ;
if (!$json_api->query->display_name) {
$json_api->error("You must include 'display_name' var in your request. ");
}
else $display_name = sanitize_text_field( $json_api->query->display_name );
$user_pass = sanitize_text_field( $_REQUEST['user_pass'] );
if ($json_api->query->seconds) $seconds = (int) $json_api->query->seconds;
else $seconds = 1209600;//14 days
//Add usernames we don't want used
$invalid_usernames = array( 'admin' );
//Do username validation
$nonce_id = $json_api->get_nonce_id('user', 'register');
if( !wp_verify_nonce($json_api->query->nonce, $nonce_id) ) {
$json_api->error("Invalid access, unverifiable 'nonce' value. Use the 'get_nonce' Core API method. ");
}
else {
if ( !validate_username( $username ) || in_array( $username, $invalid_usernames ) ) {
$json_api->error("Username is invalid.");
}
elseif ( username_exists( $username ) ) {
$json_api->error("Username already exists.");
}
else{
if ( !is_email( $email ) ) {
$json_api->error("E-mail address is invalid.");
}
elseif (email_exists($email)) {
$json_api->error("E-mail address is already in use.");
}
else {
//Everything has been validated, proceed with creating the user
//Create the user
if( !isset($_REQUEST['user_pass']) ) {
$user_pass = wp_generate_password();
$_REQUEST['user_pass'] = $user_pass;
}
$_REQUEST['user_login'] = $username;
$_REQUEST['user_email'] = $email;
$allowed_params = array('user_login', 'user_email', 'user_pass', 'display_name', 'user_nicename', 'user_url', 'nickname', 'first_name',
'last_name', 'description', 'rich_editing', 'user_registered', 'role', 'jabber', 'aim', 'yim',
'comment_shortcuts', 'admin_color', 'use_ssl', 'show_admin_bar_front'
);
foreach($_REQUEST as $field => $value){
if( in_array($field, $allowed_params) ) $user[$field] = trim(sanitize_text_field($value));
}
$user['role'] = get_option('default_role');
$user_id = wp_insert_user( $user );
/*Send e-mail to admin and new user -
You could create your own e-mail instead of using this function*/
if( isset($_REQUEST['user_pass']) && $_REQUEST['notify']=='no') {
$notify = '';
}elseif($_REQUEST['notify']!='no') $notify = $_REQUEST['notify'];
if($user_id) wp_new_user_notification( $user_id, '',$notify );
}
}
}
$expiration = time() + apply_filters('auth_cookie_expiration', $seconds, $user_id, true);
$cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in');
return array(
"cookie" => $cookie,
"user_id" => $user_id
);
}
public function get_avatar(){
global $json_api;
if (function_exists('bp_is_active')) {
if (!$json_api->query->user_id) {
$json_api->error("You must include 'user_id' var in your request. ");
}
if (!$json_api->query->type) {
$json_api->error("You must include 'type' var in your request. possible values 'full' or 'thumb' ");
}
$avatar = bp_core_fetch_avatar ( array( 'item_id' => $json_api->query->user_id, 'type' => $json_api->query->type, 'html'=>false ));
return array('avatar'=>$avatar);
} else {
$json_api->error("You must install and activate BuddyPress plugin to use this method.");
}
}
public function get_userinfo(){
global $json_api;
if (!$json_api->query->user_id) {
$json_api->error("You must include 'user_id' var in your request. ");
}
$user = get_userdata($json_api->query->user_id);
preg_match('|src="(.+?)"|', get_avatar( $user->ID, 32 ), $avatar);
return array(
"id" => $user->ID,
//"username" => $user->user_login,
"nicename" => $user->user_nicename,
//"email" => $user->user_email,
"url" => $user->user_url,
"displayname" => $user->display_name,
"firstname" => $user->user_firstname,
"lastname" => $user->last_name,
"nickname" => $user->nickname,
"avatar" => $avatar[1]
);
}
public function retrieve_password(){
global $wpdb, $json_api, $wp_hasher;
if (!$json_api->query->user_login) {
$json_api->error("You must include 'user_login' var in your request. ");
}
$user_login = $json_api->query->user_login;
if ( strpos( $user_login, '@' ) ) {
$user_data = get_user_by( 'email', trim( $user_login ) );
if ( empty( $user_data ) )
$json_api->error("Your email address not found! ");
} else {
$login = trim($user_login);
$user_data = get_user_by('login', $login);
}
// redefining user_login ensures we return the right case in the email
$user_login = $user_data->user_login;
$user_email = $user_data->user_email;
do_action('retrieve_password', $user_login);
$allow = apply_filters('allow_password_reset', true, $user_data->ID);
if ( ! $allow ) $json_api->error("password reset not allowed! ");
elseif ( is_wp_error($allow) ) $json_api->error("An error occured! ");
$key = wp_generate_password( 20, false );
do_action( 'retrieve_password_key', $user_login, $key );
if ( empty( $wp_hasher ) ) {
require_once ABSPATH . 'wp-includes/class-phpass.php';
$wp_hasher = new PasswordHash( 8, true );
}
$hashed = time() . ':' . $wp_hasher->HashPassword( $key );
$wpdb->update( $wpdb->users, array( 'user_activation_key' => $hashed ), array( 'user_login' => $user_login ) );
$message = __('Someone requested that the password be reset for the following account:') . "\r\n\r\n";
$message .= network_home_url( '/' ) . "\r\n\r\n";
$message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
$message .= __('If this was a mistake, just ignore this email and nothing will happen.') . "\r\n\r\n";
$message .= __('To reset your password, visit the following address:') . "\r\n\r\n";
$message .= '<' . network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login') . ">\r\n";
if ( is_multisite() )
$blogname = $GLOBALS['current_site']->site_name;
else
$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
$title = sprintf( __('[%s] Password Reset'), $blogname );
$title = apply_filters('retrieve_password_title', $title);
$message = apply_filters('retrieve_password_message', $message, $key);
if ( $message && !wp_mail($user_email, $title, $message) )
$json_api->error("The e-mail could not be sent. Possible reason: your host may have disabled the mail() function...");
else
return array(
"msg" => 'Link for password reset has been emailed to you. Please check your email.',
);
}
public function validate_auth_cookie() {
global $json_api;
if (!$json_api->query->cookie) {
$json_api->error("You must include a 'cookie' authentication cookie. Use the `create_auth_cookie` method.");
}
$valid = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in') ? true : false;
return array(
"valid" => $valid
);
}
public function generate_auth_cookie() {
global $json_api;
foreach($_POST as $k=>$val) {
if (isset($_POST[$k])) {
$json_api->query->$k = $val;
}
}
if (!$json_api->query->username && !$json_api->query->email) {
$json_api->error("You must include 'username' or 'email' var in your request to generate cookie.");
}
if (!$json_api->query->password) {
$json_api->error("You must include a 'password' var in your request.");
}
if ($json_api->query->seconds) $seconds = (int) $json_api->query->seconds;
else $seconds = 1209600;//14 days
if ( $json_api->query->email ) {
if ( is_email( $json_api->query->email ) ) {
if( !email_exists( $json_api->query->email)) {
$json_api->error("email does not exist.");
}
}else $json_api->error("Invalid email address.");
$user_obj = get_user_by( 'email', $json_api->query->email );
$user = wp_authenticate($user_obj->data->user_login, $json_api->query->password);
}else {
$user = wp_authenticate($json_api->query->username, $json_api->query->password);
}
if (is_wp_error($user)) {
$json_api->error("Invalid username/email and/or password.", 'error', '401');
remove_action('wp_login_failed', $json_api->query->username);
}
$expiration = time() + apply_filters('auth_cookie_expiration', $seconds, $user->ID, true);
$cookie = wp_generate_auth_cookie($user->ID, $expiration, 'logged_in');
preg_match('|src="(.+?)"|', get_avatar( $user->ID, 512 ), $avatar);
return array(
"cookie" => $cookie,
"cookie_name" => LOGGED_IN_COOKIE,
"user" => array(
"id" => $user->ID,
"username" => $user->user_login,
"nicename" => $user->user_nicename,
"email" => $user->user_email,
"url" => $user->user_url,
"registered" => $user->user_registered,
"displayname" => $user->display_name,
"firstname" => $user->user_firstname,
"lastname" => $user->last_name,
"nickname" => $user->nickname,
"description" => $user->user_description,
"capabilities" => $user->wp_capabilities,
"avatar" => $avatar[1]
),
);
}
public function get_currentuserinfo() {
global $json_api;
if (!$json_api->query->cookie) {
$json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` Auth API method.");
}
$user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
if (!$user_id) {
$json_api->error("Invalid authentication cookie. Use the `generate_auth_cookie` method.");
}
$user = get_userdata($user_id);
preg_match('|src="(.+?)"|', get_avatar( $user->ID, 32 ), $avatar);
return array(
"user" => array(
"id" => $user->ID,
"username" => $user->user_login,
"nicename" => $user->user_nicename,
"email" => $user->user_email,
"url" => $user->user_url,
"registered" => $user->user_registered,
"displayname" => $user->display_name,
"firstname" => $user->user_firstname,
"lastname" => $user->last_name,
"nickname" => $user->nickname,
"description" => $user->user_description,
"capabilities" => $user->wp_capabilities,
"avatar" => $avatar[1]
)
);
}
public function get_user_meta() {
global $json_api;
if (!$json_api->query->cookie) {
$json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
}
$user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
if (!$user_id) $json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
$meta_key = sanitize_text_field($json_api->query->meta_key);
if($meta_key) $data[$meta_key] = get_user_meta( $user_id, $meta_key);
else {
// Get all user meta data for $user_id
$meta = get_user_meta( $user_id );
// Filter out empty meta data
$data = array_filter( array_map( function( $a ) {
return $a[0];
}, $meta ) );
}
//d($data);
return $data;
}
public function update_user_meta() {
global $json_api;
if (!$json_api->query->cookie) {
$json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
}
$user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
if (!$user_id) $json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
if (!$json_api->query->meta_key) $json_api->error("You must include a 'meta_key' var in your request.");
else $meta_key = $json_api->query->meta_key;
if (!$json_api->query->meta_value) {
$json_api->error("You must include a 'meta_value' var in your request. You may provide multiple values separated by comma for 'meta_value' var.");
}
else $meta_value = sanitize_text_field($json_api->query->meta_value);
if( strpos($meta_value,',') !== false ) {
$meta_values = explode(",", $meta_value);
$meta_values = array_map('trim',$meta_values);
$data['updated'] = update_user_meta( $user_id, $meta_key, $meta_values);
}
else $data['updated'] = update_user_meta( $user_id, $meta_key, $meta_value);
return $data;
}
public function delete_user_meta() {
global $json_api;
if (!$json_api->query->cookie) {
$json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
}
$user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
if (!$user_id) $json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
if (!$json_api->query->meta_key) $json_api->error("You must include a 'meta_key' var in your request.");
else $meta_key = $json_api->query->meta_key;
if (!$json_api->query->meta_value) {
$json_api->error("You must include a 'meta_value' var in your request.");
}
else $meta_value = sanitize_text_field($json_api->query->meta_value);
$data['deleted'] = delete_user_meta( $user_id, $meta_key, $meta_value);
return $data;
}
public function update_user_meta_vars() {
global $json_api;
if (!$json_api->query->cookie) {
$json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
}
$user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
// echo '$user_id: '.$user_id;
if (!$user_id) {
$json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
}
if( sizeof($_REQUEST) <=1) $json_api->error("You must include one or more vars in your request to add or update as user_meta. e.g. 'name', 'website', 'skills'. You must provide multiple meta_key vars in this format: &name=Ali&website=parorrey.com&skills=php,css,js,web design. If any field has the possibility to hold more than one value for any multi-select fields or check boxes, you must provide ending comma even when it has only one value so that it could be added in correct array format to distinguish it from simple string var. e.g. &skills=php,");
//d($_REQUEST);
foreach($_REQUEST as $field => $value){
if($field=='cookie') continue;
$field_label = str_replace('_',' ',$field);
if( strpos($value,',') !== false ) {
$values = explode(",", $value);
$values = array_map('trim',$values);
}
else $values = trim($value);
//echo 'field-values: '.$field.'=>'.$value;
//d($values);
$result[$field_label]['updated'] = update_user_meta( $user_id, $field, $values);
}
return $result;
}
public function xprofile() {
global $json_api;
if (function_exists('bp_is_active')) {
if (!$json_api->query->user_id) {
$json_api->error("You must include a 'user_id' var in your request.");
}
else $user_id = $json_api->query->user_id;
if (!$json_api->query->field) {
$json_api->error("You must include a 'field' var in your request. Use 'field=default' for all default fields.");
}
elseif ($json_api->query->field=='default') {
$field_label='First Name, Last Name, Bio';/*you should add your own field labels here for quick viewing*/
}
else $field_label = sanitize_text_field($json_api->query->field);
$fields = explode(",", $field_label);
if(is_array($fields)){
foreach($fields as $k){
$fields_data[$k] = xprofile_get_field_data( $k, $user_id );
}
return $fields_data;
}
}
else {
$json_api->error("You must install and activate BuddyPress plugin to use this method.");
}
}
public function xprofile_update() {
global $json_api;
if (function_exists('bp_is_active')) {
if (!$json_api->query->cookie) {
$json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
}
$user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
// echo '$user_id: '.$user_id;
if (!$user_id) {
$json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
}
foreach($_REQUEST as $field => $value){
if($field=='cookie') continue;
$field_label = str_replace('_',' ',$field);
if( strpos($value,',') !== false ) {
$values = explode(",", $value);
$values = array_map('trim',$values);
}
else $values = trim($value);
//echo 'field-values: '.$field.'=>'.$value;
//d($values);
$result[$field_label]['updated'] = xprofile_set_field_data( $field_label, $user_id, $values, $is_required = true );
}
return $result;
}
else {
$json_api->error("You must install and activate BuddyPress plugin to use this method.");
}
}
public function fb_connect(){
global $json_api;
if ($json_api->query->fields) {
$fields = $json_api->query->fields;
}else $fields = 'id,name,first_name,last_name,email';
if ($json_api->query->ssl) {
$enable_ssl = $json_api->query->ssl;
}else $enable_ssl = true;
if (!$json_api->query->access_token) {
$json_api->error("You must include a 'access_token' variable. Get the valid access_token for this app from Facebook API.");
}else{
$url='https://graph.facebook.com/me/?fields='.$fields.'&access_token='.$json_api->query->access_token;
// Initiate curl
$ch = curl_init();
// Enable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $enable_ssl);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
$result = json_decode($result, true);
if(isset($result["email"])){
$user_email = $result["email"];
$email_exists = email_exists($user_email);
if($email_exists) {
$user = get_user_by( 'email', $user_email );
$user_id = $user->ID;
$user_name = $user->user_login;
}
if ( !$user_id && $email_exists == false ) {
$user_name = strtolower($result['first_name'].'.'.$result['last_name']);
while(username_exists($user_name)){
$i++;
$user_name = strtolower($result['first_name'].'.'.$result['last_name']).'.'.$i;
}
$random_password = wp_generate_password( $length=12, $include_standard_special_chars=false );
$userdata = array(
'user_login' => $user_name,
'user_email' => $user_email,
'user_pass' => $random_password,
'display_name' => $result["name"],
'first_name' => $result['first_name'],
'last_name' => $result['last_name']
);
$user_id = wp_insert_user( $userdata ) ;
if($user_id) $user_account = 'user registered.';
} else {
if($user_id) $user_account = 'user logged in.';
}
$expiration = time() + apply_filters('auth_cookie_expiration', 1209600, $user_id, true);
$cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in');
$response['msg'] = $user_account;
$response['wp_user_id'] = $user_id;
$response['cookie'] = $cookie;
$response['user_login'] = $user_name;
}
else {
$response['msg'] = "Your 'access_token' did not return email of the user. Without 'email' user can't be logged in or registered. Get user email extended permission while joining the Facebook app.";
}
}
return $response;
}
public function post_comment(){
global $json_api;
if (!$json_api->query->cookie) {
$json_api->error("You must include a 'cookie' var in your request. Use the `generate_auth_cookie` method.");
}
$user_id = wp_validate_auth_cookie($json_api->query->cookie, 'logged_in');
if (!$user_id) {
$json_api->error("Invalid cookie. Use the `generate_auth_cookie` method.");
}
if ( !$json_api->query->post_id ) {
$json_api->error("No post specified. Include 'post_id' var in your request.");
} elseif (!$json_api->query->content ) {
$json_api->error("Please include 'content' var in your request.");
}
if (!$json_api->query->comment_status ) {
$json_api->error("Please include 'comment_status' var in your request. Possible values are '1' (approved) or '0' (not-approved)");
}else $comment_approved = $json_api->query->comment_status;
$user_info = get_userdata( $user_id );
$time = current_time('mysql');
$agent = $_SERVER['HTTP_USER_AGENT'];
$ip=$_SERVER['REMOTE_ADDR'];
$data = array(
'comment_post_ID' => $json_api->query->post_id,
'comment_author' => $user_info->user_login,
'comment_author_email' => $user_info->user_email,
'comment_author_url' => $user_info->user_url,
'comment_content' => $json_api->query->content,
'comment_type' => '',
'comment_parent' => 0,
'user_id' => $user_info->ID,
'comment_author_IP' => $ip,
'comment_agent' => $agent,
'comment_date' => $time,
'comment_approved' => $comment_approved,
);
//print_r($data);
$comment_id = wp_insert_comment($data);
return array(
"comment_id" => $comment_id
);
}
}
```
|
You can internally route REST API requests using [`rest_do_request`](https://developer.wordpress.org/reference/functions/rest_do_request/) and a [`WP_REST_Request` object](https://developer.wordpress.org/reference/classes/wp_rest_request/).
```
$request = new WP_REST_Request( 'GET', '/fb_connect' );
$request->set_param( 'x', true );
// You can also use it this way:
$request['y'] = true;
$request['z'] = true;
$response = rest_do_request( $request );
```
|
251,295 |
<p>I have a situation where it would be ideal to have the database on separate hosting. Just because the host of the current site does not offer mysql. I cannot move the site (for a company)</p>
<p>Can I install wordpress on current hosting in a sub domain and have the database on another host? I have never used anything except “localhost” in the wp-config file? Thank you!</p>
|
[
{
"answer_id": 251297,
"author": "jdm2112",
"author_id": 45202,
"author_profile": "https://wordpress.stackexchange.com/users/45202",
"pm_score": 2,
"selected": false,
"text": "<p>Yes - absolutely. Simply enter the appropriate hostname and credentials in wp-config.php. Instead of the default <code>localhost</code> use the hostname provided by your database provider.</p>\n\n<p>Example:</p>\n\n<pre><code>define( 'DB_HOST', 'mysql.example.com:3307' );\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Editing_wp-config.php#Set_Database_Host\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Editing_wp-config.php#Set_Database_Host</a></p>\n"
},
{
"answer_id": 251300,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>In theory you can. You can specify the hostname or ip address of the DB server and communicate with it. </p>\n\n<p>In practice this is unlikely to work well because:</p>\n\n<ol>\n<li><p>Performance might suck. The speed of information transfer on the same server or in a LAN is much higher than what you will get when you need to communicate over the internet</p></li>\n<li><p>You will have to leave the DB open to attacks. DBs are rarely exposed directly to the internet and I am not sure how good is MySQL security track record, but even in the best case you will have to worry about attacks on two servers instead of one.</p></li>\n</ol>\n\n<p>Short version: don't do it. If the hosting sucks you either need to go away or select a different CMS that fits better what you can get from the hosting</p>\n"
},
{
"answer_id": 405282,
"author": "Mathieu Leclerc",
"author_id": 221755,
"author_profile": "https://wordpress.stackexchange.com/users/221755",
"pm_score": 0,
"selected": false,
"text": "<p>This question to my opinion is very important. I still do research on how to store the data on a specific local RAID. I dont think there is going to be a lack of performance doing so. If wordpress is on a RAID-10 and the database on a RAID-5 HDD within local hardware I am curious to know what can be wrong?</p>\n"
}
] |
2017/01/04
|
[
"https://wordpress.stackexchange.com/questions/251295",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110222/"
] |
I have a situation where it would be ideal to have the database on separate hosting. Just because the host of the current site does not offer mysql. I cannot move the site (for a company)
Can I install wordpress on current hosting in a sub domain and have the database on another host? I have never used anything except “localhost” in the wp-config file? Thank you!
|
Yes - absolutely. Simply enter the appropriate hostname and credentials in wp-config.php. Instead of the default `localhost` use the hostname provided by your database provider.
Example:
```
define( 'DB_HOST', 'mysql.example.com:3307' );
```
<https://codex.wordpress.org/Editing_wp-config.php#Set_Database_Host>
|
251,298 |
<p>Ok, i've tried all day long and do not know, how this can be. I have a website on which i load jquery like that:</p>
<pre><code>function my_script_loader() {
if (!is_admin()) { // only load for front end
//Clear jQuery if already registered
wp_deregister_script('jquery');
wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js", array(), '1.11.1', '',true);
wp_enqueue_script('jquery');
} // End of if statement
} // End of Function
add_action('wp_enqueue_scripts', 'my_script_loader');
</code></pre>
<p>The expected result in the Dom is:</p>
<pre><code><script type="text/javascript" defer="defer" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</code></pre>
<p>Then i am doing the exact same thing on another website which is a subdomain:</p>
<pre><code>function script_loader() {
if (!is_admin()) {
//Clear jQuery if already registered
wp_deregister_script('jquery');
wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js", array() , '1.12.4', '',true);
wp_enqueue_script('jquery');
}
} // End of Function
add_action('wp_enqueue_scripts', 'script_loader');
</code></pre>
<p>The unexpected result in the Dom is:</p>
<pre><code><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js?ver=1.12.4">
</code></pre>
<p>I have disabled plugins and removed all scripts but the script is not deferred. How can that happen?
Thanks for your interest.
theo</p>
|
[
{
"answer_id": 251301,
"author": "iguanarama",
"author_id": 109807,
"author_profile": "https://wordpress.stackexchange.com/users/109807",
"pm_score": 2,
"selected": true,
"text": "<p>As <strong>Mark Kaplun</strong> said in the comments, something is adding <code>defer</code> to your one domain's script.</p>\n\n<p>If you want your subdomain jQuery script to also have <code>defer</code>, this should do it:</p>\n\n<pre><code>function my_add_defer ($tag, $handle, $src) {\n if ($handle == 'jquery') {\n return str_replace (' src=', ' defer=\"defer\" src=', $tag);\n }\n return $tag;\n}\nadd_filter ('script_loader_tag', 'my_add_defer', 10, 3);\n</code></pre>\n"
},
{
"answer_id": 251332,
"author": "timholz",
"author_id": 71669,
"author_profile": "https://wordpress.stackexchange.com/users/71669",
"pm_score": 0,
"selected": false,
"text": "<p>This is the one, that caused the difference and that i was missing:</p>\n\n<pre><code>function defer_parsing_of_js ( $url ) {\nif ( FALSE === strpos( $url, '.js' ) ) return $url;\n\nreturn \"$url' defer='defer\";\n }\nadd_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 );\n</code></pre>\n"
}
] |
2017/01/04
|
[
"https://wordpress.stackexchange.com/questions/251298",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71669/"
] |
Ok, i've tried all day long and do not know, how this can be. I have a website on which i load jquery like that:
```
function my_script_loader() {
if (!is_admin()) { // only load for front end
//Clear jQuery if already registered
wp_deregister_script('jquery');
wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js", array(), '1.11.1', '',true);
wp_enqueue_script('jquery');
} // End of if statement
} // End of Function
add_action('wp_enqueue_scripts', 'my_script_loader');
```
The expected result in the Dom is:
```
<script type="text/javascript" defer="defer" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
```
Then i am doing the exact same thing on another website which is a subdomain:
```
function script_loader() {
if (!is_admin()) {
//Clear jQuery if already registered
wp_deregister_script('jquery');
wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js", array() , '1.12.4', '',true);
wp_enqueue_script('jquery');
}
} // End of Function
add_action('wp_enqueue_scripts', 'script_loader');
```
The unexpected result in the Dom is:
```
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js?ver=1.12.4">
```
I have disabled plugins and removed all scripts but the script is not deferred. How can that happen?
Thanks for your interest.
theo
|
As **Mark Kaplun** said in the comments, something is adding `defer` to your one domain's script.
If you want your subdomain jQuery script to also have `defer`, this should do it:
```
function my_add_defer ($tag, $handle, $src) {
if ($handle == 'jquery') {
return str_replace (' src=', ' defer="defer" src=', $tag);
}
return $tag;
}
add_filter ('script_loader_tag', 'my_add_defer', 10, 3);
```
|
251,324 |
<p>I have the following code, and I am attempting to concatenate the values of the echo html code & 'the_meta'. Can anyone please suggest an edit to code to get this working?</p>
<p><strong>CURRENT CODE</strong></p>
<pre><code><?php echo '<p style="text-align:left;font-size:18px;margin-bottom:5px;">
<span style="color: #000000;">By AUTHOR FOR</span> <?php the_meta(); ?> </p>'; ?>
</code></pre>
<p><strong>DESIRED RESULT</strong></p>
<p>By AUTHOR FOR A GREAT MAGAZINE</p>
|
[
{
"answer_id": 251325,
"author": "Coffee coder",
"author_id": 103155,
"author_profile": "https://wordpress.stackexchange.com/users/103155",
"pm_score": 0,
"selected": false,
"text": "<p>Did you try adding echo \"\"; inside the tag like this:</p>\n\n<pre><code> <?php the_meta(echo \"somethin\" ); ?>\n</code></pre>\n"
},
{
"answer_id": 251328,
"author": "iguanarama",
"author_id": 109807,
"author_profile": "https://wordpress.stackexchange.com/users/109807",
"pm_score": 2,
"selected": true,
"text": "<p>To display <code>the_meta ()</code> after the 'by author for' text just needs a small change:</p>\n\n<pre><code><p style=\"text-align:left;font-size:18px;margin-bottom:5px;\"><span style=\"color: #000000;\">By AUTHOR FOR</span> <?php the_meta (); ?></p>\n</code></pre>\n\n<p>However I'm not sure you want to use <code>the_meta ()</code>, because all values get displayed, and in an unordered list. (Reference: <a href=\"https://codex.wordpress.org/Function_Reference/the_meta\" rel=\"nofollow noreferrer\">the_meta</a>.)</p>\n\n<p>Instead you probably want <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\">get_post_meta</a>, so:</p>\n\n<pre><code><p style=\"text-align:left;font-size:18px;margin-bottom:5px;\"><span style=\"color: #000000;\">By AUTHOR FOR</span> <?php echo get_post_meta (get_the_ID (), 'my-author-meta-key', true); ?></p>\n</code></pre>\n\n<p>Replacing <code>my-author-meta-key</code> with your meta key name, obviously.</p>\n"
}
] |
2017/01/04
|
[
"https://wordpress.stackexchange.com/questions/251324",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91067/"
] |
I have the following code, and I am attempting to concatenate the values of the echo html code & 'the\_meta'. Can anyone please suggest an edit to code to get this working?
**CURRENT CODE**
```
<?php echo '<p style="text-align:left;font-size:18px;margin-bottom:5px;">
<span style="color: #000000;">By AUTHOR FOR</span> <?php the_meta(); ?> </p>'; ?>
```
**DESIRED RESULT**
By AUTHOR FOR A GREAT MAGAZINE
|
To display `the_meta ()` after the 'by author for' text just needs a small change:
```
<p style="text-align:left;font-size:18px;margin-bottom:5px;"><span style="color: #000000;">By AUTHOR FOR</span> <?php the_meta (); ?></p>
```
However I'm not sure you want to use `the_meta ()`, because all values get displayed, and in an unordered list. (Reference: [the\_meta](https://codex.wordpress.org/Function_Reference/the_meta).)
Instead you probably want [get\_post\_meta](https://developer.wordpress.org/reference/functions/get_post_meta/), so:
```
<p style="text-align:left;font-size:18px;margin-bottom:5px;"><span style="color: #000000;">By AUTHOR FOR</span> <?php echo get_post_meta (get_the_ID (), 'my-author-meta-key', true); ?></p>
```
Replacing `my-author-meta-key` with your meta key name, obviously.
|
251,347 |
<p>Greeting Community,</p>
<p><strong>Here’s my challenge:</strong> We have an annual report that is published annually. We do <em>NOT</em> want to spin up a new site and domain each year, but house each previous year’s edition on the same site. </p>
<p><strong><em>The kicker is this —</em></strong> each year has a unique design but most of the site’s functionality and features remain the same.
Is there a way to house each year’s report on the same site with a different stylesheet assigned to each group of annual report pages?</p>
<p>I’ve been able to create new post/pages in multiple languages that load various menus but haven’t had success in loading separate CSS to specific pages.</p>
<p>I’m relatively new at WordPress development and don’t want to use plugins and would like to write DRY code at the template level that conditionally call the proper stylesheet per the year in question and not have to worry about plugin/core compatibility or updates. </p>
<p>For example:</p>
<ul>
<li>One group of pages/posts for 2017 have stylesheet enqueued (with its own menu); and </li>
<li>2016 has a different set of pages/posts with another stylesheet, menu, etc. </li>
</ul>
<p>Is this possible? If so, what is this called for research purposes. Is there documentation on doing so in the Codex? Is this considered enqueuing, other?</p>
<p>Thanks in advance for any assistance</p>
|
[
{
"answer_id": 251360,
"author": "Ben HartLenn",
"author_id": 6645,
"author_profile": "https://wordpress.stackexchange.com/users/6645",
"pm_score": 1,
"selected": false,
"text": "<p>One simple solution that might meet your needs would be to add the published year of the current post or page to your body using body_class(), and then add the appropriate styles for each year to your stylesheet.</p>\n\n<p>Here I add a new css class to the html <code><body></code> element like \".year-2016\" using <code>get_the_date()</code> to fill in the year. Note that you should always use body_class() in your body tag:</p>\n\n<pre><code><body <?php body_class( 'year-' . get_the_date('Y') ); ?>>\n</code></pre>\n\n<p>I suspect this will be too simple and broad a stroke, and you will want to conditionally add this css class to your body only if it is a page or a single post the user is viewing, for example. Otherwise just load the body tag normally:</p>\n\n<pre><code><?php if( is_page() || ( is_post() && is_single() ) ) { ?>\n <body <?php body_class( 'year-' . get_the_date('Y') ); ?>>\n <?php } else { ?>\n <body <?php body_class(); ?> >\n<?php } ?>\n</code></pre>\n\n<p>Then in your main stylesheet you could style any menu's and other elements for posts and pages published in 2016. For example your main menu could have a different background color:</p>\n\n<pre><code>.year-2016 .main-menu {\n background: #0cf;\n}\n</code></pre>\n\n<p>This method would be very dynamic, and requires little additional coding to implement the new CSS for your different year themes. </p>\n"
},
{
"answer_id": 251381,
"author": "Magnus Guyra",
"author_id": 110059,
"author_profile": "https://wordpress.stackexchange.com/users/110059",
"pm_score": 0,
"selected": false,
"text": "<p>You could my answer here(or a modified version of it): <a href=\"https://wordpress.stackexchange.com/a/251113/110059\">https://wordpress.stackexchange.com/a/251113/110059</a></p>\n\n<p>For example, you could add a custom field to the post(s) with the annual report, giving the name of the stylesheet, and use a modified version of my code to get the name of the stylesheet from the custom field(instead of getting the tag) and load it.</p>\n"
}
] |
2017/01/05
|
[
"https://wordpress.stackexchange.com/questions/251347",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143628/"
] |
Greeting Community,
**Here’s my challenge:** We have an annual report that is published annually. We do *NOT* want to spin up a new site and domain each year, but house each previous year’s edition on the same site.
***The kicker is this —*** each year has a unique design but most of the site’s functionality and features remain the same.
Is there a way to house each year’s report on the same site with a different stylesheet assigned to each group of annual report pages?
I’ve been able to create new post/pages in multiple languages that load various menus but haven’t had success in loading separate CSS to specific pages.
I’m relatively new at WordPress development and don’t want to use plugins and would like to write DRY code at the template level that conditionally call the proper stylesheet per the year in question and not have to worry about plugin/core compatibility or updates.
For example:
* One group of pages/posts for 2017 have stylesheet enqueued (with its own menu); and
* 2016 has a different set of pages/posts with another stylesheet, menu, etc.
Is this possible? If so, what is this called for research purposes. Is there documentation on doing so in the Codex? Is this considered enqueuing, other?
Thanks in advance for any assistance
|
One simple solution that might meet your needs would be to add the published year of the current post or page to your body using body\_class(), and then add the appropriate styles for each year to your stylesheet.
Here I add a new css class to the html `<body>` element like ".year-2016" using `get_the_date()` to fill in the year. Note that you should always use body\_class() in your body tag:
```
<body <?php body_class( 'year-' . get_the_date('Y') ); ?>>
```
I suspect this will be too simple and broad a stroke, and you will want to conditionally add this css class to your body only if it is a page or a single post the user is viewing, for example. Otherwise just load the body tag normally:
```
<?php if( is_page() || ( is_post() && is_single() ) ) { ?>
<body <?php body_class( 'year-' . get_the_date('Y') ); ?>>
<?php } else { ?>
<body <?php body_class(); ?> >
<?php } ?>
```
Then in your main stylesheet you could style any menu's and other elements for posts and pages published in 2016. For example your main menu could have a different background color:
```
.year-2016 .main-menu {
background: #0cf;
}
```
This method would be very dynamic, and requires little additional coding to implement the new CSS for your different year themes.
|
251,377 |
<p>I'm kind lost on how to do that. Let me explain my problem.</p>
<p>I have an admin who can define a lot of categories. Then i want him to be able to attribute through the dashboard multiple categories to each user.</p>
<p>Then when a user will make a post (custom post type: news and others, using both the same taxonomy "Categories") it will take the one defined by the admin in his profil.</p>
<p>So for exemple, the admin go to the dashboard to user_1. He can now see the list of categories (has it is when you add a post) he select wich categories this user belongs to. Let's take :
-restaurant
-- italian</p>
<p>When user_1 is log in and add now a news he souldn't be able to select categories but whenpublishing the news it will be add in those 2 categories "restaurant" and "italian"</p>
<p>Any one has a solution i've have been trying for 3 days now :(</p>
<p>Thanks in advance for your help</p>
<p>Regards</p>
<p>Adrien</p>
<p>PS: Sorry for my bad english i'm trying to do my best.</p>
<p>Here is my actually custom post in my functions</p>
<pre><code>// Post type
add_action('init', 'postType');
// Custom Post type
function postType()
{
// News
register_post_type('news', array(
'label' => 'News',
'labels' => array(
'name' => 'News',
'singular_name' => 'News',
'all_items' => 'Toutes les News',
'add_new_item' => 'Ajouter une News',
'edit_item' => 'Éditer la News',
'new_item' => 'Nouvelle News',
'view_item' => 'Voir la News',
'search_items' => 'Rechercher parmi les News',
'not_found' => 'Pas de News',
'not_found_in_trash' => 'Pas de News dans la corbeille'
),
'public' => true,
'capability_type' => 'post',
'supports' => array(
'title',
'editor',
'excerpt',
'thumbnail',
'author'
),
'has_archive' => true,
'menu_icon' => 'dashicons-welcome-write-blog',
'hierarchical' => true,
'taxonomies' => array('category'),
'capabilities' => array(
'publish_posts' => 'publish_news',
'edit_posts' => 'edit_news',
'edit_others_posts' => 'edit_others_news',
'delete_posts' => 'delete_news',
'delete_others_posts' => 'delete_others_news',
'read_private_posts' => 'read_private_news',
'edit_post' => 'edit_news',
'delete_post' => 'delete_news',
'read_post' => 'read_news'
),
));
// News
register_post_type('etablissement', array(
'label' => 'Etablissement',
'labels' => array(
'name' => 'Etablissement',
'singular_name' => 'Etablissements',
'all_items' => 'Tous les Etablissements',
'add_new_item' => 'Ajouter un Etablissement',
'edit_item' => 'Éditer l\'Etablissement',
'new_item' => 'Nouvel Etablissement',
'view_item' => 'Voir l\'Etablissement',
'search_items' => 'Rechercher parmi les Etablissements',
'not_found' => 'Pas d\'Etablissement',
'not_found_in_trash' => 'Pas d\'Etablissement dans la corbeille'
),
'public' => true,
'capability_type' => 'post',
'supports' => array(
'title',
'editor',
'excerpt',
'thumbnail',
'author'
),
'show_ui' => true,
'has_archive' => true,
'menu_icon' => 'dashicons-admin-multisite',
'hierarchical' => true,
'taxonomies' => array('category'),
'capabilities' => array(
'publish_posts' => 'publish_letablissements',
'edit_posts' => 'edit_letablissements',
'edit_others_posts' => 'edit_others_letablissements',
'delete_posts' => 'delete_letablissements',
'delete_others_posts' => 'delete_others_letablissements',
'read_private_posts' => 'read_private_letablissements',
'edit_post' => 'edit_letablissements',
'delete_post' => 'delete_letablissements',
'read_post' => 'read_letablissements',
// 'create_posts' => false,
'create_posts' => false,
),
));
// News
register_post_type('montreux', array(
'label' => 'Montreux',
'labels' => array(
'name' => 'Montreux',
'singular_name' => 'Montreux',
'all_items' => 'Touts les articles Montreux',
'add_new_item' => 'Ajouter un article Montreux',
'edit_item' => 'Éditer l\'article Montreux',
'new_item' => 'Nouvel article Montreux',
'view_item' => 'Voir l\'article Montreux',
'search_items' => 'Rechercher parmi les articles Montreux',
'not_found' => 'Pas d\'article Montreux',
'not_found_in_trash' => 'Pas d\'article Montreux dans la corbeille'
),
'public' => true,
'capability_type' => 'post',
'supports' => array(
'title',
'editor',
'excerpt',
'thumbnail',
'author'
),
'has_archive' => true,
'menu_icon' => 'dashicons-admin-home',
'hierarchical' => true,
'taxonomies' => array('category'),
'capabilities' => array(
'edit_post' => 'edit_montreux',
'edit_posts' => 'edit_montreux',
'edit_others_posts' => 'edit_other_montreux',
'publish_posts' => 'publish_montreux',
'read_post' => 'read_montreux',
'read_private_posts' => 'read_private_montreux',
'delete_post' => 'delete_montreux',
'delete_published_posts' => 'delete_published_montreux'
),
));
flush_rewrite_rules();
}
</code></pre>
<p>Thanks</p>
|
[
{
"answer_id": 251380,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 0,
"selected": false,
"text": "<p>Here is your solution-</p>\n\n<pre><code>add_action( 'save_post_news', 'the_dramatist_save_post_cat', 10, 3 );\n\nfunction the_dramatist_save_post_cat($post_ID, $post, $update) {\n $u_id = get_current_user_id();\n if ($u_id == 1) { // Here put your user ID.\n $cats = array( 108, 109 ); // Here put \"restaurant\" and \"italian\" category ID\n // setting the category\n wp_set_object_terms($post_ID, $cats, \"category\", TRUE);\n }\n}\n</code></pre>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 251416,
"author": "Adrien de Bosset",
"author_id": 110272,
"author_profile": "https://wordpress.stackexchange.com/users/110272",
"pm_score": 2,
"selected": true,
"text": "<p>Ok thanks for your help i manage to make it work :</p>\n\n<p>1 : When admin go inside user option page he can select wich categories he is into\n2 : Then this user is creating a news and we can see i'm hiding the category box\n3 : Then if we check we can see the news has the categories set from the one choose in the user</p>\n\n<p><a href=\"https://i.stack.imgur.com/CXJEH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CXJEH.png\" alt=\"1\"></a>\n<a href=\"https://i.stack.imgur.com/EV3uM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EV3uM.png\" alt=\"2\"></a></p>\n\n<p>So let me give my code maybe it will help some one once :)</p>\n\n<pre><code> function restrict_user_form_enqueue_scripts($hook) {\n if ( ! in_array($hook, array('profile.php', 'user-edit.php' )))\n return;\n wp_enqueue_script('jquery');\n wp_enqueue_script( 'jquery.multiple.select', get_template_directory_uri() . '/js/jquery.multiple.select.js' );\n wp_register_style( 'jquery.multiple.select_css', get_template_directory_uri() . '/css/multiple-select.css', false, '1.0.0' );\n wp_enqueue_style( 'jquery.multiple.select_css' );\n}\n\n\nadd_filter('pre_option_default_category', 'jam_change_default_category');\n\nfunction jam_change_default_category($ID) {\n // Avoid error or heavy load !\n if ( ! is_user_logged_in() )\n return $ID;\n $user_id = get_current_user_id();\n $restrict_cat = get_user_meta( $user_id, '_access', true);\n if ( is_array($restrict_cat) ) {\n return reset($restrict_cat);\n } else {\n return $ID;\n }\n}\n\n/**\n* Exclude categories which arent selected for this user.\n*/\nadd_filter( 'get_terms_args', 'restrict_user_get_terms_args', 10, 2 );\n\nfunction restrict_user_get_terms_args( $args, $taxonomies ) {\n // Dont worry if we're not in the admin screen\n if (! is_admin() || $taxonomies[0] !== 'category')\n return $args;\n // Admin users are exempt.\n $currentUser = wp_get_current_user();\n if (in_array('administrator', $currentUser->roles))\n return $args;\n\n $include = get_user_meta( $currentUser->ID, '_access', true);\n\n $args['include'] = $include;\n return $args;\n //var_dump($include);\n}\n// Display and save data in admin dashboard\nfunction restrict_user_form( $user ) {\n // A little security\n if ( ! current_user_can('add_users'))\n return false;\n $args = array(\n 'show_option_all' => '',\n 'orderby' => 'ID',\n 'order' => 'ASC',\n 'show_count' => 0,\n 'hide_empty' => 0,\n 'child_of' => 0,\n 'exclude' => '',\n 'echo' => 0,\n 'hierarchical' => 1,\n 'name' => 'allow',\n 'id' => '',\n 'class' => 'postform',\n 'depth' => 0,\n 'tab_index' => 0,\n 'taxonomy' => 'category',\n 'hide_if_empty' => false,\n 'walker' => ''\n );\n\n $dropdown = wp_dropdown_categories($args);\n // We are going to modify the dropdown a little bit.\n $dom = new DOMDocument();\n //$dom->loadHTML($dropdown, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);\n $dom->loadHTML( mb_convert_encoding($dropdown, 'HTML-ENTITIES', 'UTF-8') );\n $xpath = new DOMXpath($dom);\n $selectPath = $xpath->query(\"//select[@id='allow']\");\n\n if ($selectPath != false) {\n // Change the name to an array.\n $selectPath->item(0)->setAttribute('name', 'allow[]');\n // Allow multi select.\n $selectPath->item(0)->setAttribute('multiple', 'yes');\n\n $selected = get_user_meta( $user->ID, '_access', true);\n // Flag as selected the categories we've previously chosen\n // Do not throught error in user's screen ! // @JamViet\n if ( $selected )\n foreach ($selected as $term_id) {\n // fixed delete category make error !\n if (!empty($term_id) && get_the_category_by_ID($term_id) ){\n $option = $xpath->query(\"//select[@id='allow']//option[@value='$term_id']\");\n $option->item(0)->setAttribute('selected', 'selected');\n }\n }\n }\n?>\n <h3><?php _e('Catégories de cet utilisateur', 'restrict-author-posting'); ?></h3>\n <table class=\"form-table\">\n <tr>\n <th><label for=\"access\"><?php _e('Choisissez les categories', 'restrict-author-posting') ?>:</label></th>\n <td>\n <?php echo $dom->saveXML($dom);?>\n <span class=\"description\"><?php _e('', 'restrict-author-posting') ?></span>\n </td>\n </tr>\n\n </table>\n <table class=\"form-table\">\n <tr>\n <th><label for=\"access\"><?php _e('Voir seulement ces fichiers medias', 'restrict-author-posting') ?></label></th>\n <td>\n <fieldset>\n <legend class=\"screen-reader-text\"><span><?php _e('Oui', 'restrict-author-posting') ?></span></legend>\n <label for=\"_restrict_media\">\n <input type=\"checkbox\" <?php checked (get_user_meta($user->ID, '_restrict_media', true), 1, 1 ) ?> value=\"1\" id=\"_restrict_media\" name=\"_restrict_media\">\n <?php _e('Oui', 'restrict-author-posting') ?></label>\n </fieldset>\n </td>\n </tr>\n </table>\n <script>\n <!--\n jQuery('select#allow').multipleSelect();\n -->\n </script>\n<?php\n}\n\n\n// Restrict Save Data\nfunction restrict_save_data( $user_id ) {\n // check security\n if ( ! current_user_can( 'add_users' ) )\n return false;\n // admin can not restrict himself\n if ( get_current_user_id() == $user_id )\n return false;\n // and last, save it\n if ( ! empty ($_POST['_restrict_media']) ) {\n update_user_meta( $user_id, '_restrict_media', $_POST['_restrict_media'] );\n } else {\n delete_user_meta( $user_id, '_restrict_media' );\n }\n if ( ! empty ($_POST['allow']) ) {\n update_user_meta( $user_id, '_access', $_POST['allow'] );\n } else {\n delete_user_meta( $user_id, '_access' );\n }\n}\n\n// Remove meta box for non admin \nfunction remove_metaboxes() {\nremove_meta_box( 'categorydiv','news','normal' );\nremove_meta_box( 'categorydiv','etablissement','normal' );\n}\n\n// Save Category News\nfunction save_category_news($post_ID, $post) {\n $currentUser = wp_get_current_user();\n $cat = get_user_meta( $currentUser->ID, '_access', true);\n $cat = array_map('intval', $cat);\n wp_set_object_terms($post_ID, $cat, 'category', true);\n\n}\n\n// Save Category Etablissement\nfunction save_category_etablissement($post_ID, $post) {\n $currentUser = wp_get_current_user();\n $cat = get_user_meta( $currentUser->ID, '_access', true);\n $cat = array_map('intval', $cat);\n wp_set_object_terms($post_ID, $cat, 'category', true);\n\n}\n// Action let's go\nadd_action( 'admin_enqueue_scripts', 'restrict_user_form_enqueue_scripts' );\nadd_action( 'show_user_profile', 'restrict_user_form' );\nadd_action( 'edit_user_profile', 'restrict_user_form' );\nadd_action( 'personal_options_update', 'restrict_save_data' );\nadd_action( 'edit_user_profile_update', 'restrict_save_data' );\nadd_action( 'save_post_news', 'save_category_news', 10, 3 );\nadd_action( 'save_post_etablissement', 'save_category_etablissement', 10, 3 );\nadd_action( 'admin_menu', 'remove_metaboxes');\n</code></pre>\n"
}
] |
2017/01/05
|
[
"https://wordpress.stackexchange.com/questions/251377",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110272/"
] |
I'm kind lost on how to do that. Let me explain my problem.
I have an admin who can define a lot of categories. Then i want him to be able to attribute through the dashboard multiple categories to each user.
Then when a user will make a post (custom post type: news and others, using both the same taxonomy "Categories") it will take the one defined by the admin in his profil.
So for exemple, the admin go to the dashboard to user\_1. He can now see the list of categories (has it is when you add a post) he select wich categories this user belongs to. Let's take :
-restaurant
-- italian
When user\_1 is log in and add now a news he souldn't be able to select categories but whenpublishing the news it will be add in those 2 categories "restaurant" and "italian"
Any one has a solution i've have been trying for 3 days now :(
Thanks in advance for your help
Regards
Adrien
PS: Sorry for my bad english i'm trying to do my best.
Here is my actually custom post in my functions
```
// Post type
add_action('init', 'postType');
// Custom Post type
function postType()
{
// News
register_post_type('news', array(
'label' => 'News',
'labels' => array(
'name' => 'News',
'singular_name' => 'News',
'all_items' => 'Toutes les News',
'add_new_item' => 'Ajouter une News',
'edit_item' => 'Éditer la News',
'new_item' => 'Nouvelle News',
'view_item' => 'Voir la News',
'search_items' => 'Rechercher parmi les News',
'not_found' => 'Pas de News',
'not_found_in_trash' => 'Pas de News dans la corbeille'
),
'public' => true,
'capability_type' => 'post',
'supports' => array(
'title',
'editor',
'excerpt',
'thumbnail',
'author'
),
'has_archive' => true,
'menu_icon' => 'dashicons-welcome-write-blog',
'hierarchical' => true,
'taxonomies' => array('category'),
'capabilities' => array(
'publish_posts' => 'publish_news',
'edit_posts' => 'edit_news',
'edit_others_posts' => 'edit_others_news',
'delete_posts' => 'delete_news',
'delete_others_posts' => 'delete_others_news',
'read_private_posts' => 'read_private_news',
'edit_post' => 'edit_news',
'delete_post' => 'delete_news',
'read_post' => 'read_news'
),
));
// News
register_post_type('etablissement', array(
'label' => 'Etablissement',
'labels' => array(
'name' => 'Etablissement',
'singular_name' => 'Etablissements',
'all_items' => 'Tous les Etablissements',
'add_new_item' => 'Ajouter un Etablissement',
'edit_item' => 'Éditer l\'Etablissement',
'new_item' => 'Nouvel Etablissement',
'view_item' => 'Voir l\'Etablissement',
'search_items' => 'Rechercher parmi les Etablissements',
'not_found' => 'Pas d\'Etablissement',
'not_found_in_trash' => 'Pas d\'Etablissement dans la corbeille'
),
'public' => true,
'capability_type' => 'post',
'supports' => array(
'title',
'editor',
'excerpt',
'thumbnail',
'author'
),
'show_ui' => true,
'has_archive' => true,
'menu_icon' => 'dashicons-admin-multisite',
'hierarchical' => true,
'taxonomies' => array('category'),
'capabilities' => array(
'publish_posts' => 'publish_letablissements',
'edit_posts' => 'edit_letablissements',
'edit_others_posts' => 'edit_others_letablissements',
'delete_posts' => 'delete_letablissements',
'delete_others_posts' => 'delete_others_letablissements',
'read_private_posts' => 'read_private_letablissements',
'edit_post' => 'edit_letablissements',
'delete_post' => 'delete_letablissements',
'read_post' => 'read_letablissements',
// 'create_posts' => false,
'create_posts' => false,
),
));
// News
register_post_type('montreux', array(
'label' => 'Montreux',
'labels' => array(
'name' => 'Montreux',
'singular_name' => 'Montreux',
'all_items' => 'Touts les articles Montreux',
'add_new_item' => 'Ajouter un article Montreux',
'edit_item' => 'Éditer l\'article Montreux',
'new_item' => 'Nouvel article Montreux',
'view_item' => 'Voir l\'article Montreux',
'search_items' => 'Rechercher parmi les articles Montreux',
'not_found' => 'Pas d\'article Montreux',
'not_found_in_trash' => 'Pas d\'article Montreux dans la corbeille'
),
'public' => true,
'capability_type' => 'post',
'supports' => array(
'title',
'editor',
'excerpt',
'thumbnail',
'author'
),
'has_archive' => true,
'menu_icon' => 'dashicons-admin-home',
'hierarchical' => true,
'taxonomies' => array('category'),
'capabilities' => array(
'edit_post' => 'edit_montreux',
'edit_posts' => 'edit_montreux',
'edit_others_posts' => 'edit_other_montreux',
'publish_posts' => 'publish_montreux',
'read_post' => 'read_montreux',
'read_private_posts' => 'read_private_montreux',
'delete_post' => 'delete_montreux',
'delete_published_posts' => 'delete_published_montreux'
),
));
flush_rewrite_rules();
}
```
Thanks
|
Ok thanks for your help i manage to make it work :
1 : When admin go inside user option page he can select wich categories he is into
2 : Then this user is creating a news and we can see i'm hiding the category box
3 : Then if we check we can see the news has the categories set from the one choose in the user
[](https://i.stack.imgur.com/CXJEH.png)
[](https://i.stack.imgur.com/EV3uM.png)
So let me give my code maybe it will help some one once :)
```
function restrict_user_form_enqueue_scripts($hook) {
if ( ! in_array($hook, array('profile.php', 'user-edit.php' )))
return;
wp_enqueue_script('jquery');
wp_enqueue_script( 'jquery.multiple.select', get_template_directory_uri() . '/js/jquery.multiple.select.js' );
wp_register_style( 'jquery.multiple.select_css', get_template_directory_uri() . '/css/multiple-select.css', false, '1.0.0' );
wp_enqueue_style( 'jquery.multiple.select_css' );
}
add_filter('pre_option_default_category', 'jam_change_default_category');
function jam_change_default_category($ID) {
// Avoid error or heavy load !
if ( ! is_user_logged_in() )
return $ID;
$user_id = get_current_user_id();
$restrict_cat = get_user_meta( $user_id, '_access', true);
if ( is_array($restrict_cat) ) {
return reset($restrict_cat);
} else {
return $ID;
}
}
/**
* Exclude categories which arent selected for this user.
*/
add_filter( 'get_terms_args', 'restrict_user_get_terms_args', 10, 2 );
function restrict_user_get_terms_args( $args, $taxonomies ) {
// Dont worry if we're not in the admin screen
if (! is_admin() || $taxonomies[0] !== 'category')
return $args;
// Admin users are exempt.
$currentUser = wp_get_current_user();
if (in_array('administrator', $currentUser->roles))
return $args;
$include = get_user_meta( $currentUser->ID, '_access', true);
$args['include'] = $include;
return $args;
//var_dump($include);
}
// Display and save data in admin dashboard
function restrict_user_form( $user ) {
// A little security
if ( ! current_user_can('add_users'))
return false;
$args = array(
'show_option_all' => '',
'orderby' => 'ID',
'order' => 'ASC',
'show_count' => 0,
'hide_empty' => 0,
'child_of' => 0,
'exclude' => '',
'echo' => 0,
'hierarchical' => 1,
'name' => 'allow',
'id' => '',
'class' => 'postform',
'depth' => 0,
'tab_index' => 0,
'taxonomy' => 'category',
'hide_if_empty' => false,
'walker' => ''
);
$dropdown = wp_dropdown_categories($args);
// We are going to modify the dropdown a little bit.
$dom = new DOMDocument();
//$dom->loadHTML($dropdown, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$dom->loadHTML( mb_convert_encoding($dropdown, 'HTML-ENTITIES', 'UTF-8') );
$xpath = new DOMXpath($dom);
$selectPath = $xpath->query("//select[@id='allow']");
if ($selectPath != false) {
// Change the name to an array.
$selectPath->item(0)->setAttribute('name', 'allow[]');
// Allow multi select.
$selectPath->item(0)->setAttribute('multiple', 'yes');
$selected = get_user_meta( $user->ID, '_access', true);
// Flag as selected the categories we've previously chosen
// Do not throught error in user's screen ! // @JamViet
if ( $selected )
foreach ($selected as $term_id) {
// fixed delete category make error !
if (!empty($term_id) && get_the_category_by_ID($term_id) ){
$option = $xpath->query("//select[@id='allow']//option[@value='$term_id']");
$option->item(0)->setAttribute('selected', 'selected');
}
}
}
?>
<h3><?php _e('Catégories de cet utilisateur', 'restrict-author-posting'); ?></h3>
<table class="form-table">
<tr>
<th><label for="access"><?php _e('Choisissez les categories', 'restrict-author-posting') ?>:</label></th>
<td>
<?php echo $dom->saveXML($dom);?>
<span class="description"><?php _e('', 'restrict-author-posting') ?></span>
</td>
</tr>
</table>
<table class="form-table">
<tr>
<th><label for="access"><?php _e('Voir seulement ces fichiers medias', 'restrict-author-posting') ?></label></th>
<td>
<fieldset>
<legend class="screen-reader-text"><span><?php _e('Oui', 'restrict-author-posting') ?></span></legend>
<label for="_restrict_media">
<input type="checkbox" <?php checked (get_user_meta($user->ID, '_restrict_media', true), 1, 1 ) ?> value="1" id="_restrict_media" name="_restrict_media">
<?php _e('Oui', 'restrict-author-posting') ?></label>
</fieldset>
</td>
</tr>
</table>
<script>
<!--
jQuery('select#allow').multipleSelect();
-->
</script>
<?php
}
// Restrict Save Data
function restrict_save_data( $user_id ) {
// check security
if ( ! current_user_can( 'add_users' ) )
return false;
// admin can not restrict himself
if ( get_current_user_id() == $user_id )
return false;
// and last, save it
if ( ! empty ($_POST['_restrict_media']) ) {
update_user_meta( $user_id, '_restrict_media', $_POST['_restrict_media'] );
} else {
delete_user_meta( $user_id, '_restrict_media' );
}
if ( ! empty ($_POST['allow']) ) {
update_user_meta( $user_id, '_access', $_POST['allow'] );
} else {
delete_user_meta( $user_id, '_access' );
}
}
// Remove meta box for non admin
function remove_metaboxes() {
remove_meta_box( 'categorydiv','news','normal' );
remove_meta_box( 'categorydiv','etablissement','normal' );
}
// Save Category News
function save_category_news($post_ID, $post) {
$currentUser = wp_get_current_user();
$cat = get_user_meta( $currentUser->ID, '_access', true);
$cat = array_map('intval', $cat);
wp_set_object_terms($post_ID, $cat, 'category', true);
}
// Save Category Etablissement
function save_category_etablissement($post_ID, $post) {
$currentUser = wp_get_current_user();
$cat = get_user_meta( $currentUser->ID, '_access', true);
$cat = array_map('intval', $cat);
wp_set_object_terms($post_ID, $cat, 'category', true);
}
// Action let's go
add_action( 'admin_enqueue_scripts', 'restrict_user_form_enqueue_scripts' );
add_action( 'show_user_profile', 'restrict_user_form' );
add_action( 'edit_user_profile', 'restrict_user_form' );
add_action( 'personal_options_update', 'restrict_save_data' );
add_action( 'edit_user_profile_update', 'restrict_save_data' );
add_action( 'save_post_news', 'save_category_news', 10, 3 );
add_action( 'save_post_etablissement', 'save_category_etablissement', 10, 3 );
add_action( 'admin_menu', 'remove_metaboxes');
```
|
251,390 |
<p>I have a simple webpage with a dropdown menu with a few options. I would like to be able to get the user's selection and then output the same selection on the webpage. This is the code I have so far.</p>
<pre><code>\\Pretty standard code for getting the header and title and <\div> etc.
<select id="animal" name="animal">
<option value="0">--Select Animal--</option>
<option value="Cat">Cat</option>
<option value="Dog">Dog</option>
<option value="Cow">Cow</option>
</select>
<?php
if($_POST['submit'] && $_POST['submit'] != 0)
{
$animal=$_POST['animal'];
location.reload();
}
print_r($animal);
?>
\\Pretty standard code for getting the footer etc.
</code></pre>
<p>The dropdown box displays alright as shown below. It shows all the options, but when I select an option nothing happens. What I want to do is to display the selection i.e. 'Cat' in this case. (it's not happening at the moment).<a href="https://i.stack.imgur.com/3H2Js.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3H2Js.jpg" alt="enter image description here"></a></p>
<p>Please guide me, what I am doing wrong. Eventually I hope to do other things with the dropdown. But if I can get this working I'll have an understanding of how to get the data and update the page. The next steps are relatively easier.
Also, this piece of code is part of my template file for my page. I can upload the whole code if necessary.</p>
<p><strong>Update:</strong> Eventually I want to make something like this. That is, to display relevant posts based on the user selected filters,if that helps.</p>
|
[
{
"answer_id": 251402,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": -1,
"selected": false,
"text": "<p>You can use below way to display dropdown for selected value.</p>\n\n<pre><code><script>\nfunction myFunction() {\n var txt = document.getElementById('animal').value;\n if(txt == '0') {\n text = 'You have select animal';\n }else if(txt == 'Cat'){\n text = '<h1>Cat</h1>'; \n }else if(txt == 'Dog'){\n text = '<h1>Dog</h1>'; \n }else if(txt == 'Cow'){\n text = '<h1>Cow</h1>'; \n }\n document.getElementById('demo').innerHTML = text;\n}\n</script>\n<html>\n <form action=\"post\">\n <select id=\"animal\" name=\"animal\"> \n <option value=\"0\" onclick=\"myFunction();\">--Select Animal--</option>\n <option value=\"Cat\" onclick=\"myFunction();\">Cat</option>\n <option value=\"Dog\" onclick=\"myFunction();\">Dog</option>\n <option value=\"Cow\" onclick=\"myFunction();\">Cow</option>\n </select>\n </form>\n</html>\n<p id='demo'></p>\n</code></pre>\n\n<p>Let me know incase of any concern/query for the same. </p>\n"
},
{
"answer_id": 251448,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 2,
"selected": true,
"text": "<p>How about this:</p>\n\n<pre><code><?php\n\n$arr = [\"Cat\", \"Dog\", \"Cow\" ];\n\n\nif( $_POST['animal']){\n $animal=$_POST['animal'];\n echo $animal; \n\n}\n\n\n?>\n\n<form name=\"f\" id=\"a\" method=\"post\" action=\"\">\n<select id=\"animal\" name=\"animal\" onchange=\"this.form.submit()\" > \n <option value=\"0\">--Select Animal--</option>\n <?php\n\n foreach ($arr as $a){\n\n if($a == $animal){\n echo \"<option value='{$a}' selected >$a</option>\";\n }else{\n echo \"<option value='{$a}' >$a</option>\";\n }\n\n }\n\n ?>\n\n</select>\n</form>\n</code></pre>\n\n<p>Note you may also <code>unset</code> the variable at the end but garbage collector is also there in PHP. This code assumes you use at least PHP 5.4+, else define te array via <code>$arr = array(\"Cat\", \"Dog\", \"Cow\" );</code></p>\n"
}
] |
2017/01/05
|
[
"https://wordpress.stackexchange.com/questions/251390",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110016/"
] |
I have a simple webpage with a dropdown menu with a few options. I would like to be able to get the user's selection and then output the same selection on the webpage. This is the code I have so far.
```
\\Pretty standard code for getting the header and title and <\div> etc.
<select id="animal" name="animal">
<option value="0">--Select Animal--</option>
<option value="Cat">Cat</option>
<option value="Dog">Dog</option>
<option value="Cow">Cow</option>
</select>
<?php
if($_POST['submit'] && $_POST['submit'] != 0)
{
$animal=$_POST['animal'];
location.reload();
}
print_r($animal);
?>
\\Pretty standard code for getting the footer etc.
```
The dropdown box displays alright as shown below. It shows all the options, but when I select an option nothing happens. What I want to do is to display the selection i.e. 'Cat' in this case. (it's not happening at the moment).[](https://i.stack.imgur.com/3H2Js.jpg)
Please guide me, what I am doing wrong. Eventually I hope to do other things with the dropdown. But if I can get this working I'll have an understanding of how to get the data and update the page. The next steps are relatively easier.
Also, this piece of code is part of my template file for my page. I can upload the whole code if necessary.
**Update:** Eventually I want to make something like this. That is, to display relevant posts based on the user selected filters,if that helps.
|
How about this:
```
<?php
$arr = ["Cat", "Dog", "Cow" ];
if( $_POST['animal']){
$animal=$_POST['animal'];
echo $animal;
}
?>
<form name="f" id="a" method="post" action="">
<select id="animal" name="animal" onchange="this.form.submit()" >
<option value="0">--Select Animal--</option>
<?php
foreach ($arr as $a){
if($a == $animal){
echo "<option value='{$a}' selected >$a</option>";
}else{
echo "<option value='{$a}' >$a</option>";
}
}
?>
</select>
</form>
```
Note you may also `unset` the variable at the end but garbage collector is also there in PHP. This code assumes you use at least PHP 5.4+, else define te array via `$arr = array("Cat", "Dog", "Cow" );`
|
251,408 |
<p>theme:
functions.php</p>
<pre><code>function one_admin_menu() {
add_menu_page(
'One Dashboard',
'One',
'manage_options',
'one_menu',
'one_menu_url',
'dashicons-admin-site',
1
);
}
add_action( 'admin_menu', 'one_admin_menu' );
function one_menu_url() {
include( get_template_directory() . '/includes/admin/main_one/main.php' );
}
</code></pre>
<p>main.php</p>
<pre><code><?php
function one_admin_website() {
$web = get_template_directory_uri() . '/includes/admin/main_one/website.php';
echo $web;
}
?>
<script>
function import_admin_menu(when, where, what) {
jQuery(document).ready(function() {
jQuery(when).click(function() {
jQuery(where).load(what);
});
});
}
</script>
<ul>
<li id='website'><a href="#about">Website</a></li>
</u>
<script>
import_admin_menu('#website', '#one_main_admin', '<?php one_admin_website() ?>' )
</script>
<div id='one_main_admin'> </div>
</code></pre>
<p>website.php</p>
<p>my problem is here, just trying to echo template directory and i having Fatal error: Uncaught Error: Call to undefined function get_template_directory_uri()</p>
<pre><code><?php echo get_template_directory_uri(); ?>
</code></pre>
<p>what i made wrong? i have try to search in google in stackoverlow, but didin't found anything. thank you for your time</p>
|
[
{
"answer_id": 254312,
"author": "dev",
"author_id": 111997,
"author_profile": "https://wordpress.stackexchange.com/users/111997",
"pm_score": -1,
"selected": false,
"text": "<p>get_template_directory_url</p>\n\n<p>no </p>\n\n<p>get_template_directory_uri</p>\n"
},
{
"answer_id": 384041,
"author": "Hideyasu.T",
"author_id": 202486,
"author_profile": "https://wordpress.stackexchange.com/users/202486",
"pm_score": 0,
"selected": false,
"text": "<p>Please check your domain.\nIn my case url is like this.</p>\n<p><a href=\"http://xxx.local/wp-content/themes/%7Byour_teme%7D\" rel=\"nofollow noreferrer\">http://xxx.local/wp-content/themes/{your_teme}</a></p>\n<p>change to</p>\n<p><a href=\"http://xxx.local/\" rel=\"nofollow noreferrer\">http://xxx.local/</a></p>\n<p>It fixed.\nSometimes wrong url cause this problem.</p>\n"
}
] |
2017/01/05
|
[
"https://wordpress.stackexchange.com/questions/251408",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110286/"
] |
theme:
functions.php
```
function one_admin_menu() {
add_menu_page(
'One Dashboard',
'One',
'manage_options',
'one_menu',
'one_menu_url',
'dashicons-admin-site',
1
);
}
add_action( 'admin_menu', 'one_admin_menu' );
function one_menu_url() {
include( get_template_directory() . '/includes/admin/main_one/main.php' );
}
```
main.php
```
<?php
function one_admin_website() {
$web = get_template_directory_uri() . '/includes/admin/main_one/website.php';
echo $web;
}
?>
<script>
function import_admin_menu(when, where, what) {
jQuery(document).ready(function() {
jQuery(when).click(function() {
jQuery(where).load(what);
});
});
}
</script>
<ul>
<li id='website'><a href="#about">Website</a></li>
</u>
<script>
import_admin_menu('#website', '#one_main_admin', '<?php one_admin_website() ?>' )
</script>
<div id='one_main_admin'> </div>
```
website.php
my problem is here, just trying to echo template directory and i having Fatal error: Uncaught Error: Call to undefined function get\_template\_directory\_uri()
```
<?php echo get_template_directory_uri(); ?>
```
what i made wrong? i have try to search in google in stackoverlow, but didin't found anything. thank you for your time
|
Please check your domain.
In my case url is like this.
[http://xxx.local/wp-content/themes/{your\_teme}](http://xxx.local/wp-content/themes/%7Byour_teme%7D)
change to
<http://xxx.local/>
It fixed.
Sometimes wrong url cause this problem.
|
251,425 |
<p>When an Administrator for a sub site removes a user from their sub site, I am trying to not only remove the user, but also completely delete them from the entire MU site. I have tried this:</p>
<pre><code>add_action( 'remove_user_from_blog', 'custom_remove_user', 10,4 );
function custom_remove_user( $user_id ) {
wpmu_delete_user( $user_id );
}
</code></pre>
<p>but i am not able to get it to work - it is not actually deleting the user and it fact when creating the user it is not being assigned to the proper sub site.</p>
<p>If I input an actual number of an existing user, the function works properly.</p>
<p>Any other suggestions for how to handle this?</p>
|
[
{
"answer_id": 251432,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>If I input an actual number of an existing user, the function works properly.</p>\n</blockquote>\n\n<p>The same user may exist on some other website on your MU farm.\nTry figuring out the problem from the error log.\nIs your admin also super admin?</p>\n\n<pre><code>File: /wp-admin/includes/ms.php\n\n192: function wpmu_delete_user( $id ) {\n...\n206: $_super_admins = get_super_admins();\n207: if ( in_array( $user->user_login, $_super_admins, true ) ) {\n208: return false;\n209: }\n</code></pre>\n\n<p>This may be the problem. Only super admins can remove the users.</p>\n"
},
{
"answer_id": 385505,
"author": "Adam Rehal",
"author_id": 203729,
"author_profile": "https://wordpress.stackexchange.com/users/203729",
"pm_score": 1,
"selected": false,
"text": "<p>The function you are looking for is <code>wpmu_delete_user($user->ID)</code></p>\n<p>I wrote a small plugin to delete users across the whole network by role:</p>\n<pre><code><?php\n/**\n * Plugin Name: Regbox Delete multisite users\n * Plugin URI: http://www.regbox.se/delete-multisite-users\n * Description: Delete users by role across network\n * Version: 0.1\n * Author: Adam Rehal\n * Author URI: http://www.regbox.se\n * License: GPL2\n */\n// Make admin menu item in Users\n\nadd_action('admin_menu', 'dmu_submenu_page');\n\nfunction dmu_submenu_page() {\n add_submenu_page( 'users.php', 'Delete multisite users', 'Delete users', 'manage_options', 'delete-multisite-users', 'dmu_callback' );\n}\n\nfunction dmu_callback() {\n echo '<div class="wrap"><div id="icon-tools" class="icon32"></div>';\n echo '<h2>Delete multisite users</h2>';\n echo '<p>Delete users by role across network. This will delete all users with the selected role from the current site AND from the network</p>';\n echo '<p>Users with the same role on other sites will not be removed. You can also use the Count button to count the number of users with a specific role</p>';\n echo '</div>';\n\n // Get all roles\n global $wp_roles;\n $roles = $wp_roles->get_names();\n\n // Get all blogs\n $blog_list = get_blog_list( 0, 'all' ); ?>\n\n <form method="get" action="users.php?page=delete-multisite-users">\n <input type="hidden" name="page" value="delete-multisite-users">\n <input id="what-to-do" type="hidden" name="action" value="">\n\n <!--\n Select blog:\n <select name="blog">\n <?php\n foreach ($blog_list as $blog) { ?>\n <option value="<?php echo $blog['blog_id'];?>"><?php echo str_replace('/','',$blog['path']);?></option>\n <?php }//end foreach ?>\n </select><br>\n -->\n\n Select Role:\n <select name="role">\n <?php foreach($roles as $role_value => $role_name) { ?>\n <option value="<?php echo $role_value;?>"><?php echo $role_name;?></option>\n <?php }//end foreach ?>\n </select>\n <input class="button button-secondary" onClick="javascript:document.getElementById('what-to-do').value = 'delete';" type="submit" value="Delete">\n <input class="button button-primary" onClick="javascript:document.getElementById('what-to-do').value = 'count';" type="submit" value="Count">\n </form>\n <?php\n // Needed to make use of wp_delete_user()\n require_once( ABSPATH . '/wp-admin/includes/user.php' );\n $data = new WP_User_Query( array( 'role' => $_GET['role']) );\n $userList = $data->get_results();\n $deleted = 0;\n $counted = 0;\n if($_GET['action'] == 'delete'){\n if($_GET['role'] != 'administrator'){\n foreach ($userList as $u) {\n if(wpmu_delete_user( $u->ID )){ $deleted++; }\n }\n echo "<p>" . $deleted . " user(s) deleted</p>";\n }else {\n echo "<p>Admin cannot be deleted</p>";\n }\n }\n if($_GET['action'] == 'count'){\n foreach ($userList as $u) {\n $counted++;\n }\n echo "<p>" . $counted . " " . $_GET['role'] . " user(s) on current site</p>";\n }\n}\n</code></pre>\n"
}
] |
2017/01/05
|
[
"https://wordpress.stackexchange.com/questions/251425",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32828/"
] |
When an Administrator for a sub site removes a user from their sub site, I am trying to not only remove the user, but also completely delete them from the entire MU site. I have tried this:
```
add_action( 'remove_user_from_blog', 'custom_remove_user', 10,4 );
function custom_remove_user( $user_id ) {
wpmu_delete_user( $user_id );
}
```
but i am not able to get it to work - it is not actually deleting the user and it fact when creating the user it is not being assigned to the proper sub site.
If I input an actual number of an existing user, the function works properly.
Any other suggestions for how to handle this?
|
The function you are looking for is `wpmu_delete_user($user->ID)`
I wrote a small plugin to delete users across the whole network by role:
```
<?php
/**
* Plugin Name: Regbox Delete multisite users
* Plugin URI: http://www.regbox.se/delete-multisite-users
* Description: Delete users by role across network
* Version: 0.1
* Author: Adam Rehal
* Author URI: http://www.regbox.se
* License: GPL2
*/
// Make admin menu item in Users
add_action('admin_menu', 'dmu_submenu_page');
function dmu_submenu_page() {
add_submenu_page( 'users.php', 'Delete multisite users', 'Delete users', 'manage_options', 'delete-multisite-users', 'dmu_callback' );
}
function dmu_callback() {
echo '<div class="wrap"><div id="icon-tools" class="icon32"></div>';
echo '<h2>Delete multisite users</h2>';
echo '<p>Delete users by role across network. This will delete all users with the selected role from the current site AND from the network</p>';
echo '<p>Users with the same role on other sites will not be removed. You can also use the Count button to count the number of users with a specific role</p>';
echo '</div>';
// Get all roles
global $wp_roles;
$roles = $wp_roles->get_names();
// Get all blogs
$blog_list = get_blog_list( 0, 'all' ); ?>
<form method="get" action="users.php?page=delete-multisite-users">
<input type="hidden" name="page" value="delete-multisite-users">
<input id="what-to-do" type="hidden" name="action" value="">
<!--
Select blog:
<select name="blog">
<?php
foreach ($blog_list as $blog) { ?>
<option value="<?php echo $blog['blog_id'];?>"><?php echo str_replace('/','',$blog['path']);?></option>
<?php }//end foreach ?>
</select><br>
-->
Select Role:
<select name="role">
<?php foreach($roles as $role_value => $role_name) { ?>
<option value="<?php echo $role_value;?>"><?php echo $role_name;?></option>
<?php }//end foreach ?>
</select>
<input class="button button-secondary" onClick="javascript:document.getElementById('what-to-do').value = 'delete';" type="submit" value="Delete">
<input class="button button-primary" onClick="javascript:document.getElementById('what-to-do').value = 'count';" type="submit" value="Count">
</form>
<?php
// Needed to make use of wp_delete_user()
require_once( ABSPATH . '/wp-admin/includes/user.php' );
$data = new WP_User_Query( array( 'role' => $_GET['role']) );
$userList = $data->get_results();
$deleted = 0;
$counted = 0;
if($_GET['action'] == 'delete'){
if($_GET['role'] != 'administrator'){
foreach ($userList as $u) {
if(wpmu_delete_user( $u->ID )){ $deleted++; }
}
echo "<p>" . $deleted . " user(s) deleted</p>";
}else {
echo "<p>Admin cannot be deleted</p>";
}
}
if($_GET['action'] == 'count'){
foreach ($userList as $u) {
$counted++;
}
echo "<p>" . $counted . " " . $_GET['role'] . " user(s) on current site</p>";
}
}
```
|
251,429 |
<p>Is it possible to set default options for inserting image into article. I want every image to link to full image and be right aligned. Setting this manually every time is annoying and unproductive.</p>
<p>Can I do this with some hook in my functions file?</p>
|
[
{
"answer_id": 251437,
"author": "Khaled Allen",
"author_id": 110308,
"author_profile": "https://wordpress.stackexchange.com/users/110308",
"pm_score": 3,
"selected": true,
"text": "<p>You can do this in two ways. If you want to keep it theme specific, edit your <code>functions.php</code> file with this code:</p>\n\n<pre><code>add_action( 'after_setup_theme', 'my_new_default_image_settings' );\n\nfunction my_new_default_image_settings() {\n update_option( 'image_default_align', 'right' );\n update_option( 'image_default_link_type', 'file' );\n}\n</code></pre>\n\n<p>The other way to do it is more general, but also more rigid:</p>\n\n<ol>\n<li>Go to YOURSITE.COM/wp-admin/options.php</li>\n<li>Find the <code>image_default_link_type</code> field.</li>\n<li>Type in <code>file</code>.</li>\n<li>Find the <code>image_default_align</code> field.</li>\n<li>Type in <code>right</code>.</li>\n<li>Scroll to tho bottom and hit Save.</li>\n</ol>\n\n<p>Some helpful references:</p>\n\n<ul>\n<li>WP Codex: <a href=\"https://codex.wordpress.org/Option_Reference\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Option_Reference</a></li>\n<li>Credit for the technique: <a href=\"https://writenowdesign.com/blog/wordpress/wordpress-how-to/change-wordpress-default-image-alignment-link-type/\" rel=\"nofollow noreferrer\">https://writenowdesign.com/blog/wordpress/wordpress-how-to/change-wordpress-default-image-alignment-link-type/</a></li>\n</ul>\n"
},
{
"answer_id": 312057,
"author": "Naga Raj",
"author_id": 140991,
"author_profile": "https://wordpress.stackexchange.com/users/140991",
"pm_score": 0,
"selected": false,
"text": "<pre><code>add_action( 'admin_init', 'default_image_settings_options' );\nfunction default_image_settings_options() {\n update_option( 'image_default_align', 'center' );\n update_option( 'image_default_link_type', 'file' );\n}\n</code></pre>\n"
}
] |
2017/01/05
|
[
"https://wordpress.stackexchange.com/questions/251429",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105920/"
] |
Is it possible to set default options for inserting image into article. I want every image to link to full image and be right aligned. Setting this manually every time is annoying and unproductive.
Can I do this with some hook in my functions file?
|
You can do this in two ways. If you want to keep it theme specific, edit your `functions.php` file with this code:
```
add_action( 'after_setup_theme', 'my_new_default_image_settings' );
function my_new_default_image_settings() {
update_option( 'image_default_align', 'right' );
update_option( 'image_default_link_type', 'file' );
}
```
The other way to do it is more general, but also more rigid:
1. Go to YOURSITE.COM/wp-admin/options.php
2. Find the `image_default_link_type` field.
3. Type in `file`.
4. Find the `image_default_align` field.
5. Type in `right`.
6. Scroll to tho bottom and hit Save.
Some helpful references:
* WP Codex: <https://codex.wordpress.org/Option_Reference>
* Credit for the technique: <https://writenowdesign.com/blog/wordpress/wordpress-how-to/change-wordpress-default-image-alignment-link-type/>
|
251,439 |
<p>We often see this insdie the WordPress templates: </p>
<pre><code>while ( have_posts() ) : the_post();
...
endwhile;
</code></pre>
<p>Do you have any idea why not using braces or "curly brackets" {} for <code>while</code> loop? What is the gain?</p>
|
[
{
"answer_id": 251441,
"author": "iguanarama",
"author_id": 109807,
"author_profile": "https://wordpress.stackexchange.com/users/109807",
"pm_score": 0,
"selected": false,
"text": "<p>It's just another way of writing it, mostly a stylistic choice. I use while loops with curly brackets, and find while : endwhile very hard to read.</p>\n\n<p>Edit: previously asked <a href=\"https://wordpress.stackexchange.com/questions/220682/correct-use-of-curly-braces-vs-alternative-synax\">here</a>. tl;dr: same answer.</p>\n"
},
{
"answer_id": 251454,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>According to the wordpress handbook on <a href=\"https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/\" rel=\"nofollow noreferrer\"><strong>php coding standards</strong></a>, braces should be used for all blocks in the style shown below:</p>\n\n<pre><code>if ( condition ) {\n action1();\n action2();\n} elseif ( condition2 && condition3 ) {\n action3();\n action4();\n} else {\n defaultaction();\n}\n</code></pre>\n\n<blockquote>\n <p>The use of braces means <strong><em>single-statement inline control structures</em></strong>\n are prohibited so it's better to use the <a href=\"http://php.net/manual/en/control-structures.alternative-syntax.php\" rel=\"nofollow noreferrer\"><strong>alternative syntax for\n control structures</strong></a> (e.g. <code>if</code>/<code>endif</code>, <code>while</code>/<code>endwhile</code>) in this scenario,\n especially in template files where PHP code is embedded within HTML:</p>\n</blockquote>\n\n<pre><code><?php if ( have_posts() ) : ?>\n <div class=\"hfeed\">\n <?php while ( have_posts() ) : the_post(); ?>\n <article id=\"post-<?php the_ID() ?>\" class=\"<?php post_class() ?>\">\n <!-- ... -->\n </article>\n <?php endwhile; ?>\n </div>\n<?php endif; ?>\n</code></pre>\n"
}
] |
2017/01/05
|
[
"https://wordpress.stackexchange.com/questions/251439",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88606/"
] |
We often see this insdie the WordPress templates:
```
while ( have_posts() ) : the_post();
...
endwhile;
```
Do you have any idea why not using braces or "curly brackets" {} for `while` loop? What is the gain?
|
According to the wordpress handbook on [**php coding standards**](https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/), braces should be used for all blocks in the style shown below:
```
if ( condition ) {
action1();
action2();
} elseif ( condition2 && condition3 ) {
action3();
action4();
} else {
defaultaction();
}
```
>
> The use of braces means ***single-statement inline control structures***
> are prohibited so it's better to use the [**alternative syntax for
> control structures**](http://php.net/manual/en/control-structures.alternative-syntax.php) (e.g. `if`/`endif`, `while`/`endwhile`) in this scenario,
> especially in template files where PHP code is embedded within HTML:
>
>
>
```
<?php if ( have_posts() ) : ?>
<div class="hfeed">
<?php while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID() ?>" class="<?php post_class() ?>">
<!-- ... -->
</article>
<?php endwhile; ?>
</div>
<?php endif; ?>
```
|
251,458 |
<p>I use an extension called Custom Field Suite to import info from a csv in order to batch create posts. In order to display the form fields I use <code><?php echo CFS()->get('image_location'); ?></code> One type of information I import is image sources which I display images using <code><img src="<?php echo CFS()->get('image_location'); ?>" class="preview" alt="image thumbnail" /></code> This works great without any problems. </p>
<p>But, I want the images to link to the next post using <code>next_post_link</code>. I've seen <code><?php next_post_link('%link','<img src="IMAGELINK"/>'); ?></code> but I can't quite figure out how to combine the two bits of php into a whole.</p>
<p>I've tried <code><?php next_post_link('%link','<img src="echo CFS()->get('image_location')"/>'); ?></code> but get a syntax error. Any advice would be helpful.</p>
|
[
{
"answer_id": 251459,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": false,
"text": "<p>You can format it as, there's also no need to put the <code>echo</code></p>\n\n<pre><code><?php next_post_link('%link',\"<img src=\" . CFS()->get('image_location') . \"/>\"); ?>\n</code></pre>\n\n<p><code>CFS()->get('image_location')</code> gets the field based on the current post id. If you want to use it for the next or previous, you have to pass the next or previous posts ID.</p>\n\n<p>You can do something like this:</p>\n\n<pre><code>$next_post = get_adjacent_post( true, '', false, 'taxonomy_slug' );\n$next_post_id = '';\nif ( is_a( $next_post, 'WP_Post' ) )\n $next_post_id = $next_post->ID;\nif ( ! empty( $next_post_id ) ) {\n $next_post_image_source = CFS()->get( 'image_location', $next_post_id );\n} else {\n $next_post_image_source = \"default image\";\n}\n\nnext_post_link('%link',\"<img src=\" . $next_post_image_source . \"/>\"); \n</code></pre>\n\n<p>No assurance this would work but it should be easy to continue from here</p>\n"
},
{
"answer_id": 251842,
"author": "Thomas Martin",
"author_id": 70344,
"author_profile": "https://wordpress.stackexchange.com/users/70344",
"pm_score": 0,
"selected": false,
"text": "<p>I am able to get the desired functionality using the <code>posts_nav_link</code> template tag. <code>posts_nav_link( '&nbsp;', '&nbsp;', \"<img src=\" . CFS()->get('artwork_image_location') . \">\" );</code> It looks like the <code>next_post_link</code> template tag is not working for me at all, even with a hard link to an image.</p>\n"
}
] |
2017/01/05
|
[
"https://wordpress.stackexchange.com/questions/251458",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70344/"
] |
I use an extension called Custom Field Suite to import info from a csv in order to batch create posts. In order to display the form fields I use `<?php echo CFS()->get('image_location'); ?>` One type of information I import is image sources which I display images using `<img src="<?php echo CFS()->get('image_location'); ?>" class="preview" alt="image thumbnail" />` This works great without any problems.
But, I want the images to link to the next post using `next_post_link`. I've seen `<?php next_post_link('%link','<img src="IMAGELINK"/>'); ?>` but I can't quite figure out how to combine the two bits of php into a whole.
I've tried `<?php next_post_link('%link','<img src="echo CFS()->get('image_location')"/>'); ?>` but get a syntax error. Any advice would be helpful.
|
You can format it as, there's also no need to put the `echo`
```
<?php next_post_link('%link',"<img src=" . CFS()->get('image_location') . "/>"); ?>
```
`CFS()->get('image_location')` gets the field based on the current post id. If you want to use it for the next or previous, you have to pass the next or previous posts ID.
You can do something like this:
```
$next_post = get_adjacent_post( true, '', false, 'taxonomy_slug' );
$next_post_id = '';
if ( is_a( $next_post, 'WP_Post' ) )
$next_post_id = $next_post->ID;
if ( ! empty( $next_post_id ) ) {
$next_post_image_source = CFS()->get( 'image_location', $next_post_id );
} else {
$next_post_image_source = "default image";
}
next_post_link('%link',"<img src=" . $next_post_image_source . "/>");
```
No assurance this would work but it should be easy to continue from here
|
251,460 |
<p>I'm trying to make posts as easy to edit as possible. When a person clicks on "Edit Post", the default is to open in the same window. This can be frustrating, because it's a little difficult to quickly get back to the page they clicked "Edit Post" from (the blogroll).</p>
<p>Obviously, they could right-click > "Open Link in New Tab" (or Command-click), but I was wondering if there's a way to add <code>target="_blank"</code> to the edit_post_link(). Is that possible?</p>
|
[
{
"answer_id": 251462,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>You can adjust the link via the <code>edit_post_link</code> filter.</p>\n\n<p>Here's an example where we use a simple replace since we don't have the <code>class</code> and <code>url</code> explicitly as input arguments:</p>\n\n<pre><code>add_filter( 'edit_post_link', function( $link, $post_id, $text )\n{\n // Add the target attribute \n if( false === strpos( $link, 'target=' ) )\n $link = str_replace( '<a ', '<a target=\"_blank\" ', $link );\n\n return $link;\n}, 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 251465,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>You can achieve this using the <a href=\"https://developer.wordpress.org/reference/hooks/edit_post_link/\" rel=\"nofollow noreferrer\"><strong><code>edit_post_link</code></strong></a> filter.</p>\n\n<pre><code>add_filter( 'edit_post_link', 'wpse251460_admin_edit_post_link', 10, 3 );\n\nfunction wpse251460_admin_edit_post_link( $link, $post_id, $text ) {\n\n if( is_admin() )\n $link = str_replace( '<a ', '<a target=\"_blank\" ', $link );\n\n return $link;\n}\n</code></pre>\n"
}
] |
2017/01/05
|
[
"https://wordpress.stackexchange.com/questions/251460",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73966/"
] |
I'm trying to make posts as easy to edit as possible. When a person clicks on "Edit Post", the default is to open in the same window. This can be frustrating, because it's a little difficult to quickly get back to the page they clicked "Edit Post" from (the blogroll).
Obviously, they could right-click > "Open Link in New Tab" (or Command-click), but I was wondering if there's a way to add `target="_blank"` to the edit\_post\_link(). Is that possible?
|
You can adjust the link via the `edit_post_link` filter.
Here's an example where we use a simple replace since we don't have the `class` and `url` explicitly as input arguments:
```
add_filter( 'edit_post_link', function( $link, $post_id, $text )
{
// Add the target attribute
if( false === strpos( $link, 'target=' ) )
$link = str_replace( '<a ', '<a target="_blank" ', $link );
return $link;
}, 10, 3 );
```
|
251,461 |
<p>I am trying to get the exact same hierarchy structure of this site: <a href="https://theculturetrip.com/" rel="nofollow noreferrer">https://theculturetrip.com/</a></p>
<p>To me it seems they have this category hierarchy:</p>
<pre><code>-Continent
——-Country
————–City
-Food and Drink
-See and Do
-Art
-Literature
-etc.
</code></pre>
<p>If you click on a continent you will land on a page with posts in that continent sorted by the categories above (food and drink, art, literature, see and do).</p>
<p>Then if you click on a country you land on a page with posts in that country sorted by the same categories above (food and drink, art, literature, see and do).</p>
<p>Then if you click on a city you will land on a page with posts in that city sorted again… by the same categories above (food and drink, art, literature, see and do).</p>
<p>If you instead of clicking on a city you click on a category such as food and drink, you will be taken to a page where all the food and drink posts for that city appear (BUT NOT ALL FOOD AND DRINK POSTS IN GENERAL).</p>
<p>So my question is, is the category hierarchy they used as I described above? Or is it like this:</p>
<pre><code>-Continent
-Food and Drink for this Continent
-See and Do for this Continent
-Art for this Continent
-Literature for this Continent
-etc.
——-Country
——-Food and Drink for this Country
——-Art for this Country
——-Literature for this Country
——-etc. for this Country
————City
————Food and Drink for this Country
————See and Do for this Country
————Art for this Country
————Literature for this Country
————etc. for this Country
</code></pre>
<p>This would lead to hundreds if not thousands of categories due to all the cities and countries this would need to be created for. Or would this rather be done by creating different pages for every single one of these? </p>
<p>I want to set my site up in the same exact way as this, but i just dont know how best to build the relationships.</p>
<p>Can somebody help with a solution here?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 251462,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>You can adjust the link via the <code>edit_post_link</code> filter.</p>\n\n<p>Here's an example where we use a simple replace since we don't have the <code>class</code> and <code>url</code> explicitly as input arguments:</p>\n\n<pre><code>add_filter( 'edit_post_link', function( $link, $post_id, $text )\n{\n // Add the target attribute \n if( false === strpos( $link, 'target=' ) )\n $link = str_replace( '<a ', '<a target=\"_blank\" ', $link );\n\n return $link;\n}, 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 251465,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>You can achieve this using the <a href=\"https://developer.wordpress.org/reference/hooks/edit_post_link/\" rel=\"nofollow noreferrer\"><strong><code>edit_post_link</code></strong></a> filter.</p>\n\n<pre><code>add_filter( 'edit_post_link', 'wpse251460_admin_edit_post_link', 10, 3 );\n\nfunction wpse251460_admin_edit_post_link( $link, $post_id, $text ) {\n\n if( is_admin() )\n $link = str_replace( '<a ', '<a target=\"_blank\" ', $link );\n\n return $link;\n}\n</code></pre>\n"
}
] |
2017/01/05
|
[
"https://wordpress.stackexchange.com/questions/251461",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110322/"
] |
I am trying to get the exact same hierarchy structure of this site: <https://theculturetrip.com/>
To me it seems they have this category hierarchy:
```
-Continent
——-Country
————–City
-Food and Drink
-See and Do
-Art
-Literature
-etc.
```
If you click on a continent you will land on a page with posts in that continent sorted by the categories above (food and drink, art, literature, see and do).
Then if you click on a country you land on a page with posts in that country sorted by the same categories above (food and drink, art, literature, see and do).
Then if you click on a city you will land on a page with posts in that city sorted again… by the same categories above (food and drink, art, literature, see and do).
If you instead of clicking on a city you click on a category such as food and drink, you will be taken to a page where all the food and drink posts for that city appear (BUT NOT ALL FOOD AND DRINK POSTS IN GENERAL).
So my question is, is the category hierarchy they used as I described above? Or is it like this:
```
-Continent
-Food and Drink for this Continent
-See and Do for this Continent
-Art for this Continent
-Literature for this Continent
-etc.
——-Country
——-Food and Drink for this Country
——-Art for this Country
——-Literature for this Country
——-etc. for this Country
————City
————Food and Drink for this Country
————See and Do for this Country
————Art for this Country
————Literature for this Country
————etc. for this Country
```
This would lead to hundreds if not thousands of categories due to all the cities and countries this would need to be created for. Or would this rather be done by creating different pages for every single one of these?
I want to set my site up in the same exact way as this, but i just dont know how best to build the relationships.
Can somebody help with a solution here?
Thanks!
|
You can adjust the link via the `edit_post_link` filter.
Here's an example where we use a simple replace since we don't have the `class` and `url` explicitly as input arguments:
```
add_filter( 'edit_post_link', function( $link, $post_id, $text )
{
// Add the target attribute
if( false === strpos( $link, 'target=' ) )
$link = str_replace( '<a ', '<a target="_blank" ', $link );
return $link;
}, 10, 3 );
```
|
251,468 |
<p>How would I go about displaying related categories instead of the follow which displays related tags. Please any help would be much appreciated. Thanks in advance</p>
<pre><code>if(!function_exists('solstice_related_post')) {
function solstice_related_post() {
global $post;
$tags = wp_get_post_tags($post->ID);
if(!empty($tags) && is_array($tags)):
$simlar_tag = $tags[0]->term_id;
?>
<div class="related-posts">
<h6><?php esc_html_e('YOU MIGHT ALSO LIKE', 'solstice-theme'); ?></h6>
<div class="row">
<?php
$args = array(
'tag__in' => array($simlar_tag),
'post__not_in' => array($post->ID),
'posts_per_page' => 3,
'meta_query' => array(array('key' => '_thumbnail_id', 'compare' => 'EXISTS')),
'ignore_sticky_posts' => 1,
);
$re_query = new WP_Query($args);
while ($re_query->have_posts()) : $re_query->the_post();
?>
<article <?php post_class('blog-post col-md-4'); ?>>
<header>
<figure>
<?php the_post_thumbnail('solstice-small'); ?>
</figure>
<h3><a href="<?php echo esc_url(get_the_permalink()); ?>"><?php the_title(); ?></a></h3>
<div class="meta">
<span><?php echo get_the_category_list( ' , ', 'solstice-theme' );?></span>
<span><time datetime="<?php the_time('Y-m-d'); ?>"><?php the_time('F d, Y'); ?></time></span>
</div><!-- /meta -->
</header>
</article>
<?php endwhile; wp_reset_postdata(); ?>
</div><!-- /row -->
</div><!-- /related-posts -->
<?php
endif;
}
}
</code></pre>
|
[
{
"answer_id": 251462,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>You can adjust the link via the <code>edit_post_link</code> filter.</p>\n\n<p>Here's an example where we use a simple replace since we don't have the <code>class</code> and <code>url</code> explicitly as input arguments:</p>\n\n<pre><code>add_filter( 'edit_post_link', function( $link, $post_id, $text )\n{\n // Add the target attribute \n if( false === strpos( $link, 'target=' ) )\n $link = str_replace( '<a ', '<a target=\"_blank\" ', $link );\n\n return $link;\n}, 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 251465,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>You can achieve this using the <a href=\"https://developer.wordpress.org/reference/hooks/edit_post_link/\" rel=\"nofollow noreferrer\"><strong><code>edit_post_link</code></strong></a> filter.</p>\n\n<pre><code>add_filter( 'edit_post_link', 'wpse251460_admin_edit_post_link', 10, 3 );\n\nfunction wpse251460_admin_edit_post_link( $link, $post_id, $text ) {\n\n if( is_admin() )\n $link = str_replace( '<a ', '<a target=\"_blank\" ', $link );\n\n return $link;\n}\n</code></pre>\n"
}
] |
2017/01/05
|
[
"https://wordpress.stackexchange.com/questions/251468",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110255/"
] |
How would I go about displaying related categories instead of the follow which displays related tags. Please any help would be much appreciated. Thanks in advance
```
if(!function_exists('solstice_related_post')) {
function solstice_related_post() {
global $post;
$tags = wp_get_post_tags($post->ID);
if(!empty($tags) && is_array($tags)):
$simlar_tag = $tags[0]->term_id;
?>
<div class="related-posts">
<h6><?php esc_html_e('YOU MIGHT ALSO LIKE', 'solstice-theme'); ?></h6>
<div class="row">
<?php
$args = array(
'tag__in' => array($simlar_tag),
'post__not_in' => array($post->ID),
'posts_per_page' => 3,
'meta_query' => array(array('key' => '_thumbnail_id', 'compare' => 'EXISTS')),
'ignore_sticky_posts' => 1,
);
$re_query = new WP_Query($args);
while ($re_query->have_posts()) : $re_query->the_post();
?>
<article <?php post_class('blog-post col-md-4'); ?>>
<header>
<figure>
<?php the_post_thumbnail('solstice-small'); ?>
</figure>
<h3><a href="<?php echo esc_url(get_the_permalink()); ?>"><?php the_title(); ?></a></h3>
<div class="meta">
<span><?php echo get_the_category_list( ' , ', 'solstice-theme' );?></span>
<span><time datetime="<?php the_time('Y-m-d'); ?>"><?php the_time('F d, Y'); ?></time></span>
</div><!-- /meta -->
</header>
</article>
<?php endwhile; wp_reset_postdata(); ?>
</div><!-- /row -->
</div><!-- /related-posts -->
<?php
endif;
}
}
```
|
You can adjust the link via the `edit_post_link` filter.
Here's an example where we use a simple replace since we don't have the `class` and `url` explicitly as input arguments:
```
add_filter( 'edit_post_link', function( $link, $post_id, $text )
{
// Add the target attribute
if( false === strpos( $link, 'target=' ) )
$link = str_replace( '<a ', '<a target="_blank" ', $link );
return $link;
}, 10, 3 );
```
|
251,499 |
<p>I have a code like this.</p>
<pre><code><div class="slick"></div>
<div class="slick active"></div>
<div class="slick active"></div>
<div class="slick active"></div>
<div class="slick"></div>
<div class="slick"></div>
</code></pre>
<p>I want to style the last div having the class 'active'. Is there any way to do this?</p>
|
[
{
"answer_id": 251500,
"author": "Shareef",
"author_id": 110271,
"author_profile": "https://wordpress.stackexchange.com/users/110271",
"pm_score": 0,
"selected": false,
"text": "<p>with the help of jQuery you can achieve it.</p>\n\n<p>jQuery will find the last child of the parent and give you ability to change it by adding classes and styles.</p>\n\n<p>go through this link <a href=\"https://api.jquery.com/last-child-selector/\" rel=\"nofollow noreferrer\">https://api.jquery.com/last-child-selector/</a></p>\n\n<p>or use css like this <a href=\"https://css-tricks.com/almanac/selectors/l/last-child/\" rel=\"nofollow noreferrer\">https://css-tricks.com/almanac/selectors/l/last-child/</a></p>\n"
},
{
"answer_id": 251501,
"author": "Sjors Ottjes",
"author_id": 105133,
"author_profile": "https://wordpress.stackexchange.com/users/105133",
"pm_score": 2,
"selected": true,
"text": "<p>There is no (good) way to solve this problem in its current state with CSS. The best solution is to add an extra class to the last active div, or to use javascript</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/6401268/how-do-i-select-the-last-child-with-a-specific-class-name-in-css\">this question</a> for more details</p>\n"
}
] |
2017/01/06
|
[
"https://wordpress.stackexchange.com/questions/251499",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110342/"
] |
I have a code like this.
```
<div class="slick"></div>
<div class="slick active"></div>
<div class="slick active"></div>
<div class="slick active"></div>
<div class="slick"></div>
<div class="slick"></div>
```
I want to style the last div having the class 'active'. Is there any way to do this?
|
There is no (good) way to solve this problem in its current state with CSS. The best solution is to add an extra class to the last active div, or to use javascript
See [this question](https://stackoverflow.com/questions/6401268/how-do-i-select-the-last-child-with-a-specific-class-name-in-css) for more details
|
251,521 |
<p>I created a menu to my Wordpress website, and I have a menu like this</p>
<pre><code> MENU1
..submenu2
...submenu3
</code></pre>
<p>if I click on submenu3/submenu2 then the URL is like,</p>
<pre><code> abc.com/submenu3 or abc.com/submenu2
</code></pre>
<p>what I exactly want to do is like, </p>
<pre><code> abc.com/menu1/submenu2/submenu3
</code></pre>
<p>Please reply me your answer, I really need it. Thanks in advance.</p>
|
[
{
"answer_id": 251532,
"author": "pankaj",
"author_id": 110363,
"author_profile": "https://wordpress.stackexchange.com/users/110363",
"pm_score": -1,
"selected": false,
"text": "<p>Assign MENU1 as parent of submenu2 & submenu2 as parent of submenu3</p>\n"
},
{
"answer_id": 251553,
"author": "codiiv",
"author_id": 91561,
"author_profile": "https://wordpress.stackexchange.com/users/91561",
"pm_score": 0,
"selected": false,
"text": "<p>Even though there may be a few factors to consider, assuming that your menu items are pages, to achieve abc.com/menu1/submenu2/submenu3</p>\n\n<p><strong>You would need to set submenu2 as the parent page os submenu3 and menu1 as parent page for submenu2.</strong> </p>\n\n<p>On the other hand, <strong>if they are not pages or hierarchical custom post types</strong>, it may prove to be messy with having to redefine a few rewrite rules. </p>\n"
},
{
"answer_id": 251563,
"author": "ImSarah",
"author_id": 110378,
"author_profile": "https://wordpress.stackexchange.com/users/110378",
"pm_score": 0,
"selected": false,
"text": "<p>login to your wordpress site go to the specific page you want to make child of a page, after opening page on right corner you will see page attribute add the parent page! Woaaah thats easy! go a head..</p>\n"
},
{
"answer_id": 251564,
"author": "Charles Xavier",
"author_id": 101716,
"author_profile": "https://wordpress.stackexchange.com/users/101716",
"pm_score": 1,
"selected": true,
"text": "<p>If you dont want to do any back end coding you can create a custom link in the menu panel </p>\n\n<p><a href=\"https://i.stack.imgur.com/XXrHJ.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XXrHJ.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>and then drag the submenu3 under the msubmenu2 and then all under menu1\n<a href=\"https://i.stack.imgur.com/mLOvl.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mLOvl.jpg\" alt=\"enter image description here\"></a></p>\n"
}
] |
2017/01/06
|
[
"https://wordpress.stackexchange.com/questions/251521",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106371/"
] |
I created a menu to my Wordpress website, and I have a menu like this
```
MENU1
..submenu2
...submenu3
```
if I click on submenu3/submenu2 then the URL is like,
```
abc.com/submenu3 or abc.com/submenu2
```
what I exactly want to do is like,
```
abc.com/menu1/submenu2/submenu3
```
Please reply me your answer, I really need it. Thanks in advance.
|
If you dont want to do any back end coding you can create a custom link in the menu panel
[](https://i.stack.imgur.com/XXrHJ.jpg)
and then drag the submenu3 under the msubmenu2 and then all under menu1
[](https://i.stack.imgur.com/mLOvl.jpg)
|
251,527 |
<p>I have been meddling with REST API and I am stuck with this: How can I filter posts in both cat1 and cat2?</p>
<p>For now, <code>?categories[]=45&categories[]=50</code> returns in category ID 45 OR 50 - how can I get posts in 45 AND 50?</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 252483,
"author": "Jamie Halvorson",
"author_id": 82990,
"author_profile": "https://wordpress.stackexchange.com/users/82990",
"pm_score": -1,
"selected": false,
"text": "<p>You should be able to access multiple categories by using the following:</p>\n\n<pre><code>http://YOURSITE.DEV/wp-json/wp/v2/posts?categories=45+50\n</code></pre>\n\n<p>Hope that helps!</p>\n\n<p>Cheers</p>\n"
},
{
"answer_id": 266572,
"author": "Manish Jung Thapa",
"author_id": 119463,
"author_profile": "https://wordpress.stackexchange.com/users/119463",
"pm_score": 4,
"selected": false,
"text": "<p>Multiple categories can be separated by comma like below</p>\n\n<pre><code>http://example.com/wp-json/wp/v2/posts?categories=20,30\n</code></pre>\n\n<p>hope this helps</p>\n"
},
{
"answer_id": 289686,
"author": "Austin Passy",
"author_id": 9065,
"author_profile": "https://wordpress.stackexchange.com/users/9065",
"pm_score": 3,
"selected": false,
"text": "<p>@Jesse see: <a href=\"https://github.com/WP-API/WP-API/issues/2990\" rel=\"noreferrer\">WP-API/WP-API#2990</a></p>\n\n<p>Since WP 4.7, <code>filter</code> has been removed from WP-API.</p>\n\n<p>You need to use this plugin: <a href=\"https://github.com/WP-API/rest-filter\" rel=\"noreferrer\">https://github.com/WP-API/rest-filter</a></p>\n"
},
{
"answer_id": 298533,
"author": "Louis S",
"author_id": 126279,
"author_profile": "https://wordpress.stackexchange.com/users/126279",
"pm_score": 1,
"selected": false,
"text": "<p>Install the filter plugin Austin mentioned (<a href=\"https://github.com/WP-API/rest-filter\" rel=\"nofollow noreferrer\">https://github.com/WP-API/rest-filter</a>) and try <code>?filter[categories]=cat_one_slug%2Bcat_two_slug</code>.</p>\n\n<p>I found out that <code>%2B</code> is the code equivalent of the <code>+</code> symbol. </p>\n\n<p>Normally we would use <code>+</code> for the AND operator but unfortunately it gets converted into a space so use <code>%2B</code> instead.</p>\n"
},
{
"answer_id": 340132,
"author": "Thavaprakash Swaminathan",
"author_id": 169766,
"author_profile": "https://wordpress.stackexchange.com/users/169766",
"pm_score": -1,
"selected": false,
"text": "<p>This is what I did, It works fine.</p>\n\n<pre><code>http://example.com/wp-json/wp/v2/articles/?_embed&categories=1,2,3,4&per_page=30\n</code></pre>\n"
},
{
"answer_id": 361390,
"author": "vahid sabet",
"author_id": 184783,
"author_profile": "https://wordpress.stackexchange.com/users/184783",
"pm_score": -1,
"selected": false,
"text": "<p>For those who are using Rest API v3, It works for me:</p>\n\n<pre><code>http://example.com/wp-json/wc/v3/products/?category=42,43\n</code></pre>\n"
},
{
"answer_id": 365405,
"author": "Frank",
"author_id": 67406,
"author_profile": "https://wordpress.stackexchange.com/users/67406",
"pm_score": 2,
"selected": false,
"text": "<p>There doesn't seem to be a way to do this in the current version of the API. Without using a plugin, it can be achieved with a custom endpoint or by using the <a href=\"https://developer.wordpress.org/reference/hooks/rest_this-post_type_query/\" rel=\"nofollow noreferrer\">rest query filter function</a> for the specific post type.</p>\n\n<p>Here's a rough filter function that adds a parameter called <code>cat_relation</code>:\n<pre><code>add_filter( 'rest_post_query', function( $args, $request ) {\n if($request['cat_relation'] == 'AND') {\n $args['category__and'] = $request['categories'];\n }\n return $args;\n}, 10, 2);\n</pre></code></p>\n\n<p>So an example request URL would be:<br>\n<code>http://example.com/wp-json/wp/v2/posts?categories=17,8&cat_relation=AND</code> </p>\n"
},
{
"answer_id": 370459,
"author": "Amal Ajith",
"author_id": 191133,
"author_profile": "https://wordpress.stackexchange.com/users/191133",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Filtering posts based on multiple custom taxonomy terms based on logical "AND", "OR" condition.</strong></p>\n<p>Here is what you need to do in the newer versions of Wordpress (v5 and above)</p>\n<p>Lets say you have two custom taxonomies: sector and offerings.</p>\n<p>Getting all posts that are tagged with taxonomy ID 51 "OR" 52 beloning to the taxonmy term "sector"\n"OR"\nGetting all posts that are tagged with taxonomy ID 57 "AND" 58 beloning to the taxonomy term "offering"</p>\n<pre><code>https://mywordpressbackend.com/wp-json/wp/v2/posts?sector=51+52&offering=57,58&tax_relation=OR\n</code></pre>\n<p>Getting all posts that are tagged with taxonomy ID 51 "OR" 52 beloning to the taxonmy term "sector"\n"AND"\nGetting all posts that are tagged with taxonomy ID 57 "AND" 58 beloning to the taxonomy term "offering"</p>\n<pre><code>https://mywordpressbackend.com/wp-json/wp/v2/posts?sector=51+52&offering=57,58&tax_relation=AND\n</code></pre>\n"
},
{
"answer_id": 388750,
"author": "Ahmedakhtar11",
"author_id": 206945,
"author_profile": "https://wordpress.stackexchange.com/users/206945",
"pm_score": 0,
"selected": false,
"text": "<p>Okay so it's going to say the categories number for each post when you fetch posts.</p>\n<p>Then you can just filter by the category number like this:</p>\n<pre><code>const wpdata = await fetch(`http://example.com/wp-json/wp/v2/posts`);\nconst jsonresp = await wpdata.json()\nconst particularcategoryposts = jsonresp.filter(function(item){\n return item.categories == "4"; \n});\n</code></pre>\n<p>P.S.</p>\n<p>By default the WP API only returns 10 posts. Make sure to clarify that you'll need to fetch more than 10 posts if that is the case. 100 Posts is the max.</p>\n<pre><code>const wpdata = await fetch(`http://example.com/wp-json/wp/v2/posts/?per_page=100`);\n</code></pre>\n"
}
] |
2017/01/06
|
[
"https://wordpress.stackexchange.com/questions/251527",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110359/"
] |
I have been meddling with REST API and I am stuck with this: How can I filter posts in both cat1 and cat2?
For now, `?categories[]=45&categories[]=50` returns in category ID 45 OR 50 - how can I get posts in 45 AND 50?
Thanks in advance.
|
Multiple categories can be separated by comma like below
```
http://example.com/wp-json/wp/v2/posts?categories=20,30
```
hope this helps
|
251,530 |
<p>My function in functions.php</p>
<pre><code>function adding_front_style(){
if(is_front_page()){
wp_enqueue_style('front',get_template_directory_uri().'/css/front.css');
}else{
//some code
}
}
add_action('init','adding_front_style');
</code></pre>
<p>My front-page.php</p>
<pre><code><?php get_header(); ?>
<div class = "search">
<?php get_search_form() ?>
</div>
</code></pre>
<p>My front.css</p>
<pre><code> .search{
background-color: blue;
}
</code></pre>
|
[
{
"answer_id": 251534,
"author": "Yuvrajsinh Jhala",
"author_id": 110365,
"author_profile": "https://wordpress.stackexchange.com/users/110365",
"pm_score": 2,
"selected": true,
"text": "<p>Wrong choice of hook, <code>Init</code> hook Fires after WordPress has finished loading, so what you have thought is right. But <code>wp_enqueue_scripts</code> hook is required to load JavaScript and CSS.</p>\n\n<p>Replace line <code>add_action('init','adding_front_style');</code> with\n<code>add_action('wp_enqueue_scripts','adding_front_style');</code></p>\n"
},
{
"answer_id": 251535,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 0,
"selected": false,
"text": "<p>You're using the wrong action for to add the script, you're should use the <code>wp_enqueue_scripts</code> hook instead of <code>init</code></p>\n\n<pre><code>function adding_front_style() {\n if( is_front_page() ) {\n wp_enqueue_style( 'front', get_template_directory_uri().'/css/front.css');\n } else {\n //some code\n }\n}\nadd_action('wp_enqueue_scripts','adding_front_style');\n</code></pre>\n"
},
{
"answer_id": 251536,
"author": "stevenkellow",
"author_id": 101702,
"author_profile": "https://wordpress.stackexchange.com/users/101702",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of hooking the enqueue in to 'init' you need to use wp_enqueue_scripts.</p>\n\n<pre><code>function adding_front_style(){\n if(is_front_page()){\n wp_enqueue_style('front',get_template_directory_uri().'/css/front.css');\n } else {\n //some code\n }\n}\nadd_action('wp_enqueue_scripts','adding_front_style');\n</code></pre>\n\n<p>It's also worth noting that if you are using a child theme at all you'd be better off using get_stylesheet_directory_uri() instead of get_template_directory_uri(), as with the latter your child theme won't override any styles in the parent theme.</p>\n"
}
] |
2017/01/06
|
[
"https://wordpress.stackexchange.com/questions/251530",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110362/"
] |
My function in functions.php
```
function adding_front_style(){
if(is_front_page()){
wp_enqueue_style('front',get_template_directory_uri().'/css/front.css');
}else{
//some code
}
}
add_action('init','adding_front_style');
```
My front-page.php
```
<?php get_header(); ?>
<div class = "search">
<?php get_search_form() ?>
</div>
```
My front.css
```
.search{
background-color: blue;
}
```
|
Wrong choice of hook, `Init` hook Fires after WordPress has finished loading, so what you have thought is right. But `wp_enqueue_scripts` hook is required to load JavaScript and CSS.
Replace line `add_action('init','adding_front_style');` with
`add_action('wp_enqueue_scripts','adding_front_style');`
|
251,531 |
<p>The menus have been registered in <code>functions.php</code>, but they don't appear within the Appearance > Menus section in Admin and the pages, posts etc options are greyed out.</p>
<p>The menus are saved, as you can not create the menu with the same name again.</p>
<p><a href="https://i.stack.imgur.com/29ekB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/29ekB.png" alt="Greyed out Menu options"></a></p>
<p>Within <code>functions.php</code>:</p>
<pre><code>function theme_setup() {
add_theme_support( 'automatic-feed-links' );
add_theme_support( 'post-thumbnails' );
add_theme_support( 'html5', array( 'search-form' ) );
/*** Register Menus */
if (function_exists('register_nav_menus'))
{
register_nav_menus(
array(
'main-menu' => __( 'Main Menu', 'site' ),
'footer-menu' => __( 'Footer Menu', 'site' ),
)
);
}
}
add_action('after_setup_theme', 'theme_setup');
</code></pre>
<p>Within <code>header.php</code></p>
<pre><code>wp_nav_menu(
array(
'menu' => 'Main Menu',
'container' => '',
'depth' => 1,
'theme_location' => 'main-menu',
)
);
</code></pre>
<p>Within <code>footer.php</code></p>
<pre><code>wp_nav_menu(
array(
'menu' => 'Footer Menu',
'container' => '',
'items_wrap' => '',
'theme_location' => 'footer-menu'
)
);
</code></pre>
<p>The main issue here is that these menus exist and are rendering out on the site, but they seem to be hidden within the admin panel and if a new menu is created it never shows up.</p>
<p>Using Wordpress version 4.7 (Latest)</p>
<p>Plugins:
<a href="https://i.stack.imgur.com/tBKuu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tBKuu.jpg" alt="Current plugins"></a></p>
<p>What could be causing this?</p>
|
[
{
"answer_id": 251534,
"author": "Yuvrajsinh Jhala",
"author_id": 110365,
"author_profile": "https://wordpress.stackexchange.com/users/110365",
"pm_score": 2,
"selected": true,
"text": "<p>Wrong choice of hook, <code>Init</code> hook Fires after WordPress has finished loading, so what you have thought is right. But <code>wp_enqueue_scripts</code> hook is required to load JavaScript and CSS.</p>\n\n<p>Replace line <code>add_action('init','adding_front_style');</code> with\n<code>add_action('wp_enqueue_scripts','adding_front_style');</code></p>\n"
},
{
"answer_id": 251535,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 0,
"selected": false,
"text": "<p>You're using the wrong action for to add the script, you're should use the <code>wp_enqueue_scripts</code> hook instead of <code>init</code></p>\n\n<pre><code>function adding_front_style() {\n if( is_front_page() ) {\n wp_enqueue_style( 'front', get_template_directory_uri().'/css/front.css');\n } else {\n //some code\n }\n}\nadd_action('wp_enqueue_scripts','adding_front_style');\n</code></pre>\n"
},
{
"answer_id": 251536,
"author": "stevenkellow",
"author_id": 101702,
"author_profile": "https://wordpress.stackexchange.com/users/101702",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of hooking the enqueue in to 'init' you need to use wp_enqueue_scripts.</p>\n\n<pre><code>function adding_front_style(){\n if(is_front_page()){\n wp_enqueue_style('front',get_template_directory_uri().'/css/front.css');\n } else {\n //some code\n }\n}\nadd_action('wp_enqueue_scripts','adding_front_style');\n</code></pre>\n\n<p>It's also worth noting that if you are using a child theme at all you'd be better off using get_stylesheet_directory_uri() instead of get_template_directory_uri(), as with the latter your child theme won't override any styles in the parent theme.</p>\n"
}
] |
2017/01/06
|
[
"https://wordpress.stackexchange.com/questions/251531",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69398/"
] |
The menus have been registered in `functions.php`, but they don't appear within the Appearance > Menus section in Admin and the pages, posts etc options are greyed out.
The menus are saved, as you can not create the menu with the same name again.
[](https://i.stack.imgur.com/29ekB.png)
Within `functions.php`:
```
function theme_setup() {
add_theme_support( 'automatic-feed-links' );
add_theme_support( 'post-thumbnails' );
add_theme_support( 'html5', array( 'search-form' ) );
/*** Register Menus */
if (function_exists('register_nav_menus'))
{
register_nav_menus(
array(
'main-menu' => __( 'Main Menu', 'site' ),
'footer-menu' => __( 'Footer Menu', 'site' ),
)
);
}
}
add_action('after_setup_theme', 'theme_setup');
```
Within `header.php`
```
wp_nav_menu(
array(
'menu' => 'Main Menu',
'container' => '',
'depth' => 1,
'theme_location' => 'main-menu',
)
);
```
Within `footer.php`
```
wp_nav_menu(
array(
'menu' => 'Footer Menu',
'container' => '',
'items_wrap' => '',
'theme_location' => 'footer-menu'
)
);
```
The main issue here is that these menus exist and are rendering out on the site, but they seem to be hidden within the admin panel and if a new menu is created it never shows up.
Using Wordpress version 4.7 (Latest)
Plugins:
[](https://i.stack.imgur.com/tBKuu.jpg)
What could be causing this?
|
Wrong choice of hook, `Init` hook Fires after WordPress has finished loading, so what you have thought is right. But `wp_enqueue_scripts` hook is required to load JavaScript and CSS.
Replace line `add_action('init','adding_front_style');` with
`add_action('wp_enqueue_scripts','adding_front_style');`
|
251,576 |
<p>On my <a href="http://alexander-pastor.de" rel="nofollow noreferrer" title="my website">website</a> I want to mark featured articles with a star icon, which works by checking if a post has the category "Featured". However, it somehow always seems to return true for backdated articles, which is really strange. (Everything below Computers -> Programming Best Practices, for instance is wrongly marked as featured!). Making it even more awkward, it is not even called for these backdated articles and strange enough twice for each featured article.</p>
<p>Here's my code from functions.php:</p>
<pre><code>function showPosts($number, $category="", $description = false, $disambiguation = null, $featured = false, $collapsible = true, $thumbnail = false, $languageFlag = true)
{
global $post;
$args = array(
'numberposts' => $number,
'category_name' => $category
);
$myposts = get_posts($args);
if( $myposts )
{
// hidden posts due to language setting
$hiddenPosts = 0;
// get cookie data (prefered language(s))
if(isset($_COOKIE["post-data"])) :
$allowedLanguages = get_tangboshi_cookies();
else:
$allowedLanguages = array();
endif;
// if language setting has not been set, allow all
// not very elegant to have all the stuff in a single array (post-data), with multiple arrays one could use array.empty();
if( !(in_array("posts-english", $allowedLanguages) || in_array("posts-german", $allowedLanguages)) ) :
array_push($allowedLanguages, "posts-english");
array_push($allowedLanguages, "posts-german");
endif;
foreach( $myposts as $post )
{
setup_postdata($post);
$id = convertText(get_the_title())."-".$disambiguation;
$postID = get_the_ID();
$status = get_post_meta($postID, "status", true);
switch ($status)
{
case "": $statusText = ""; break;
default: $statusText = '<span class="caption-draft"> - '.$status.'</span>'; break;
}
if ( $featured ) :
$id .= "-featured";
endif;
// same problem with has_category('Featured')
if ( in_category('Featured') )
{
// every featured article mentioned twice; BUG!!
// backdated always get start...
$icon = 'star';
}
// get language of current post
$language = get_post_meta($postID, "language", true);
// if language not mentioned, default is English
if ( !$language )
{
$language = "english";
}
// filter out posts with wrong language
if ( in_array("posts-".$language, $allowedLanguages) )
{
$isAllowedLanguage = true;
}
else
{
$isAllowedLanguage = false;
}
if($languageFlag):
switch($language):
case "english": $flagicon = '<span class="flag-icon flag-icon-squared flag-icon-us"></span> ';break;
case "german": $flagicon = '<span class="flag-icon flag-icon-squared flag-icon-de"></span> ';break;
case "french": $flagicon = '<span class="flag-icon flag-icon-squared flag-icon-fr"></span> ';break;
case "chinese": $flagicon = '<span class="flag-icon flag-icon-squared flag-icon-cn"></span> ';break;
default: throw("Uncaught exception: undefined post language.");
endswitch;
$languageFlagText = $flagicon;
endif;
if( $collapsible && $isAllowedLanguage )
{
$postArgs = array(
"id" => $id,
"caption" => $languageFlagText.get_the_title().$statusText,
"icon" => $icon,
"initialState" => "out",
"function" => "showPostDescription",
"args" => $thumbnail,
"style" => "modern-post"
);
$ret .= call_user_func_array("createPanelWidget", $postArgs);
}
elseif ( !$collapsible )
{
$ret.= "<p>Non-collapsible detected. Unimplemented. Please set collapsible to true.</p>";
}
else
{
$hiddenPosts++;
}
the_post();
}
wp_reset_query();
}
if($hiddenPosts > 0) : $ret.= "<p>Hidden posts due to your language setting: ".$hiddenPosts.".</p>"; endif;
return $ret;
}
function createPanelWidget($id, $caption, $icon, $initialState, $function = "noop", $args = null, $functionHandlesArray = false, $style = 'modern', $nestedLevel = 1)
{
if( $function == "createPanelWidget" )
{
$newLevel = $nestedLevel + 1;
$args["nestedLevel"] = $newLevel;
}
if ( is_array($args) && !$functionHandlesArray )
{
$tmp = call_user_func_array($function, $args);
}
else
{
$tmp = call_user_func($function, $args);
}
// prevent empty panels from being created
if(!isset($tmp)) : return; endif;
$ret .= '
<div class="panel-group">
<div class="panel panel-level-'.$nestedLevel.'" id="'.$id.'-panel">
<div class="panel-heading panel-'.$style.'">
<a data-toggle="collapse" href="#'.$id.'">
<div class="panel-caption-wrapper">
<div class="panel-caption">
<p>
';
if(isset($icon))
{
$ret .= '<span class="fa fa-'.$icon.'"></span>';
}
$ret .= '
'.$caption.'
</p>
</div>
<div class="panel-toggle-icon">
<span class="fa-stack fa-lg">
<span class="fa fa-square fa-stack-2x"></span>
<span class="toggle-icon"></span>
</span>
</div>
</div>
</a>
</div>
<div id="'.$id.'" class="panel-collapse collapse '.$initialState.'">
<div class="panel-body panel-'.$style.'">';
$ret .= $tmp;
$ret .= '
</div>
</div>
</div>
</div>
';
return $ret;
}
</code></pre>
<p><strong>EDIT:</strong></p>
<p>In my <code>index.php</code> I call <code>"createMainPanel(...)"</code>, <code>showPosts(...)</code> is called as a callback of call_userf_func_array with <code>panelAllPostsParams(...)</code>:</p>
<pre><code>function createMainPanel()
{
$catsArgs = array(
'parent' => 0,
'orderby' => 'count',
'order' => 'DESC',
'hide_empty' => true,
'exclude' => array(12) // 12 is Featured
);
$cats = get_categories($catsArgs);
//var_dump($cats);
$ret .= '<div id="primary" class="content-area">';
$ret .= '<main id="main" class="site-main" role="main">';
//$ret .= '<div class="warning">Since Wed. 28 Dec, 2016 23:30 UTC+1 this page is under maintenance. Expect a lot of stuff to return in the next few days.</div>';
$ret .= addLoadingIcon(500, 400);
$ret .= "<ul class='nav nav-tabs' id='main-panel-cats'>";
foreach( $cats as $index => $cat )
{
$catName = $cat->cat_name;
$catRef = convertText($catName);
if( $index == 0 ){ $active = " active "; }
else{ $active = ""; }
$icon = "fa fa-".getIcon($catName);
$ret .= "<li class='".$active."'><a href='#".$catRef."' data-toggle='tab'><span class='".$icon."'></span> ".$catName."</a></li>";
}
$ret .= "</ul>";
$ret .= '<div class="tab-content">';
foreach( $cats as $cat )
{
static $counter = 0;
$description = category_description($cat);
$catName = $cat->cat_name;
//set first tab to active tab, if there's stuff in localstorage javascript will change this later
if( !$counter ){ $active = " active "; }
else{ $active = ""; }
$icon = "fa fa-".getIcon($catName);
$catRef = convertText($catName);
$ret .= '<div id="'.$catRef.'" class="tab-pane'.$active.'">';
$ret .= '<div class="row">';
$ret .= '<div class="col-md-12">';
$panelHeadlineParams = array(
'id' => 'desc-'.$catRef,
'caption' => 'What can I expect from <span class="'.$icon.'"></span> '.$catName.' articles?',
'icon' => 'info-circle',
'initialState' => 'out',
'function' => 'showString',
'args' => $description
);
$panelFeaturedParams = array(
'id' => 'featured-'.$catRef,
'caption' => 'Featured articles in <span class="'.$icon.'"></span> '.$catName,
'icon' => 'star',
'initialState' => 'out',
'function' => 'showPosts',
'args' => array(
'number' => null,
'category' => strtoupper($catRef),
'description' => false,
'disambiguation' => $catRef,
'featured' => true
)
);
$panelAllPostsParams = array(
'id' => 'posts-'.$catRef,
'caption' => 'All posts about <span class="'.$icon.'"></span> '.$catName,
'icon' => 'pencil',
'initialState' => 'in',
'function' => 'showPosts',
'args' => array(
'number' => null,
'category' => strtoupper($catRef),
'description' => true,
'disambiguation' => $catRef
)
);
$ret .= call_user_func_array("createPanelWidget", $panelHeadlineParams);
$ret .= call_user_func_array("createPanelWidget", $panelFeaturedParams);
$ret .= call_user_func_array("createPanelWidget", $panelAllPostsParams);
$ret .= '</div><!-- col -->';
$ret .= '</div><!-- row -->';
$ret .= '</div><!-- tab-pane -->';
$counter++;
}
$ret .= '</div> <!-- tab-content -->';
$ret .= '</main>';
$ret .= '</div> <!-- #primary -->';
echo $ret;
}
</code></pre>
|
[
{
"answer_id": 251577,
"author": "montrealist",
"author_id": 8105,
"author_profile": "https://wordpress.stackexchange.com/users/8105",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect that you're not using <code>get_posts</code> correctly (looks like you're mixing <code>WP_Query</code> methods such as <code>the_post</code> in with results from <code>get_posts</code>). Please read on the differences between <code>WP_Query</code> and <code>get_posts</code>, for example <a href=\"https://wordpress.stackexchange.com/questions/1753/when-should-you-use-wp-query-vs-query-posts-vs-get-posts\">here</a>. </p>\n\n<p>Have you tried passing the current post ID into <code>in_category</code>?</p>\n\n<pre><code>if ( in_category('Featured', $post->ID) )\n</code></pre>\n"
},
{
"answer_id": 251625,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": -1,
"selected": true,
"text": "<p>you do not reset the icon variable after each iteration of the loop, therefor once it gets to be a \"star\" it will always remain.</p>\n"
}
] |
2017/01/06
|
[
"https://wordpress.stackexchange.com/questions/251576",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92039/"
] |
On my [website](http://alexander-pastor.de "my website") I want to mark featured articles with a star icon, which works by checking if a post has the category "Featured". However, it somehow always seems to return true for backdated articles, which is really strange. (Everything below Computers -> Programming Best Practices, for instance is wrongly marked as featured!). Making it even more awkward, it is not even called for these backdated articles and strange enough twice for each featured article.
Here's my code from functions.php:
```
function showPosts($number, $category="", $description = false, $disambiguation = null, $featured = false, $collapsible = true, $thumbnail = false, $languageFlag = true)
{
global $post;
$args = array(
'numberposts' => $number,
'category_name' => $category
);
$myposts = get_posts($args);
if( $myposts )
{
// hidden posts due to language setting
$hiddenPosts = 0;
// get cookie data (prefered language(s))
if(isset($_COOKIE["post-data"])) :
$allowedLanguages = get_tangboshi_cookies();
else:
$allowedLanguages = array();
endif;
// if language setting has not been set, allow all
// not very elegant to have all the stuff in a single array (post-data), with multiple arrays one could use array.empty();
if( !(in_array("posts-english", $allowedLanguages) || in_array("posts-german", $allowedLanguages)) ) :
array_push($allowedLanguages, "posts-english");
array_push($allowedLanguages, "posts-german");
endif;
foreach( $myposts as $post )
{
setup_postdata($post);
$id = convertText(get_the_title())."-".$disambiguation;
$postID = get_the_ID();
$status = get_post_meta($postID, "status", true);
switch ($status)
{
case "": $statusText = ""; break;
default: $statusText = '<span class="caption-draft"> - '.$status.'</span>'; break;
}
if ( $featured ) :
$id .= "-featured";
endif;
// same problem with has_category('Featured')
if ( in_category('Featured') )
{
// every featured article mentioned twice; BUG!!
// backdated always get start...
$icon = 'star';
}
// get language of current post
$language = get_post_meta($postID, "language", true);
// if language not mentioned, default is English
if ( !$language )
{
$language = "english";
}
// filter out posts with wrong language
if ( in_array("posts-".$language, $allowedLanguages) )
{
$isAllowedLanguage = true;
}
else
{
$isAllowedLanguage = false;
}
if($languageFlag):
switch($language):
case "english": $flagicon = '<span class="flag-icon flag-icon-squared flag-icon-us"></span> ';break;
case "german": $flagicon = '<span class="flag-icon flag-icon-squared flag-icon-de"></span> ';break;
case "french": $flagicon = '<span class="flag-icon flag-icon-squared flag-icon-fr"></span> ';break;
case "chinese": $flagicon = '<span class="flag-icon flag-icon-squared flag-icon-cn"></span> ';break;
default: throw("Uncaught exception: undefined post language.");
endswitch;
$languageFlagText = $flagicon;
endif;
if( $collapsible && $isAllowedLanguage )
{
$postArgs = array(
"id" => $id,
"caption" => $languageFlagText.get_the_title().$statusText,
"icon" => $icon,
"initialState" => "out",
"function" => "showPostDescription",
"args" => $thumbnail,
"style" => "modern-post"
);
$ret .= call_user_func_array("createPanelWidget", $postArgs);
}
elseif ( !$collapsible )
{
$ret.= "<p>Non-collapsible detected. Unimplemented. Please set collapsible to true.</p>";
}
else
{
$hiddenPosts++;
}
the_post();
}
wp_reset_query();
}
if($hiddenPosts > 0) : $ret.= "<p>Hidden posts due to your language setting: ".$hiddenPosts.".</p>"; endif;
return $ret;
}
function createPanelWidget($id, $caption, $icon, $initialState, $function = "noop", $args = null, $functionHandlesArray = false, $style = 'modern', $nestedLevel = 1)
{
if( $function == "createPanelWidget" )
{
$newLevel = $nestedLevel + 1;
$args["nestedLevel"] = $newLevel;
}
if ( is_array($args) && !$functionHandlesArray )
{
$tmp = call_user_func_array($function, $args);
}
else
{
$tmp = call_user_func($function, $args);
}
// prevent empty panels from being created
if(!isset($tmp)) : return; endif;
$ret .= '
<div class="panel-group">
<div class="panel panel-level-'.$nestedLevel.'" id="'.$id.'-panel">
<div class="panel-heading panel-'.$style.'">
<a data-toggle="collapse" href="#'.$id.'">
<div class="panel-caption-wrapper">
<div class="panel-caption">
<p>
';
if(isset($icon))
{
$ret .= '<span class="fa fa-'.$icon.'"></span>';
}
$ret .= '
'.$caption.'
</p>
</div>
<div class="panel-toggle-icon">
<span class="fa-stack fa-lg">
<span class="fa fa-square fa-stack-2x"></span>
<span class="toggle-icon"></span>
</span>
</div>
</div>
</a>
</div>
<div id="'.$id.'" class="panel-collapse collapse '.$initialState.'">
<div class="panel-body panel-'.$style.'">';
$ret .= $tmp;
$ret .= '
</div>
</div>
</div>
</div>
';
return $ret;
}
```
**EDIT:**
In my `index.php` I call `"createMainPanel(...)"`, `showPosts(...)` is called as a callback of call\_userf\_func\_array with `panelAllPostsParams(...)`:
```
function createMainPanel()
{
$catsArgs = array(
'parent' => 0,
'orderby' => 'count',
'order' => 'DESC',
'hide_empty' => true,
'exclude' => array(12) // 12 is Featured
);
$cats = get_categories($catsArgs);
//var_dump($cats);
$ret .= '<div id="primary" class="content-area">';
$ret .= '<main id="main" class="site-main" role="main">';
//$ret .= '<div class="warning">Since Wed. 28 Dec, 2016 23:30 UTC+1 this page is under maintenance. Expect a lot of stuff to return in the next few days.</div>';
$ret .= addLoadingIcon(500, 400);
$ret .= "<ul class='nav nav-tabs' id='main-panel-cats'>";
foreach( $cats as $index => $cat )
{
$catName = $cat->cat_name;
$catRef = convertText($catName);
if( $index == 0 ){ $active = " active "; }
else{ $active = ""; }
$icon = "fa fa-".getIcon($catName);
$ret .= "<li class='".$active."'><a href='#".$catRef."' data-toggle='tab'><span class='".$icon."'></span> ".$catName."</a></li>";
}
$ret .= "</ul>";
$ret .= '<div class="tab-content">';
foreach( $cats as $cat )
{
static $counter = 0;
$description = category_description($cat);
$catName = $cat->cat_name;
//set first tab to active tab, if there's stuff in localstorage javascript will change this later
if( !$counter ){ $active = " active "; }
else{ $active = ""; }
$icon = "fa fa-".getIcon($catName);
$catRef = convertText($catName);
$ret .= '<div id="'.$catRef.'" class="tab-pane'.$active.'">';
$ret .= '<div class="row">';
$ret .= '<div class="col-md-12">';
$panelHeadlineParams = array(
'id' => 'desc-'.$catRef,
'caption' => 'What can I expect from <span class="'.$icon.'"></span> '.$catName.' articles?',
'icon' => 'info-circle',
'initialState' => 'out',
'function' => 'showString',
'args' => $description
);
$panelFeaturedParams = array(
'id' => 'featured-'.$catRef,
'caption' => 'Featured articles in <span class="'.$icon.'"></span> '.$catName,
'icon' => 'star',
'initialState' => 'out',
'function' => 'showPosts',
'args' => array(
'number' => null,
'category' => strtoupper($catRef),
'description' => false,
'disambiguation' => $catRef,
'featured' => true
)
);
$panelAllPostsParams = array(
'id' => 'posts-'.$catRef,
'caption' => 'All posts about <span class="'.$icon.'"></span> '.$catName,
'icon' => 'pencil',
'initialState' => 'in',
'function' => 'showPosts',
'args' => array(
'number' => null,
'category' => strtoupper($catRef),
'description' => true,
'disambiguation' => $catRef
)
);
$ret .= call_user_func_array("createPanelWidget", $panelHeadlineParams);
$ret .= call_user_func_array("createPanelWidget", $panelFeaturedParams);
$ret .= call_user_func_array("createPanelWidget", $panelAllPostsParams);
$ret .= '</div><!-- col -->';
$ret .= '</div><!-- row -->';
$ret .= '</div><!-- tab-pane -->';
$counter++;
}
$ret .= '</div> <!-- tab-content -->';
$ret .= '</main>';
$ret .= '</div> <!-- #primary -->';
echo $ret;
}
```
|
you do not reset the icon variable after each iteration of the loop, therefor once it gets to be a "star" it will always remain.
|
251,580 |
<p>I'm trying to use <code>setcookie</code> inside a WP REST request, but it isn't working. The REST request runs properly and performs it's other duties well, but it doesn't set any cookies. </p>
<p>Here's my example code, which is running on <code>mywebsite.com</code></p>
<pre><code>add_action( 'rest_api_init', function () {
register_rest_route( 'my_auth/v1', '/auth_login', array(
'methods' => array('POST'),
'callback' => 'auth_login',
));
});
function auth_login( WP_REST_Request $request ) {
update_post_meta(1234, 'test_field', 'test_value'); // this works!
setcookie('auth_token', 'test1234', time()+3600, "/", 'mywebsite.com'); // this doesn't work
return 'test';
}
</code></pre>
<p>If I send an AJAX request to my endpoint (<code>mywebsite.com/wp-json/my_auth/v1/auth_login</code>), the <code>update_post_meta</code> call works fine, but the <code>setcookie</code> call does not. I have tested this by visiting <code>mywebsite.com</code> after a request, which has no cookies set. </p>
|
[
{
"answer_id": 251582,
"author": "rorymorris89",
"author_id": 104431,
"author_profile": "https://wordpress.stackexchange.com/users/104431",
"pm_score": 3,
"selected": true,
"text": "<p>Adding this line to my <code>$.ajax</code> call fixed the problem for me.</p>\n\n<pre><code>$.ajax({\n xhrFields: { withCredentials: true },\n // the rest...\n</code></pre>\n\n<p>Sidenote: this requires the following header to be set on the server-side, which is enabled by default with the REST API (it seems).</p>\n\n<pre><code>Access-Control-Allow-Credentials:true\n</code></pre>\n"
},
{
"answer_id": 401477,
"author": "user4301296",
"author_id": 218083,
"author_profile": "https://wordpress.stackexchange.com/users/218083",
"pm_score": 0,
"selected": false,
"text": "<p>You need to add the following line to your ajax call:</p>\n<pre><code>xhrFields: { withCredentials: true }\n</code></pre>\n"
}
] |
2017/01/06
|
[
"https://wordpress.stackexchange.com/questions/251580",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104431/"
] |
I'm trying to use `setcookie` inside a WP REST request, but it isn't working. The REST request runs properly and performs it's other duties well, but it doesn't set any cookies.
Here's my example code, which is running on `mywebsite.com`
```
add_action( 'rest_api_init', function () {
register_rest_route( 'my_auth/v1', '/auth_login', array(
'methods' => array('POST'),
'callback' => 'auth_login',
));
});
function auth_login( WP_REST_Request $request ) {
update_post_meta(1234, 'test_field', 'test_value'); // this works!
setcookie('auth_token', 'test1234', time()+3600, "/", 'mywebsite.com'); // this doesn't work
return 'test';
}
```
If I send an AJAX request to my endpoint (`mywebsite.com/wp-json/my_auth/v1/auth_login`), the `update_post_meta` call works fine, but the `setcookie` call does not. I have tested this by visiting `mywebsite.com` after a request, which has no cookies set.
|
Adding this line to my `$.ajax` call fixed the problem for me.
```
$.ajax({
xhrFields: { withCredentials: true },
// the rest...
```
Sidenote: this requires the following header to be set on the server-side, which is enabled by default with the REST API (it seems).
```
Access-Control-Allow-Credentials:true
```
|
251,587 |
<p>I have the following array that I want to store in a single custom field.</p>
<pre><code>array("Accounting"=>"Peter", "Finance"=>"Ben", "Marketing"=>"Joe");
</code></pre>
<p>I want to store it by typing it in a custom field in wp-admin.</p>
<p>Then I want to retrieve this custom field as an array in a page, with something like</p>
<pre><code>$pos = get_post_meta($post_id, 'pos ', true);
</code></pre>
<p>and Output the array with:</p>
<pre><code>foreach($pos as $x => $x_value) {
echo $x_value . " head " . $x;
echo "<br>";
}
</code></pre>
<p>My Questions are:</p>
<ol>
<li><p>How do I save the array in a single custom field? What exactly do i have to type into the custom field?</p></li>
<li><p>How do I retrieve this custom field value as an array in a wordpress template?</p></li>
</ol>
<p><strong>Final Solution to problem thx to Ray:</strong></p>
<ol>
<li><p>I write the following directly into the custom field in wp admin (or use update_post_meta with json_encode in template)</p>
<pre><code>{"Accounting":"Peter","Finance":"Ben","Marketing":"Joe"}
</code></pre></li>
<li><p>Retrieve array in custom field with:</p>
<pre><code>$json_data = get_post_meta($post_id, "my_custom_meta_key", true);
$arr_data = json_decode($json_data, true);
</code></pre></li>
</ol>
|
[
{
"answer_id": 251589,
"author": "Ray",
"author_id": 101989,
"author_profile": "https://wordpress.stackexchange.com/users/101989",
"pm_score": 3,
"selected": true,
"text": "<p>You can <code>json_encode()</code> it which will make it a string that you can put into a custom field then just ensure you <code>json_decode()</code> it to bring it back to an object or <code>json_decode($data, true)</code> to bring it back as an array</p>\n\n<pre><code>$arr = array(\"Accounting\"=>\"Peter\", \"Finance\"=>\"Ben\", \"Marketing\"=>\"Joe\");\nupdate_post_meta($post_id, \"my_custom_meta_key\", json_encode($arr));\n$json_data = get_post_meta($post_id, \"my_custom_meta_key\", true); // true to ensure it comes back as a string and not an array\n$arr_data = json_decode($json_data, true); // 2nd parameter == true so it comes back as an array();\n</code></pre>\n"
},
{
"answer_id": 251590,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>Usually, custom fields are save from form input. If you want to save an array like yours, you can create a metabox on the post edit screen.</p>\n\n<p>This metabox should display input with the same name, something like that</p>\n\n<pre><code><input type=\"text\" name=\"pos[Accounting]\" value=\"\"/>\n<input type=\"text\" name=\"pos[Finance]\" value=\"\"/>\n<input type=\"text\" name=\"pos[Marketing]\" value=\"\"/>\n</code></pre>\n\n<p>The way you suggest to display looks good.</p>\n\n<p>You can find more details to display and save metaboxes with <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes\" rel=\"nofollow noreferrer\"><code>add_meta_boxes</code></a> action et <a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\"><code>add_meta_box()</code></a></p>\n\n<p>hope it gives you some hints !</p>\n"
},
{
"answer_id": 251593,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds like you want to be able to input these values from the core WordPress custom fields metabox:</p>\n\n<p><a href=\"https://i.stack.imgur.com/sz3x2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sz3x2.png\" alt=\"enter image description here\"></a></p>\n\n<p>To do this I would use a custom format, and then convert it when the post is saved.</p>\n\n<pre><code>// This function converts \"Accounting,Peter|Finance,Ben|Marketing,Joe\" format\n// to array(\"Accounting\"=>\"Peter\", \"Finance\"=>\"Ben\", \"Marketing\"=>\"Joe\");\nfunction smyles_convert_custom_format_to_array( $val ){\n\n $employee_data = array();\n\n // Create array with | as separator\n $parts = explode( '|', $val );\n\n if( ! empty( $parts ) ){\n\n // Loop through each one\n foreach( $parts as $part ){\n\n // Split again based on comma\n $part_array = explode( ',', $part );\n\n // As long as there is a value, let's add it to our employee array\n if( ! empty( $part_array[0] ) && ! empty( $part_array[1] ) ){\n\n // First value in array will be our key, second will be the value\n $employee_data[ $part_array[0] ] = $part_array[1];\n }\n\n }\n\n }\n\n return $employee_data;\n}\n</code></pre>\n\n<p>You then need to add an action to update the meta after converting the custom format with the function above:</p>\n\n<pre><code>// Add a custom action on save post so we can convert our custom format\nadd_action( 'save_post', 'smyles_save_post_format_custom_field', 99, 3 );\n// This function will update the post meta with an array instead of using our custom format\nfunction smyles_save_post_format_custom_field( $id, $post, $update ){\n\n $custom_field = 'employees';\n\n // Change `post` below to something else if using custom post type\n if( $post->post_type != 'post' ) {\n return;\n }\n\n // Only try to process if a value exists\n if( ! empty( $_POST[ $custom_field ] ) ){\n $value = smyles_convert_custom_format_to_array( $_POST[ $custom_field ] );\n } else {\n // Otherwise set $value to empty value, meaning custom field was deleted or has an empty value\n $value = array();\n }\n\n update_post_meta( $id, $custom_field, $value, true );\n\n}\n</code></pre>\n\n<p>When you want to pull these values, just use this:</p>\n\n<pre><code>// Arrays are stored serialized, so let's get that first\n$value = get_post_meta( $post_id, 'employees', true);\n</code></pre>\n\n<p>Voila! Profit!</p>\n"
}
] |
2017/01/06
|
[
"https://wordpress.stackexchange.com/questions/251587",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110297/"
] |
I have the following array that I want to store in a single custom field.
```
array("Accounting"=>"Peter", "Finance"=>"Ben", "Marketing"=>"Joe");
```
I want to store it by typing it in a custom field in wp-admin.
Then I want to retrieve this custom field as an array in a page, with something like
```
$pos = get_post_meta($post_id, 'pos ', true);
```
and Output the array with:
```
foreach($pos as $x => $x_value) {
echo $x_value . " head " . $x;
echo "<br>";
}
```
My Questions are:
1. How do I save the array in a single custom field? What exactly do i have to type into the custom field?
2. How do I retrieve this custom field value as an array in a wordpress template?
**Final Solution to problem thx to Ray:**
1. I write the following directly into the custom field in wp admin (or use update\_post\_meta with json\_encode in template)
```
{"Accounting":"Peter","Finance":"Ben","Marketing":"Joe"}
```
2. Retrieve array in custom field with:
```
$json_data = get_post_meta($post_id, "my_custom_meta_key", true);
$arr_data = json_decode($json_data, true);
```
|
You can `json_encode()` it which will make it a string that you can put into a custom field then just ensure you `json_decode()` it to bring it back to an object or `json_decode($data, true)` to bring it back as an array
```
$arr = array("Accounting"=>"Peter", "Finance"=>"Ben", "Marketing"=>"Joe");
update_post_meta($post_id, "my_custom_meta_key", json_encode($arr));
$json_data = get_post_meta($post_id, "my_custom_meta_key", true); // true to ensure it comes back as a string and not an array
$arr_data = json_decode($json_data, true); // 2nd parameter == true so it comes back as an array();
```
|
251,592 |
<p>I want to move the title of the posts under the thumbnail of the post while keeping all 3 of the posts on the same row. This seems like a fairly easy thing to do, but I can't figure out the correct coding. If anyone could help I would really appreciate it.</p>
<p>image of what it looks like (I want the post title below the image thumbnail)
<a href="https://i.stack.imgur.com/26y65.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/26y65.png" alt="enter image description here"></a></p>
<p>related-posts.php</p>
<pre><code><!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<div class="related-posts">
<?php $orig_post = $post;
global $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=> 3, // Number of related posts that will be shown.
'caller_get_posts'=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo '<div id="related-posts"><h3 class="related-posts-title">Related Posts</h3><ul>';
while( $my_query->have_posts() ) {
$my_query->the_post();?>
<div class="relatedthumb"><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><span class="related-posts-image"><?php the_post_thumbnail(); ?></span></a></div>
<div class="relatedcontent">
<h3><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
</div>
<?
}
echo '</ul></div>';
}
}
$post = $orig_post;
wp_reset_query(); ?>
</div>
</code></pre>
<p>css</p>
<pre class="lang-html prettyprint-override"><code>.related-posts-title {
text-transform: uppercase;
font-family: 'Montserrat', sans-serif;
font-size: 12px;
letter-spacing: 1px;
}
.related-posts-image img {
height:259px;
width:400px;
}
.relatedthumb {
display: inline-block;
}
.relatedcontent {
display: inline-block;
}
</code></pre>
|
[
{
"answer_id": 251589,
"author": "Ray",
"author_id": 101989,
"author_profile": "https://wordpress.stackexchange.com/users/101989",
"pm_score": 3,
"selected": true,
"text": "<p>You can <code>json_encode()</code> it which will make it a string that you can put into a custom field then just ensure you <code>json_decode()</code> it to bring it back to an object or <code>json_decode($data, true)</code> to bring it back as an array</p>\n\n<pre><code>$arr = array(\"Accounting\"=>\"Peter\", \"Finance\"=>\"Ben\", \"Marketing\"=>\"Joe\");\nupdate_post_meta($post_id, \"my_custom_meta_key\", json_encode($arr));\n$json_data = get_post_meta($post_id, \"my_custom_meta_key\", true); // true to ensure it comes back as a string and not an array\n$arr_data = json_decode($json_data, true); // 2nd parameter == true so it comes back as an array();\n</code></pre>\n"
},
{
"answer_id": 251590,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>Usually, custom fields are save from form input. If you want to save an array like yours, you can create a metabox on the post edit screen.</p>\n\n<p>This metabox should display input with the same name, something like that</p>\n\n<pre><code><input type=\"text\" name=\"pos[Accounting]\" value=\"\"/>\n<input type=\"text\" name=\"pos[Finance]\" value=\"\"/>\n<input type=\"text\" name=\"pos[Marketing]\" value=\"\"/>\n</code></pre>\n\n<p>The way you suggest to display looks good.</p>\n\n<p>You can find more details to display and save metaboxes with <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes\" rel=\"nofollow noreferrer\"><code>add_meta_boxes</code></a> action et <a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\"><code>add_meta_box()</code></a></p>\n\n<p>hope it gives you some hints !</p>\n"
},
{
"answer_id": 251593,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds like you want to be able to input these values from the core WordPress custom fields metabox:</p>\n\n<p><a href=\"https://i.stack.imgur.com/sz3x2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sz3x2.png\" alt=\"enter image description here\"></a></p>\n\n<p>To do this I would use a custom format, and then convert it when the post is saved.</p>\n\n<pre><code>// This function converts \"Accounting,Peter|Finance,Ben|Marketing,Joe\" format\n// to array(\"Accounting\"=>\"Peter\", \"Finance\"=>\"Ben\", \"Marketing\"=>\"Joe\");\nfunction smyles_convert_custom_format_to_array( $val ){\n\n $employee_data = array();\n\n // Create array with | as separator\n $parts = explode( '|', $val );\n\n if( ! empty( $parts ) ){\n\n // Loop through each one\n foreach( $parts as $part ){\n\n // Split again based on comma\n $part_array = explode( ',', $part );\n\n // As long as there is a value, let's add it to our employee array\n if( ! empty( $part_array[0] ) && ! empty( $part_array[1] ) ){\n\n // First value in array will be our key, second will be the value\n $employee_data[ $part_array[0] ] = $part_array[1];\n }\n\n }\n\n }\n\n return $employee_data;\n}\n</code></pre>\n\n<p>You then need to add an action to update the meta after converting the custom format with the function above:</p>\n\n<pre><code>// Add a custom action on save post so we can convert our custom format\nadd_action( 'save_post', 'smyles_save_post_format_custom_field', 99, 3 );\n// This function will update the post meta with an array instead of using our custom format\nfunction smyles_save_post_format_custom_field( $id, $post, $update ){\n\n $custom_field = 'employees';\n\n // Change `post` below to something else if using custom post type\n if( $post->post_type != 'post' ) {\n return;\n }\n\n // Only try to process if a value exists\n if( ! empty( $_POST[ $custom_field ] ) ){\n $value = smyles_convert_custom_format_to_array( $_POST[ $custom_field ] );\n } else {\n // Otherwise set $value to empty value, meaning custom field was deleted or has an empty value\n $value = array();\n }\n\n update_post_meta( $id, $custom_field, $value, true );\n\n}\n</code></pre>\n\n<p>When you want to pull these values, just use this:</p>\n\n<pre><code>// Arrays are stored serialized, so let's get that first\n$value = get_post_meta( $post_id, 'employees', true);\n</code></pre>\n\n<p>Voila! Profit!</p>\n"
}
] |
2017/01/06
|
[
"https://wordpress.stackexchange.com/questions/251592",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101743/"
] |
I want to move the title of the posts under the thumbnail of the post while keeping all 3 of the posts on the same row. This seems like a fairly easy thing to do, but I can't figure out the correct coding. If anyone could help I would really appreciate it.
image of what it looks like (I want the post title below the image thumbnail)
[](https://i.stack.imgur.com/26y65.png)
related-posts.php
```
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<div class="related-posts">
<?php $orig_post = $post;
global $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=> 3, // Number of related posts that will be shown.
'caller_get_posts'=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo '<div id="related-posts"><h3 class="related-posts-title">Related Posts</h3><ul>';
while( $my_query->have_posts() ) {
$my_query->the_post();?>
<div class="relatedthumb"><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><span class="related-posts-image"><?php the_post_thumbnail(); ?></span></a></div>
<div class="relatedcontent">
<h3><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
</div>
<?
}
echo '</ul></div>';
}
}
$post = $orig_post;
wp_reset_query(); ?>
</div>
```
css
```html
.related-posts-title {
text-transform: uppercase;
font-family: 'Montserrat', sans-serif;
font-size: 12px;
letter-spacing: 1px;
}
.related-posts-image img {
height:259px;
width:400px;
}
.relatedthumb {
display: inline-block;
}
.relatedcontent {
display: inline-block;
}
```
|
You can `json_encode()` it which will make it a string that you can put into a custom field then just ensure you `json_decode()` it to bring it back to an object or `json_decode($data, true)` to bring it back as an array
```
$arr = array("Accounting"=>"Peter", "Finance"=>"Ben", "Marketing"=>"Joe");
update_post_meta($post_id, "my_custom_meta_key", json_encode($arr));
$json_data = get_post_meta($post_id, "my_custom_meta_key", true); // true to ensure it comes back as a string and not an array
$arr_data = json_decode($json_data, true); // 2nd parameter == true so it comes back as an array();
```
|
251,594 |
<p>I have a WordPress site with an SSL certificate. It all works fine, except that this little insecure shield icon shows up because the header has an enqueued non-https script. <a href="https://i.stack.imgur.com/99FiS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/99FiS.png" alt="enter image description here"></a></p>
<p>The issue is that I don't know which plugin is enqueuing this script into the header in order to change it into https. Is there any way I could track down where the script is being enqueued from? Any help would be appreciated! </p>
<p>Btw, in case it helps, the unsafe script that is being enqueued is the google maps script (<a href="http://maps.google.com/maps/api/js?sensor=false&ver=4.2.10" rel="nofollow noreferrer">http://maps.google.com/maps/api/js?sensor=false&ver=4.2.10</a>)</p>
|
[
{
"answer_id": 251597,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 2,
"selected": false,
"text": "<p>There is no filter when a script is registered, so it is hard to track that down. Use a full text search in all your theme and plugin files to find the source.</p>\n\n<p>In addition, you can filter the URL before it is printed:</p>\n\n<pre><code>add_filter( 'script_loader_src', function( $url ) {\n if ( 0 !== strpos( $url, 'http:' ) )\n return $url;\n\n return substr( $url, 5 );\n});\n</code></pre>\n\n<p>This will create an URL without protocol, so the browser will just use the same protocol (here: HTTPS) as your site.</p>\n"
},
{
"answer_id": 251686,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>The issue is that I don't know which plugin is enqueuing this script into the header in order to change it into https.</p>\n</blockquote>\n\n<p>The easy way @EmilioVenegas is to remove the plugins, one by one, and check.</p>\n\n<p>You can try to alter the </p>\n\n<pre><code>http://maps.google.com/maps/api/js?sensor=false&ver=4.2.10\n</code></pre>\n\n<p>to start with </p>\n\n<pre><code>//maps.google.com/maps/api/js...\n</code></pre>\n\n<p>If not a plugin it may be the theme.</p>\n"
}
] |
2017/01/06
|
[
"https://wordpress.stackexchange.com/questions/251594",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110395/"
] |
I have a WordPress site with an SSL certificate. It all works fine, except that this little insecure shield icon shows up because the header has an enqueued non-https script. [](https://i.stack.imgur.com/99FiS.png)
The issue is that I don't know which plugin is enqueuing this script into the header in order to change it into https. Is there any way I could track down where the script is being enqueued from? Any help would be appreciated!
Btw, in case it helps, the unsafe script that is being enqueued is the google maps script (<http://maps.google.com/maps/api/js?sensor=false&ver=4.2.10>)
|
There is no filter when a script is registered, so it is hard to track that down. Use a full text search in all your theme and plugin files to find the source.
In addition, you can filter the URL before it is printed:
```
add_filter( 'script_loader_src', function( $url ) {
if ( 0 !== strpos( $url, 'http:' ) )
return $url;
return substr( $url, 5 );
});
```
This will create an URL without protocol, so the browser will just use the same protocol (here: HTTPS) as your site.
|
251,605 |
<p>I have a custom post type that has a number of meta boxes in it. One of these is an expiration_date field that stores its info in the db as a string formatted like </p>
<pre><code>Feb 1, 2017
</code></pre>
<p>I am trying to write a query that will filter out those items that have a date in the past, only showing future ones. I have tried several versions of the following query, and none work:</p>
<pre><code>$myquery = array (
'post_type' => $cpt,
'numberposts'=>-1,
'meta_key' => 'expiration_date',
'meta_value' => date('M j, Y'),
'meta_compare' => '<'
),
);
</code></pre>
<p>The query returns all posts regardless of date, or zero posts if I reverse the carot (<)</p>
<p>I know that that in order to use date fields WP expects it to be in a different format (YYYY-MM-DD) but this is not how this app was built (by someone else), so the format above is what I am working with.</p>
<p>So the question is: Is there a way to convert the datetime BEFORE the compare? If I pull the field out by itself in any record, I can convert it (using strtotime), but of course I am trying to filter out values based on date before display so I have the right number in the set to work with at the start.</p>
|
[
{
"answer_id": 255915,
"author": "Stephen",
"author_id": 11023,
"author_profile": "https://wordpress.stackexchange.com/users/11023",
"pm_score": 1,
"selected": false,
"text": "<p>I ended up working around the problem of the initial date format by changing the expiration_date field format to YYYY-MM-DD (and then modifying the display of that field elsewhere so that it remains in the original format when end-users view it). So now a normal meta_query using DATETIME will work:</p>\n\n<pre><code>$myquery = array (\n'post_type' => $cpt,\n 'numberposts'=>-1,\n 'meta_key' => 'expiration_date',\n 'type'=> 'DATETIME',\n 'meta_value' => date(\"Y-m-d\"),\n 'meta_compare' => '<'\n ),\n );\n</code></pre>\n\n<p>I would still like an answer to the above if one exists, where the value can be string converted on the fly before compare, so I guess I will hold off on accepting my own answer for a bit hoping for that answer.</p>\n"
},
{
"answer_id": 255986,
"author": "Mudy S",
"author_id": 113041,
"author_profile": "https://wordpress.stackexchange.com/users/113041",
"pm_score": 0,
"selected": false,
"text": "<p>You can do date_parse_from_format to convert the date format:</p>\n\n<pre><code>date_parse_from_format('M j, Y', 'Feb 1, 2017');\n</code></pre>\n\n<p>Then you could reform the array as date(\"Y-m-d\").</p>\n\n<p>The complete array structure is:</p>\n\n<pre><code>[year] => \n[month] => \n[day] => \n[hour] => \n[minute] => \n[second] =>\n[fraction] => \n[warning_count] => \n[warnings] => Array() \n[error_count] => \n[errors] => Array() \n[is_localtime] => \n[zone_type] => \n[zone] => \n[is_dst] =>\n</code></pre>\n"
},
{
"answer_id": 256444,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 4,
"selected": true,
"text": "<h2>Introducing <code>STR_TO_DATE</code></h2>\n\n<p>MySQL has a <a href=\"https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date\" rel=\"noreferrer\"><code>STR_TO_DATE</code></a> function that you could leverage for the scope.</p>\n\n<p>To use it you need to filter the <code>WHERE</code> clause of a <code>WP_Query</code>, probably using <a href=\"https://developer.wordpress.org/reference/hooks/posts_where/\" rel=\"noreferrer\"><code>posts_where</code></a> filter.</p>\n\n<p>That function allows to format a column value as a date by using a specific format.</p>\n\n<p>By default, WordPress uses the <a href=\"https://dev.mysql.com/doc/refman/5.7/en/cast-functions.html#function_cast\" rel=\"noreferrer\"><code>CAST</code></a> MySQL function that expects the value to be in the format <code>Y-m-d H:i:s</code> (according to PHP <code>date</code> arguments).</p>\n\n<p><code>STR_TO_DATE</code>, on the contrary, allows to pass a specific format. The format \"placeholders\" are not the same PHP uses, you can see supported MySQL format placeholders here: <a href=\"https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format\" rel=\"noreferrer\">https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format</a>.</p>\n\n<h2>Workflow</h2>\n\n<p>What I can suggest as workflow is:</p>\n\n<ul>\n<li>create a <code>WP_Query</code> object</li>\n<li>use <code>posts_where</code> to add a <code>WHERE</code> clause that makes use of <code>STR_TO_DATE</code></li>\n<li>remove the filter have the query run, to avoid affecting any other query</li>\n</ul>\n\n<p>Note that <code>STR_TO_DATE</code> can be used also to order values. In case you want to do that, you would need to use <a href=\"https://developer.wordpress.org/reference/hooks/posts_orderby/\" rel=\"noreferrer\"><code>posts_orderby</code></a> filter.</p>\n\n<h2>The filtering class</h2>\n\n<p>Here there's a class (PHP 7+) that wraps the workflow described above for ease re use:</p>\n\n<pre><code>class DateFieldQueryFilter {\n\n const COMPARE_TYPES = [ '<', '>', '=', '<=', '>=' ];\n private $date_key;\n private $date_value;\n private $format;\n private $compare = '=';\n private $order_by_meta = '';\n\n public function __construct(\n string $date_key,\n string $date_value,\n string $mysql_format,\n string $compare = '='\n ) {\n $this->date_key = $date_key;\n $this->date_value = $date_value;\n $this->format = $mysql_format;\n in_array($compare, self::COMPARE_TYPES, TRUE) and $this->compare = $compare;\n }\n\n public function orderByMeta(string $direction = 'DESC'): DateFieldQueryFilter {\n if (in_array(strtoupper($direction), ['ASC', 'DESC'], TRUE)) {\n $this->order_by_meta = $direction;\n }\n return $this;\n }\n\n public function createWpQuery(array $args = []): \\WP_Query {\n $args['meta_key'] = $this->date_key;\n $this->whereFilter('add');\n $this->order_by_meta and $this->orderByFilter('add');\n $query = new \\WP_Query($args);\n $this->whereFilter('remove');\n $this->order_by_meta and $this->orderByFilter('remove');\n return $query;\n }\n\n private function whereFilter(string $action) {\n static $filter;\n if (! $filter && $action === 'add') {\n $filter = function ($where) {\n global $wpdb;\n $where and $where .= ' AND ';\n $sql = \"STR_TO_DATE({$wpdb->postmeta}.meta_value, %s) \";\n $sql .= \"{$this->compare} %s\";\n return $where . $wpdb->prepare($sql, $this->format, $this->date_value);\n };\n }\n $action === 'add'\n ? add_filter('posts_where', $filter)\n : remove_filter('posts_where', $filter);\n }\n\n private function orderByFilter(string $action) {\n static $filter;\n if (! $filter && $action === 'add') {\n $filter = function () {\n global $wpdb;\n $sql = \"STR_TO_DATE({$wpdb->postmeta}.meta_value, %s) \";\n $sql .= $this->order_by_meta;\n return $wpdb->prepare($sql, $this->format);\n };\n }\n $action === 'add'\n ? add_filter('posts_orderby', $filter)\n : remove_filter('posts_orderby', $filter);\n }\n}\n</code></pre>\n\n<p>Sorry if this not include much comments or explaination, it is hard to write code here.</p>\n\n<h2>Where the \"magic\" happen</h2>\n\n<p>The \"core\" of the class is the filter that get added to <code>posts_where</code> before the query runs and removed after that. It is:</p>\n\n<pre><code>function ($where) {\n global $wpdb;\n $where and $where .= ' AND ';\n // something like: STR_TO_DATE(wp_postmeta.meta_value,'%b %e, %Y') < 'Feb 1, 2017'\n $sql = \"STR_TO_DATE({$wpdb->postmeta}.meta_value, %s) {$this->compare} %s\";\n\n return $where . $wpdb->prepare($sql, $this->format, $this->date_value);\n};\n</code></pre>\n\n<p>You can see here how we are telling WordPress to query the posts. Note that\n<code>STR_TO_DATE</code> is a computation that does not comes for free, and will be quite heavy (expecially for CPU) in case of many thousands (or millions) of rows.</p>\n\n<h2>How to make use of it</h2>\n\n<p>By the way, the class can then be used it like this:</p>\n\n<pre><code>$query_filter = new DateFieldQueryFilter (\n 'expiration_date', // meta key\n date('M j, Y'), // meta value\n '%b %e, %Y', // date format using MySQL placeholders\n '<' // comparison to use\n);\n\n$query = $query_filter->createWpQuery(['posts_per_page' => - 1]);\n\nwhile($query->have_posts()) {\n $query->the_post();\n // rest of the loop here\n}\n</code></pre>\n\n<p>In case you want to order by a standard WordPress field, e.g. post date, post title..., you could simple pass related <code>order</code> and <code>orderby</code> query arguments to the <code>DateFieldQueryFilter::createWpQuery()</code> method.</p>\n\n<p>In case you want to order using the same meta value, the class provides the <code>DateFieldQueryFilter::orderByMeta()</code> for the scope.</p>\n\n<p>E.g. in the last snippet you would create the query like this:</p>\n\n<pre><code>$query = $query_filter\n ->orderByMeta('DESC')\n ->createWpQuery(['posts_per_page' => - 1]);\n</code></pre>\n\n<h2>Conclusion</h2>\n\n<p>Even if this works, when it is possible, dates should be saved in database using MySQL format or timestamps, because that simplify <em>a lot</em> any filtering or ordering operation.</p>\n\n<p>In fact, it is much easier to convert the date in the desired format for output <em>after</em> they are retrieved from database.</p>\n\n<p>Even if computation happen either way, doing it <em>after</em> it will be done only on the records returned, but letting MySQL perform the computation it needs to act on **all* the records, requiring much more work.</p>\n\n<p>If you store the dates in MySQL format WordPress provides a function, <a href=\"https://developer.wordpress.org/reference/functions/mysql2date/\" rel=\"noreferrer\"><code>mysql2date()</code></a>, that can be used for to convert them to a desired format and it's also locale aware.</p>\n"
},
{
"answer_id": 256525,
"author": "Aamer Shahzad",
"author_id": 42772,
"author_profile": "https://wordpress.stackexchange.com/users/42772",
"pm_score": 1,
"selected": false,
"text": "<p>Did you try using meta_query in WP_Query?</p>\n\n<pre><code>$args = array(\n 'post_type' => $cpt,\n 'meta_query' => array(\n array(\n 'key' => 'expiration_date',\n 'value' => date('M j, Y'),\n 'compare' => '<',\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>also, make sure that the date in the postmeta table is of the same format that you pass as value in meta_query.</p>\n"
},
{
"answer_id": 256564,
"author": "Hamsterdrache",
"author_id": 113380,
"author_profile": "https://wordpress.stackexchange.com/users/113380",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe you could try something like this? </p>\n\n<pre><code>$args2 = array( \n 'post_type' => $cpt,\n 'posts_per_page'=> -1, \n 'meta-key' => 'expiration_date',\n 'meta_query' => Array ( \n Array ('key' => 'expiration_date', \n 'compare' => '>=', \n 'value' => date('M j, Y',strtotime('now')), //strtotime for value for now, date() to format the timestamp\n 'type' => 'DATETIME'\n ) \n ),\n 'orderby' => 'meta_value', \n 'order' => 'ASC' //or DESC\n );\n</code></pre>\n\n<p>This works for me in getting only events, which are still in the future. </p>\n\n<p>EDIT: \nI have to apologize, this does NOT work. I was driving to an appointment, when i realized where the sorting was actually done. Way down my file was an if-statement left from my previous try, which did the sorting and ordering. Removed that line and it stopped working ... </p>\n"
},
{
"answer_id": 256645,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>The smart solution would be to use the <code>expiration_date</code> field format to <code>YYYY-MM-DD</code>. </p>\n\n<p>This way you will be able to create future <a href=\"https://codex.wordpress.org/Class_Reference/WP_Meta_Query\" rel=\"nofollow noreferrer\">WordPress meta queries</a> without the problem.</p>\n\n<p>The conversion should be a breeze. </p>\n"
}
] |
2017/01/06
|
[
"https://wordpress.stackexchange.com/questions/251605",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/11023/"
] |
I have a custom post type that has a number of meta boxes in it. One of these is an expiration\_date field that stores its info in the db as a string formatted like
```
Feb 1, 2017
```
I am trying to write a query that will filter out those items that have a date in the past, only showing future ones. I have tried several versions of the following query, and none work:
```
$myquery = array (
'post_type' => $cpt,
'numberposts'=>-1,
'meta_key' => 'expiration_date',
'meta_value' => date('M j, Y'),
'meta_compare' => '<'
),
);
```
The query returns all posts regardless of date, or zero posts if I reverse the carot (<)
I know that that in order to use date fields WP expects it to be in a different format (YYYY-MM-DD) but this is not how this app was built (by someone else), so the format above is what I am working with.
So the question is: Is there a way to convert the datetime BEFORE the compare? If I pull the field out by itself in any record, I can convert it (using strtotime), but of course I am trying to filter out values based on date before display so I have the right number in the set to work with at the start.
|
Introducing `STR_TO_DATE`
-------------------------
MySQL has a [`STR_TO_DATE`](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date) function that you could leverage for the scope.
To use it you need to filter the `WHERE` clause of a `WP_Query`, probably using [`posts_where`](https://developer.wordpress.org/reference/hooks/posts_where/) filter.
That function allows to format a column value as a date by using a specific format.
By default, WordPress uses the [`CAST`](https://dev.mysql.com/doc/refman/5.7/en/cast-functions.html#function_cast) MySQL function that expects the value to be in the format `Y-m-d H:i:s` (according to PHP `date` arguments).
`STR_TO_DATE`, on the contrary, allows to pass a specific format. The format "placeholders" are not the same PHP uses, you can see supported MySQL format placeholders here: <https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format>.
Workflow
--------
What I can suggest as workflow is:
* create a `WP_Query` object
* use `posts_where` to add a `WHERE` clause that makes use of `STR_TO_DATE`
* remove the filter have the query run, to avoid affecting any other query
Note that `STR_TO_DATE` can be used also to order values. In case you want to do that, you would need to use [`posts_orderby`](https://developer.wordpress.org/reference/hooks/posts_orderby/) filter.
The filtering class
-------------------
Here there's a class (PHP 7+) that wraps the workflow described above for ease re use:
```
class DateFieldQueryFilter {
const COMPARE_TYPES = [ '<', '>', '=', '<=', '>=' ];
private $date_key;
private $date_value;
private $format;
private $compare = '=';
private $order_by_meta = '';
public function __construct(
string $date_key,
string $date_value,
string $mysql_format,
string $compare = '='
) {
$this->date_key = $date_key;
$this->date_value = $date_value;
$this->format = $mysql_format;
in_array($compare, self::COMPARE_TYPES, TRUE) and $this->compare = $compare;
}
public function orderByMeta(string $direction = 'DESC'): DateFieldQueryFilter {
if (in_array(strtoupper($direction), ['ASC', 'DESC'], TRUE)) {
$this->order_by_meta = $direction;
}
return $this;
}
public function createWpQuery(array $args = []): \WP_Query {
$args['meta_key'] = $this->date_key;
$this->whereFilter('add');
$this->order_by_meta and $this->orderByFilter('add');
$query = new \WP_Query($args);
$this->whereFilter('remove');
$this->order_by_meta and $this->orderByFilter('remove');
return $query;
}
private function whereFilter(string $action) {
static $filter;
if (! $filter && $action === 'add') {
$filter = function ($where) {
global $wpdb;
$where and $where .= ' AND ';
$sql = "STR_TO_DATE({$wpdb->postmeta}.meta_value, %s) ";
$sql .= "{$this->compare} %s";
return $where . $wpdb->prepare($sql, $this->format, $this->date_value);
};
}
$action === 'add'
? add_filter('posts_where', $filter)
: remove_filter('posts_where', $filter);
}
private function orderByFilter(string $action) {
static $filter;
if (! $filter && $action === 'add') {
$filter = function () {
global $wpdb;
$sql = "STR_TO_DATE({$wpdb->postmeta}.meta_value, %s) ";
$sql .= $this->order_by_meta;
return $wpdb->prepare($sql, $this->format);
};
}
$action === 'add'
? add_filter('posts_orderby', $filter)
: remove_filter('posts_orderby', $filter);
}
}
```
Sorry if this not include much comments or explaination, it is hard to write code here.
Where the "magic" happen
------------------------
The "core" of the class is the filter that get added to `posts_where` before the query runs and removed after that. It is:
```
function ($where) {
global $wpdb;
$where and $where .= ' AND ';
// something like: STR_TO_DATE(wp_postmeta.meta_value,'%b %e, %Y') < 'Feb 1, 2017'
$sql = "STR_TO_DATE({$wpdb->postmeta}.meta_value, %s) {$this->compare} %s";
return $where . $wpdb->prepare($sql, $this->format, $this->date_value);
};
```
You can see here how we are telling WordPress to query the posts. Note that
`STR_TO_DATE` is a computation that does not comes for free, and will be quite heavy (expecially for CPU) in case of many thousands (or millions) of rows.
How to make use of it
---------------------
By the way, the class can then be used it like this:
```
$query_filter = new DateFieldQueryFilter (
'expiration_date', // meta key
date('M j, Y'), // meta value
'%b %e, %Y', // date format using MySQL placeholders
'<' // comparison to use
);
$query = $query_filter->createWpQuery(['posts_per_page' => - 1]);
while($query->have_posts()) {
$query->the_post();
// rest of the loop here
}
```
In case you want to order by a standard WordPress field, e.g. post date, post title..., you could simple pass related `order` and `orderby` query arguments to the `DateFieldQueryFilter::createWpQuery()` method.
In case you want to order using the same meta value, the class provides the `DateFieldQueryFilter::orderByMeta()` for the scope.
E.g. in the last snippet you would create the query like this:
```
$query = $query_filter
->orderByMeta('DESC')
->createWpQuery(['posts_per_page' => - 1]);
```
Conclusion
----------
Even if this works, when it is possible, dates should be saved in database using MySQL format or timestamps, because that simplify *a lot* any filtering or ordering operation.
In fact, it is much easier to convert the date in the desired format for output *after* they are retrieved from database.
Even if computation happen either way, doing it *after* it will be done only on the records returned, but letting MySQL perform the computation it needs to act on \*\*all\* the records, requiring much more work.
If you store the dates in MySQL format WordPress provides a function, [`mysql2date()`](https://developer.wordpress.org/reference/functions/mysql2date/), that can be used for to convert them to a desired format and it's also locale aware.
|
251,614 |
<p>I am working on a script to detect if the user is close enough to our location to display the local version of our website located on a subdomain. I'm looking for help where I should insert this and the best method of redirection from WordPress</p>
<pre><code><?php
$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
$clean = substr($details->loc, 0, -1);
$coord = explode(',', $clean);
$latitudeFrom = floatval($coord[0]);
$longitudeFrom = floatval($coord[1]);
echo "Long: ".$longitudeFrom."\r\n";
echo "Lat: ".$latitudeFrom."\r\n";
$longitudeTo = -68.6833;
$latitudeTo = 33.1711;
$radius = 50; //miles
$latFrom = deg2rad($latitudeFrom);
$lonFrom = deg2rad($longitudeFrom);
$latTo = deg2rad($latitudeTo);
$lonTo = deg2rad($longitudeTo);
$latDelta = $latTo - $latFrom;
echo $latDelta."\r\n";
$lonDelta = $lonTo - $lonFrom;
echo $lonDelta."\r\n";
$angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
$distance = $angle * 3959;
if ($distance < $radius) {
//redirect to local page
}
?>
</code></pre>
|
[
{
"answer_id": 251615,
"author": "czerspalace",
"author_id": 47406,
"author_profile": "https://wordpress.stackexchange.com/users/47406",
"pm_score": 0,
"selected": false,
"text": "<p>In the functions.php file of your theme, I would add an action that hooks to template_redirect, like this (untested) below:</p>\n\n<pre><code><?php\n add_action( 'template_redirect', 'wpse251614_redirect_to_local_site' );\n\n function wpse251614_redirect_to_local_site(){\n $ip = $_SERVER['REMOTE_ADDR'];\n $details = json_decode(file_get_contents(\"http://ipinfo.io/{$ip}/json\"));\n $clean = substr($details->loc, 0, -1);\n $coord = explode(',', $clean);\n $latitudeFrom = floatval($coord[0]);\n $longitudeFrom = floatval($coord[1]);\n echo \"Long: \".$longitudeFrom.\"\\r\\n\";\n echo \"Lat: \".$latitudeFrom.\"\\r\\n\";\n\n $longitudeTo = -68.6833;\n $latitudeTo = 33.1711;\n $radius = 50; //miles\n\n $latFrom = deg2rad($latitudeFrom);\n $lonFrom = deg2rad($longitudeFrom);\n $latTo = deg2rad($latitudeTo);\n $lonTo = deg2rad($longitudeTo);\n\n $latDelta = $latTo - $latFrom;\n echo $latDelta.\"\\r\\n\";\n $lonDelta = $lonTo - $lonFrom;\n echo $lonDelta.\"\\r\\n\";\n\n $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +\n cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));\n $distance = $angle * 3959;\n\n if ($distance < $radius) {\n //redirect to local page\n wp_redirect(LOCAL_PAGE);\n exit;\n }\n }\n?>\n</code></pre>\n\n<p>Reference:</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect</a>\n<a href=\"https://developer.wordpress.org/reference/functions/wp_redirect/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_redirect/</a></p>\n"
},
{
"answer_id": 251616,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>If you want it to run as early as possible, which makes sense if you want to avoid loading unnecessary assets, put the code in a function in a <a href=\"https://codex.wordpress.org/Must_Use_Plugins\" rel=\"nofollow noreferrer\">Must Use Plugin</a>, and hook that function to the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/muplugins_loaded\" rel=\"nofollow noreferrer\"><code>muplugins_loaded</code></a> action.</p>\n\n<pre><code><?php\n\nadd_action( 'muplugins_loaded', 'wpd_my_redirector' );\n\nfunction wpd_my_redirector() {\n\n // your code here\n // wp_redirect is not defined this early, so we use php's header\n\n if( $somecondition === true ){\n header( 'Location: ' . home_url( '/your-local-page/' ) );\n exit;\n }\n}\n</code></pre>\n"
}
] |
2017/01/07
|
[
"https://wordpress.stackexchange.com/questions/251614",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110382/"
] |
I am working on a script to detect if the user is close enough to our location to display the local version of our website located on a subdomain. I'm looking for help where I should insert this and the best method of redirection from WordPress
```
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
$clean = substr($details->loc, 0, -1);
$coord = explode(',', $clean);
$latitudeFrom = floatval($coord[0]);
$longitudeFrom = floatval($coord[1]);
echo "Long: ".$longitudeFrom."\r\n";
echo "Lat: ".$latitudeFrom."\r\n";
$longitudeTo = -68.6833;
$latitudeTo = 33.1711;
$radius = 50; //miles
$latFrom = deg2rad($latitudeFrom);
$lonFrom = deg2rad($longitudeFrom);
$latTo = deg2rad($latitudeTo);
$lonTo = deg2rad($longitudeTo);
$latDelta = $latTo - $latFrom;
echo $latDelta."\r\n";
$lonDelta = $lonTo - $lonFrom;
echo $lonDelta."\r\n";
$angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
$distance = $angle * 3959;
if ($distance < $radius) {
//redirect to local page
}
?>
```
|
If you want it to run as early as possible, which makes sense if you want to avoid loading unnecessary assets, put the code in a function in a [Must Use Plugin](https://codex.wordpress.org/Must_Use_Plugins), and hook that function to the [`muplugins_loaded`](https://codex.wordpress.org/Plugin_API/Action_Reference/muplugins_loaded) action.
```
<?php
add_action( 'muplugins_loaded', 'wpd_my_redirector' );
function wpd_my_redirector() {
// your code here
// wp_redirect is not defined this early, so we use php's header
if( $somecondition === true ){
header( 'Location: ' . home_url( '/your-local-page/' ) );
exit;
}
}
```
|
251,618 |
<p>This is work:
<a href="http://localhost:8888/all-games?s=me" rel="nofollow noreferrer">http://localhost:8888/all-games?s=me</a></p>
<p>This doesn't work (page cannot be found):
<a href="http://localhost:8888/all-games?s=met" rel="nofollow noreferrer">http://localhost:8888/all-games?s=met</a></p>
<p>the post title is: Metal Gear Solid</p>
<p>here is my query:</p>
<pre><code> $args = array("posts_per_page" => get_option("posts_per_page"), "post_type" => "astro_game", "paged" => get_query_var("paged"), "s" => $_GET["s"]);
$wp_query = new wp_query($args);
if ($wp_query -> have_posts()) :
/* Start the Loop */
while ($wp_query -> have_posts()) : $wp_query -> the_post();
get_template_part('template-parts/content-grid', get_post_format());
endwhile;
else :
get_template_part('template-parts/content', 'none');
endif;
</code></pre>
|
[
{
"answer_id": 251619,
"author": "tonywei",
"author_id": 110409,
"author_profile": "https://wordpress.stackexchange.com/users/110409",
"pm_score": 0,
"selected": false,
"text": "<p>change 's' parameter into something else, like \"search\", example: </p>\n\n<p><a href=\"http://localhost:8888/all-games?search=metal\" rel=\"nofollow noreferrer\">http://localhost:8888/all-games?search=metal</a></p>\n\n<p>and change wp_query args:</p>\n\n<pre><code>$args = array(\"posts_per_page\" => get_option(\"posts_per_page\"), \"post_type\" => \"astro_game\", \"paged\" => get_query_var(\"paged\"), \"s\" => $_GET[\"search\"]);\n</code></pre>\n\n<p>and this will work</p>\n"
},
{
"answer_id": 251623,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>You should use <a href=\"https://developer.wordpress.org/reference/functions/get_query_var/\" rel=\"nofollow noreferrer\"><strong><code>get_query_var</code></strong></a> instead of <code>$_GET[\"s\"]</code>, this is a built-in wordpress function that retrieves <strong>public</strong> query variables which would have already been parsed and fed into WP_Query.</p>\n\n<pre><code>$args = array(\"posts_per_page\" => get_option(\"posts_per_page\"), \"post_type\" => \"astro_game\", \"paged\" => get_query_var(\"paged\"), \"s\" => get_query_var(\"s\");\n</code></pre>\n\n<p><strong>Reference: <a href=\"https://codex.wordpress.org/WordPress_Query_Vars#Query_variables\" rel=\"nofollow noreferrer\">WordPress_Query_Vars</a></strong></p>\n"
}
] |
2017/01/07
|
[
"https://wordpress.stackexchange.com/questions/251618",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110409/"
] |
This is work:
<http://localhost:8888/all-games?s=me>
This doesn't work (page cannot be found):
<http://localhost:8888/all-games?s=met>
the post title is: Metal Gear Solid
here is my query:
```
$args = array("posts_per_page" => get_option("posts_per_page"), "post_type" => "astro_game", "paged" => get_query_var("paged"), "s" => $_GET["s"]);
$wp_query = new wp_query($args);
if ($wp_query -> have_posts()) :
/* Start the Loop */
while ($wp_query -> have_posts()) : $wp_query -> the_post();
get_template_part('template-parts/content-grid', get_post_format());
endwhile;
else :
get_template_part('template-parts/content', 'none');
endif;
```
|
You should use [**`get_query_var`**](https://developer.wordpress.org/reference/functions/get_query_var/) instead of `$_GET["s"]`, this is a built-in wordpress function that retrieves **public** query variables which would have already been parsed and fed into WP\_Query.
```
$args = array("posts_per_page" => get_option("posts_per_page"), "post_type" => "astro_game", "paged" => get_query_var("paged"), "s" => get_query_var("s");
```
**Reference: [WordPress\_Query\_Vars](https://codex.wordpress.org/WordPress_Query_Vars#Query_variables)**
|
251,620 |
<p>Function:</p>
<pre><code>function get_highest_bid(){
global $wpdb;
$postid = get_post_id();
$table = $wpdb->prefix . "jwp_bids";
$highest_bid = $wpdb->get_var(
"Select max(bid_amt)
FROM " . $table . "
WHERE post_id = " . $postid . ';" );'
echo $highest_bid;
}
</code></pre>
<p>Error:
Unexpected echo line blah blah.</p>
<p>Question:
What did I do wrong concatenating that <code>; );</code> at the end? Concatenating when quotes are part of the statement confuses the dickens out of me. Any tips on that?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 251619,
"author": "tonywei",
"author_id": 110409,
"author_profile": "https://wordpress.stackexchange.com/users/110409",
"pm_score": 0,
"selected": false,
"text": "<p>change 's' parameter into something else, like \"search\", example: </p>\n\n<p><a href=\"http://localhost:8888/all-games?search=metal\" rel=\"nofollow noreferrer\">http://localhost:8888/all-games?search=metal</a></p>\n\n<p>and change wp_query args:</p>\n\n<pre><code>$args = array(\"posts_per_page\" => get_option(\"posts_per_page\"), \"post_type\" => \"astro_game\", \"paged\" => get_query_var(\"paged\"), \"s\" => $_GET[\"search\"]);\n</code></pre>\n\n<p>and this will work</p>\n"
},
{
"answer_id": 251623,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>You should use <a href=\"https://developer.wordpress.org/reference/functions/get_query_var/\" rel=\"nofollow noreferrer\"><strong><code>get_query_var</code></strong></a> instead of <code>$_GET[\"s\"]</code>, this is a built-in wordpress function that retrieves <strong>public</strong> query variables which would have already been parsed and fed into WP_Query.</p>\n\n<pre><code>$args = array(\"posts_per_page\" => get_option(\"posts_per_page\"), \"post_type\" => \"astro_game\", \"paged\" => get_query_var(\"paged\"), \"s\" => get_query_var(\"s\");\n</code></pre>\n\n<p><strong>Reference: <a href=\"https://codex.wordpress.org/WordPress_Query_Vars#Query_variables\" rel=\"nofollow noreferrer\">WordPress_Query_Vars</a></strong></p>\n"
}
] |
2017/01/07
|
[
"https://wordpress.stackexchange.com/questions/251620",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108215/"
] |
Function:
```
function get_highest_bid(){
global $wpdb;
$postid = get_post_id();
$table = $wpdb->prefix . "jwp_bids";
$highest_bid = $wpdb->get_var(
"Select max(bid_amt)
FROM " . $table . "
WHERE post_id = " . $postid . ';" );'
echo $highest_bid;
}
```
Error:
Unexpected echo line blah blah.
Question:
What did I do wrong concatenating that `; );` at the end? Concatenating when quotes are part of the statement confuses the dickens out of me. Any tips on that?
Thanks!
|
You should use [**`get_query_var`**](https://developer.wordpress.org/reference/functions/get_query_var/) instead of `$_GET["s"]`, this is a built-in wordpress function that retrieves **public** query variables which would have already been parsed and fed into WP\_Query.
```
$args = array("posts_per_page" => get_option("posts_per_page"), "post_type" => "astro_game", "paged" => get_query_var("paged"), "s" => get_query_var("s");
```
**Reference: [WordPress\_Query\_Vars](https://codex.wordpress.org/WordPress_Query_Vars#Query_variables)**
|
251,648 |
<p>I have a parent theme that refers to an image in the theme's <code>img</code> folder like so;</p>
<pre><code><button id="buy" type="submit"><img src="<?php bloginfo('template_directory'); ?>/img/Buy-Now-Button.jpg" border="0" width="160" height="47" title="" alt="Buy One" style="cursor:pointer;"></button>
</code></pre>
<p>However, I thought that if I activated a child theme and then within that child theme there was another <code>img</code>folder with a different Buy-Now-Button.jpg then that would be used instead of the one in the parent them.</p>
<p>My aim is to allow users to use their own buy now button if they want to simply by placing it in the child theme img folder, am I going about this the right way?</p>
|
[
{
"answer_id": 251650,
"author": "Felix",
"author_id": 110428,
"author_profile": "https://wordpress.stackexchange.com/users/110428",
"pm_score": 3,
"selected": true,
"text": "<p>Try using <code>get_stylesheet_directory_uri()</code> instead of <code>bloginfo('template_directory')</code>.</p>\n\n<p>This function will give you the path to the <code>style.css</code> of your currently activated theme (the child theme). From there you can navigate to all sub-folders in your child theme folder.</p>\n\n<pre><code><button id=\"buy\" type=\"submit\"><img src=\"<?php get_stylesheet_directory_uri(); ?>/img/Buy-Now-Button.jpg\" border=\"0\" width=\"160\" height=\"47\" title=\"\" alt=\"Buy One\" style=\"cursor:pointer;\"></button>\n</code></pre>\n"
},
{
"answer_id": 251672,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>There are new functions on board, finally some intuitive names.\n<code>get_parent_theme_file_uri</code> and <code>get_theme_file_uri</code>.</p>\n\n<p>You may use that instead of <code>get_stylesheet_directory_uri()</code>.</p>\n\n<pre><code>File: wp-includes/link-template.php\n4026: /**\n4027: * Retrieves the URL of a file in the theme.\n4028: *\n4029: * Searches in the stylesheet directory before the template directory so themes\n4030: * which inherit from a parent theme can just override one file.\n4031: *\n4032: * @since 4.7.0\n4033: *\n4034: * @param string $file Optional. File to search for in the stylesheet directory.\n4035: * @return string The URL of the file.\n4036: */\n4037: function get_theme_file_uri( $file = '' ) {\n4038: $file = ltrim( $file, '/' );\n4039: \n4040: if ( empty( $file ) ) {\n4041: $url = get_stylesheet_directory_uri();\n4042: } elseif ( file_exists( get_stylesheet_directory() . '/' . $file ) ) {\n4043: $url = get_stylesheet_directory_uri() . '/' . $file;\n4044: } else {\n4045: $url = get_template_directory_uri() . '/' . $file;\n4046: }\n4047: \n4048: /**\n4049: * Filters the URL to a file in the theme.\n4050: *\n4051: * @since 4.7.0\n4052: *\n4053: * @param string $url The file URL.\n4054: * @param string $file The requested file to search for.\n4055: */\n4056: return apply_filters( 'theme_file_uri', $url, $file );\n4057: }\n</code></pre>\n\n<p>And</p>\n\n<pre><code>File: wp-includes/link-template.php\n4059: /**\n4060: * Retrieves the URL of a file in the parent theme.\n4061: *\n4062: * @since 4.7.0\n4063: *\n4064: * @param string $file Optional. File to return the URL for in the template directory.\n4065: * @return string The URL of the file.\n4066: */\n4067: function get_parent_theme_file_uri( $file = '' ) {\n4068: $file = ltrim( $file, '/' );\n4069: \n4070: if ( empty( $file ) ) {\n4071: $url = get_template_directory_uri();\n4072: } else {\n4073: $url = get_template_directory_uri() . '/' . $file;\n4074: }\n4075: \n4076: /**\n4077: * Filters the URL to a file in the parent theme.\n4078: *\n4079: * @since 4.7.0\n4080: *\n4081: * @param string $url The file URL.\n4082: * @param string $file The requested file to search for.\n4083: */\n4084: return apply_filters( 'parent_theme_file_uri', $url, $file );\n4085: }\n</code></pre>\n\n<p>Twentyseventeen uses for instnace them when accessing resources. ZBe.:</p>\n\n<pre><code>File: wp-content/themes/twentyseventeen/inc/custom-header.php\n36: add_theme_support( 'custom-header', apply_filters( 'twentyseventeen_custom_header_args', array(\n37: 'default-image' => get_parent_theme_file_uri( '/assets/images/header.jpg' ),\n38: 'width' => 2000,\n39: 'height' => 1200,\n40: 'flex-height' => true,\n41: 'video' => true,\n42: 'wp-head-callback' => 'twentyseventeen_header_style',\n43: ) ) );\n</code></pre>\n"
}
] |
2017/01/07
|
[
"https://wordpress.stackexchange.com/questions/251648",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/36773/"
] |
I have a parent theme that refers to an image in the theme's `img` folder like so;
```
<button id="buy" type="submit"><img src="<?php bloginfo('template_directory'); ?>/img/Buy-Now-Button.jpg" border="0" width="160" height="47" title="" alt="Buy One" style="cursor:pointer;"></button>
```
However, I thought that if I activated a child theme and then within that child theme there was another `img`folder with a different Buy-Now-Button.jpg then that would be used instead of the one in the parent them.
My aim is to allow users to use their own buy now button if they want to simply by placing it in the child theme img folder, am I going about this the right way?
|
Try using `get_stylesheet_directory_uri()` instead of `bloginfo('template_directory')`.
This function will give you the path to the `style.css` of your currently activated theme (the child theme). From there you can navigate to all sub-folders in your child theme folder.
```
<button id="buy" type="submit"><img src="<?php get_stylesheet_directory_uri(); ?>/img/Buy-Now-Button.jpg" border="0" width="160" height="47" title="" alt="Buy One" style="cursor:pointer;"></button>
```
|
251,652 |
<p>I just want some information about WP_DEBUG.</p>
<p>What happen if I comment this line in wp-config.php files</p>
<pre><code>define('WP_DEBUG',true);
</code></pre>
<p>I had an issue on the site where my server getting down and database where crashing, so my server guy advice me that, this comment code is causing issue on the server and the database and please uncomment this.</p>
<p>Can someone please advice, that commenting this code can cause issue on server or the database ?</p>
|
[
{
"answer_id": 251658,
"author": "Dohnutt",
"author_id": 110437,
"author_profile": "https://wordpress.stackexchange.com/users/110437",
"pm_score": 0,
"selected": false,
"text": "<p>Setting <code>WP_DEBUG</code> to <code>true</code> will show that you have errors on your website, but shouldn't cause them. Rather than commenting out this code—if you want to disable it—you should set it to <code>false</code> instead.</p>\n"
},
{
"answer_id": 251664,
"author": "JMau",
"author_id": 31376,
"author_profile": "https://wordpress.stackexchange.com/users/31376",
"pm_score": 1,
"selected": false,
"text": "<p>IMHO WP_DEBUG allows to enable display of notices during development. If you look at the core file <code>default-constants.php</code> you see this :</p>\n\n<pre><code>if ( !defined('WP_DEBUG') )\n define( 'WP_DEBUG', false );\n</code></pre>\n\n<p>So I don't see why you should set it to false <em>again</em> in <code>wp-config.php</code>. </p>\n\n<p>Regarding your issue just delete the line, WP_DEBUG should never be used on a live website, it's a developer tool.</p>\n\n<p>The fact that the constant cannot cause anything it's a display tool. However maybe we have to admit that in a very weird universe bad things happen such as error display on a live site. If that's the case you can leave the WP_DEBUG constant set to true and hide display like that :</p>\n\n<pre><code>define( 'WP_DEBUG_DISPLAY', false );\n</code></pre>\n\n<p>Your server guy should know that errors should never be shown on a live website.</p>\n\n<p><a href=\"https://codex.wordpress.org/Debugging_in_WordPress#WP_DEBUG_DISPLAY\" rel=\"nofollow noreferrer\">Source</a></p>\n"
},
{
"answer_id": 251666,
"author": "Felix",
"author_id": 110428,
"author_profile": "https://wordpress.stackexchange.com/users/110428",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't know, what this line of code is good for, I recommend you to remove it (just this one).</p>\n\n<p>As stated by JMau, <code>WP_DEBUG</code> is only for development. If you activate the debug mode by adding <code>define('WP_DEBUG',true);</code> to your <code>wp-config.php</code> your website will display sensitive data to all of your visitors. </p>\n\n<p>If you're experiencing some PHP or database error, this at least would look ugly. An attacker could use the provided information for hacking into your blog.</p>\n\n<p>And: in combination with other DEBUG settings (like <code>SAVEQUERIES</code>), <code>WP_DEBUG</code> <em>can</em> lead to performance issues. </p>\n\n<p>I suggest you read more about debugging in WordPress on the official codex site: <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow noreferrer\">Debugging in WordPress</a></p>\n"
}
] |
2017/01/07
|
[
"https://wordpress.stackexchange.com/questions/251652",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104250/"
] |
I just want some information about WP\_DEBUG.
What happen if I comment this line in wp-config.php files
```
define('WP_DEBUG',true);
```
I had an issue on the site where my server getting down and database where crashing, so my server guy advice me that, this comment code is causing issue on the server and the database and please uncomment this.
Can someone please advice, that commenting this code can cause issue on server or the database ?
|
IMHO WP\_DEBUG allows to enable display of notices during development. If you look at the core file `default-constants.php` you see this :
```
if ( !defined('WP_DEBUG') )
define( 'WP_DEBUG', false );
```
So I don't see why you should set it to false *again* in `wp-config.php`.
Regarding your issue just delete the line, WP\_DEBUG should never be used on a live website, it's a developer tool.
The fact that the constant cannot cause anything it's a display tool. However maybe we have to admit that in a very weird universe bad things happen such as error display on a live site. If that's the case you can leave the WP\_DEBUG constant set to true and hide display like that :
```
define( 'WP_DEBUG_DISPLAY', false );
```
Your server guy should know that errors should never be shown on a live website.
[Source](https://codex.wordpress.org/Debugging_in_WordPress#WP_DEBUG_DISPLAY)
|
251,661 |
<p>Okay, so when I include my header in any page besides the home page, and I inspect the page, all of the calls show as errors because it's adding that page to the root of the source call. How do I change that?? Here are some of my calls:</p>
<pre><code><script src="wp-content/themes/gamer_meld/js/jquery.flexslider.js"></script>
<script src="wp-content/themes/gamer_meld/js/fancySelect.js"></script>
<script src="wp-content/themes/gamer_meld/js/script.js"></script>
</code></pre>
|
[
{
"answer_id": 251662,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": true,
"text": "<p>First, don't put script tags directly in template files, enqueue them from your theme/child theme's <code>functions.php</code>. Second, use the API to output URIs for scripts, don't hardcode or use relative paths.</p>\n\n<pre><code>function wpdocs_theme_name_scripts() {\n wp_enqueue_script(\n 'flexslider',\n get_template_directory_uri() . '/js/jquery.flexslider.js',\n array('jquery'),\n null,\n true\n );\n wp_enqueue_script(\n 'fancyselect',\n get_template_directory_uri() . '/js/fancySelect.js',\n array('jquery'),\n null,\n true\n );\n wp_enqueue_script(\n 'myscript',\n get_template_directory_uri() . '/js/script.js',\n array('jquery'),\n null,\n true\n );\n}\nadd_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );\n</code></pre>\n"
},
{
"answer_id": 251663,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>While everything @milo says is true, your core problem is cuased by you using relative urls. Never ever use relative urls as you never know where they are going to point to in different pages</p>\n"
}
] |
2017/01/07
|
[
"https://wordpress.stackexchange.com/questions/251661",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108586/"
] |
Okay, so when I include my header in any page besides the home page, and I inspect the page, all of the calls show as errors because it's adding that page to the root of the source call. How do I change that?? Here are some of my calls:
```
<script src="wp-content/themes/gamer_meld/js/jquery.flexslider.js"></script>
<script src="wp-content/themes/gamer_meld/js/fancySelect.js"></script>
<script src="wp-content/themes/gamer_meld/js/script.js"></script>
```
|
First, don't put script tags directly in template files, enqueue them from your theme/child theme's `functions.php`. Second, use the API to output URIs for scripts, don't hardcode or use relative paths.
```
function wpdocs_theme_name_scripts() {
wp_enqueue_script(
'flexslider',
get_template_directory_uri() . '/js/jquery.flexslider.js',
array('jquery'),
null,
true
);
wp_enqueue_script(
'fancyselect',
get_template_directory_uri() . '/js/fancySelect.js',
array('jquery'),
null,
true
);
wp_enqueue_script(
'myscript',
get_template_directory_uri() . '/js/script.js',
array('jquery'),
null,
true
);
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );
```
|
251,676 |
<p>I am migrating from an ancient static web site to Wordpress.</p>
<p>In the old site, I used htaccess and RewriteRule to simplify URLs and mask the underlying parms. One case was:</p>
<pre><code>RewriteRule ^definition/([^/]+) /display-definition?word=$1 [NC]
</code></pre>
<p>This allowed people to specify a URL of:</p>
<pre><code>domain.com/definition/love
</code></pre>
<p>And under the sheets executed instead:</p>
<pre><code>domain.com/display-definition?word=love
</code></pre>
<p>I have created and tested the new Wordpress page, and manually passing it the parameter works fine. The htaccess redirect does not, and instead tosses visitors to the default Wordpress 404 page.</p>
<p>I have tried placing the RewriteRule in various places in htaccess, but the results do not differ.</p>
<p>Current attempted htaccess file is:</p>
<pre><code>RewriteEngine on
RewriteRule ^definition/([^/]+) /display-definition?word=$1 [NC]
RewriteRule ^murphyism/([^/]+) /display-murphy?id=$1 [NC]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
|
[
{
"answer_id": 251662,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": true,
"text": "<p>First, don't put script tags directly in template files, enqueue them from your theme/child theme's <code>functions.php</code>. Second, use the API to output URIs for scripts, don't hardcode or use relative paths.</p>\n\n<pre><code>function wpdocs_theme_name_scripts() {\n wp_enqueue_script(\n 'flexslider',\n get_template_directory_uri() . '/js/jquery.flexslider.js',\n array('jquery'),\n null,\n true\n );\n wp_enqueue_script(\n 'fancyselect',\n get_template_directory_uri() . '/js/fancySelect.js',\n array('jquery'),\n null,\n true\n );\n wp_enqueue_script(\n 'myscript',\n get_template_directory_uri() . '/js/script.js',\n array('jquery'),\n null,\n true\n );\n}\nadd_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );\n</code></pre>\n"
},
{
"answer_id": 251663,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>While everything @milo says is true, your core problem is cuased by you using relative urls. Never ever use relative urls as you never know where they are going to point to in different pages</p>\n"
}
] |
2017/01/07
|
[
"https://wordpress.stackexchange.com/questions/251676",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110445/"
] |
I am migrating from an ancient static web site to Wordpress.
In the old site, I used htaccess and RewriteRule to simplify URLs and mask the underlying parms. One case was:
```
RewriteRule ^definition/([^/]+) /display-definition?word=$1 [NC]
```
This allowed people to specify a URL of:
```
domain.com/definition/love
```
And under the sheets executed instead:
```
domain.com/display-definition?word=love
```
I have created and tested the new Wordpress page, and manually passing it the parameter works fine. The htaccess redirect does not, and instead tosses visitors to the default Wordpress 404 page.
I have tried placing the RewriteRule in various places in htaccess, but the results do not differ.
Current attempted htaccess file is:
```
RewriteEngine on
RewriteRule ^definition/([^/]+) /display-definition?word=$1 [NC]
RewriteRule ^murphyism/([^/]+) /display-murphy?id=$1 [NC]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
|
First, don't put script tags directly in template files, enqueue them from your theme/child theme's `functions.php`. Second, use the API to output URIs for scripts, don't hardcode or use relative paths.
```
function wpdocs_theme_name_scripts() {
wp_enqueue_script(
'flexslider',
get_template_directory_uri() . '/js/jquery.flexslider.js',
array('jquery'),
null,
true
);
wp_enqueue_script(
'fancyselect',
get_template_directory_uri() . '/js/fancySelect.js',
array('jquery'),
null,
true
);
wp_enqueue_script(
'myscript',
get_template_directory_uri() . '/js/script.js',
array('jquery'),
null,
true
);
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );
```
|
251,678 |
<p>I have some custom PHP that creates a shortcode. I must have some errant code in here because it is showing up on the backend (edit side) of Wordpress. I am using the Divi theme and have it in a Text module with a class "SearchBarArea". So that is the name of the DIV it should be in, but on the front end, it is NOT in that DIV it is coming in right after "entry-content". Any idea?</p>
<pre><code>function searchbar_function() {//Creates shortcode [searchbar]
$MainCategories = get_categories( array(
'orderby' => 'name',
'parent' => 0
) );//Grabs just the parent categories
?>
<form action="action_page.php">
<?php
foreach ( $MainCategories as $MainCategory ) {
$MainCatID=esc_html($MainCategory->term_id);//Gets Main Category ID
if($MainCatID!=='1' && $MainCatID!=='153'){//Exclude Uncategorized or Featured from Main Category List
$MainCatURL=esc_url( get_category_link( $MainCategory->term_id ) );//Gets Main Category URL
$MainCatName=esc_html( $MainCategory->name );//Gets Main Category Name
$MainCatSlug=esc_html( $MainCategory->slug );//Gets Main Category Slug
$MainCatCount=esc_html( $MainCategory->category_count );
$MainCat='<label>'.$MainCatName.'</label>';
echo $MainCat;
$MainCatCode='<option value="'.$MainCatSlug.'">ALL '.$MainCatName.'</option>';?>
<select name="<?php echo $MainCatSlug?>-dropdown">
<option value=""><?php echo esc_attr_e( 'Select:', 'textdomain' ); ?></option>
<?php
echo $MainCatCode;//Makes Main Category first choice
$categories = get_categories( array( 'child_of' => $MainCatID ) );//Number is the Main Category ID
foreach ( $categories as $category ) {
$SubCatValueName= esc_attr($category->category_nicename);
$SubCatValue= esc_attr( '/category/archives/' . $category->category_nicename );
$SubCatName=esc_html( $category->cat_name );
$SubCatCount=esc_html( $category->category_count );
$SubCatOption ='<option value="'.$SubCatValueName.'">'.$SubCatName.'</option>';
echo $SubCatOption;
}
?>
</select>
<?php
}
}?>
<input type="submit" value="Search">
</form>
<?php
}
add_shortcode( 'searchbar', 'searchbar_function' );
</code></pre>
|
[
{
"answer_id": 251679,
"author": "CompuSolver",
"author_id": 110446,
"author_profile": "https://wordpress.stackexchange.com/users/110446",
"pm_score": 1,
"selected": false,
"text": "<p>Even with the missing open php tag, this won't work the way you're trying to do it. The Divi code module accepts html code and PHP shortcodes. I haven't tried javascript, so not sure about that.</p>\n\n<p>You'll need to integrate your code as a stand alone plugin. After that, you can use the shortcode in the Divi code module and should also be able to use it in the text tab mode.</p>\n"
},
{
"answer_id": 251752,
"author": "Kirk",
"author_id": 110216,
"author_profile": "https://wordpress.stackexchange.com/users/110216",
"pm_score": 1,
"selected": false,
"text": "<p>I figured it out.I rearranged the HTML and used variables so there was no break in the code. I also removed</p>\n\n<pre><code>esc_attr_e( 'Select:', 'textdomain' );\n</code></pre>\n\n<p>Because it was causing the results to appear outside the DIV the shortcode was put in.</p>\n\n<pre><code>function searchbar_function() {//Creates shortcode [searchbar]\n$MainCategories = get_categories( array(\n 'orderby' => 'name',\n 'parent' => 0\n) );//Grabs just the parent categories\n$CodeResult.='<form action=\"action_page.php\">';\n\nforeach ( $MainCategories as $MainCategory ) {\n $MainCatID=esc_html($MainCategory->term_id);//Gets Main Category ID\n if($MainCatID!=='1' && $MainCatID!=='153'){//Exclude Uncategorized or Featured from Main Category List\n $MainCatURL=esc_url( get_category_link( $MainCategory->term_id ) );//Gets Main Category URL\n $MainCatName=esc_html( $MainCategory->name );//Gets Main Category Name\n $MainCatSlug=esc_html( $MainCategory->slug );//Gets Main Category Slug\n $MainCatCount=esc_html( $MainCategory->category_count );\n $MainCat='<label>'.$MainCatName.'</label>';\n $MainCatCode='<option value=\"'.$MainCatSlug.'\">ALL '.$MainCatName.'</option>';\n $CodeResult.=$MainCat;\n $SelectCode='<select name=\"'.$MainCatSlug.'-dropdown\"><option value=\"\">Select:</option>';\n $CodeResult.=$SelectCode;\n $CodeResult.=$MainCatCode;//Makes Main Category first choice\n $categories = get_categories( array( 'child_of' => $MainCatID ) );//Number is the Main Category ID \n foreach ( $categories as $category ) {\n $SubCatValueName= esc_attr($category->category_nicename);\n $SubCatValue= esc_attr( '/category/archives/' . $category->category_nicename );\n $SubCatName=esc_html( $category->cat_name );\n $SubCatCount=esc_html( $category->category_count );\n $SubCatOption ='<option value=\"'.$SubCatValueName.'\">'.$SubCatName.'</option>';\n $CodeResult.=$SubCatOption;\n }\n $CodeResult.='</select>';\n }\n}\n$SubmitEnd='<input type=\"submit\" value=\"Search\">\n </form>';\n$CodeResult.=$SubmitEnd;\n return $CodeResult;\n}\nadd_shortcode( 'searchbar', 'searchbar_function' );\n</code></pre>\n"
},
{
"answer_id": 251801,
"author": "Thinkerman",
"author_id": 110469,
"author_profile": "https://wordpress.stackexchange.com/users/110469",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code>ob_start()</code> before starting your shortcode codes and right after the shortcode codes use something like</p>\n\n<pre><code>$my_clean_ob = ob_get_clean();\nreturn $my_clean_ob;\n</code></pre>\n\n<p>Hope it helps. </p>\n"
}
] |
2017/01/07
|
[
"https://wordpress.stackexchange.com/questions/251678",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110216/"
] |
I have some custom PHP that creates a shortcode. I must have some errant code in here because it is showing up on the backend (edit side) of Wordpress. I am using the Divi theme and have it in a Text module with a class "SearchBarArea". So that is the name of the DIV it should be in, but on the front end, it is NOT in that DIV it is coming in right after "entry-content". Any idea?
```
function searchbar_function() {//Creates shortcode [searchbar]
$MainCategories = get_categories( array(
'orderby' => 'name',
'parent' => 0
) );//Grabs just the parent categories
?>
<form action="action_page.php">
<?php
foreach ( $MainCategories as $MainCategory ) {
$MainCatID=esc_html($MainCategory->term_id);//Gets Main Category ID
if($MainCatID!=='1' && $MainCatID!=='153'){//Exclude Uncategorized or Featured from Main Category List
$MainCatURL=esc_url( get_category_link( $MainCategory->term_id ) );//Gets Main Category URL
$MainCatName=esc_html( $MainCategory->name );//Gets Main Category Name
$MainCatSlug=esc_html( $MainCategory->slug );//Gets Main Category Slug
$MainCatCount=esc_html( $MainCategory->category_count );
$MainCat='<label>'.$MainCatName.'</label>';
echo $MainCat;
$MainCatCode='<option value="'.$MainCatSlug.'">ALL '.$MainCatName.'</option>';?>
<select name="<?php echo $MainCatSlug?>-dropdown">
<option value=""><?php echo esc_attr_e( 'Select:', 'textdomain' ); ?></option>
<?php
echo $MainCatCode;//Makes Main Category first choice
$categories = get_categories( array( 'child_of' => $MainCatID ) );//Number is the Main Category ID
foreach ( $categories as $category ) {
$SubCatValueName= esc_attr($category->category_nicename);
$SubCatValue= esc_attr( '/category/archives/' . $category->category_nicename );
$SubCatName=esc_html( $category->cat_name );
$SubCatCount=esc_html( $category->category_count );
$SubCatOption ='<option value="'.$SubCatValueName.'">'.$SubCatName.'</option>';
echo $SubCatOption;
}
?>
</select>
<?php
}
}?>
<input type="submit" value="Search">
</form>
<?php
}
add_shortcode( 'searchbar', 'searchbar_function' );
```
|
Even with the missing open php tag, this won't work the way you're trying to do it. The Divi code module accepts html code and PHP shortcodes. I haven't tried javascript, so not sure about that.
You'll need to integrate your code as a stand alone plugin. After that, you can use the shortcode in the Divi code module and should also be able to use it in the text tab mode.
|
251,696 |
<p>Here is what I have so far:</p>
<pre><code>function get_highest_bid_info(){
global $wpdb;
$postid = get_the_id();
$table = $wpdb->prefix . "jwp_bids";
$wpdb->get_results(
"SELECT email, max(bid_amt)
FROM $table
WHERE post_id = '$postid')"
);
</code></pre>
<p>Now I want to assign those two values to independent variables such as <code>$high_bid</code> and <code>$high_bidder</code>. I know the two values are in an array of some sort. I read in the codex but don't ascertain from that How to access and assign them?</p>
<p>Any help is greatly appreciated. I'm learning here :)</p>
<p>Thanks!</p>
|
[
{
"answer_id": 251679,
"author": "CompuSolver",
"author_id": 110446,
"author_profile": "https://wordpress.stackexchange.com/users/110446",
"pm_score": 1,
"selected": false,
"text": "<p>Even with the missing open php tag, this won't work the way you're trying to do it. The Divi code module accepts html code and PHP shortcodes. I haven't tried javascript, so not sure about that.</p>\n\n<p>You'll need to integrate your code as a stand alone plugin. After that, you can use the shortcode in the Divi code module and should also be able to use it in the text tab mode.</p>\n"
},
{
"answer_id": 251752,
"author": "Kirk",
"author_id": 110216,
"author_profile": "https://wordpress.stackexchange.com/users/110216",
"pm_score": 1,
"selected": false,
"text": "<p>I figured it out.I rearranged the HTML and used variables so there was no break in the code. I also removed</p>\n\n<pre><code>esc_attr_e( 'Select:', 'textdomain' );\n</code></pre>\n\n<p>Because it was causing the results to appear outside the DIV the shortcode was put in.</p>\n\n<pre><code>function searchbar_function() {//Creates shortcode [searchbar]\n$MainCategories = get_categories( array(\n 'orderby' => 'name',\n 'parent' => 0\n) );//Grabs just the parent categories\n$CodeResult.='<form action=\"action_page.php\">';\n\nforeach ( $MainCategories as $MainCategory ) {\n $MainCatID=esc_html($MainCategory->term_id);//Gets Main Category ID\n if($MainCatID!=='1' && $MainCatID!=='153'){//Exclude Uncategorized or Featured from Main Category List\n $MainCatURL=esc_url( get_category_link( $MainCategory->term_id ) );//Gets Main Category URL\n $MainCatName=esc_html( $MainCategory->name );//Gets Main Category Name\n $MainCatSlug=esc_html( $MainCategory->slug );//Gets Main Category Slug\n $MainCatCount=esc_html( $MainCategory->category_count );\n $MainCat='<label>'.$MainCatName.'</label>';\n $MainCatCode='<option value=\"'.$MainCatSlug.'\">ALL '.$MainCatName.'</option>';\n $CodeResult.=$MainCat;\n $SelectCode='<select name=\"'.$MainCatSlug.'-dropdown\"><option value=\"\">Select:</option>';\n $CodeResult.=$SelectCode;\n $CodeResult.=$MainCatCode;//Makes Main Category first choice\n $categories = get_categories( array( 'child_of' => $MainCatID ) );//Number is the Main Category ID \n foreach ( $categories as $category ) {\n $SubCatValueName= esc_attr($category->category_nicename);\n $SubCatValue= esc_attr( '/category/archives/' . $category->category_nicename );\n $SubCatName=esc_html( $category->cat_name );\n $SubCatCount=esc_html( $category->category_count );\n $SubCatOption ='<option value=\"'.$SubCatValueName.'\">'.$SubCatName.'</option>';\n $CodeResult.=$SubCatOption;\n }\n $CodeResult.='</select>';\n }\n}\n$SubmitEnd='<input type=\"submit\" value=\"Search\">\n </form>';\n$CodeResult.=$SubmitEnd;\n return $CodeResult;\n}\nadd_shortcode( 'searchbar', 'searchbar_function' );\n</code></pre>\n"
},
{
"answer_id": 251801,
"author": "Thinkerman",
"author_id": 110469,
"author_profile": "https://wordpress.stackexchange.com/users/110469",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code>ob_start()</code> before starting your shortcode codes and right after the shortcode codes use something like</p>\n\n<pre><code>$my_clean_ob = ob_get_clean();\nreturn $my_clean_ob;\n</code></pre>\n\n<p>Hope it helps. </p>\n"
}
] |
2017/01/08
|
[
"https://wordpress.stackexchange.com/questions/251696",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108215/"
] |
Here is what I have so far:
```
function get_highest_bid_info(){
global $wpdb;
$postid = get_the_id();
$table = $wpdb->prefix . "jwp_bids";
$wpdb->get_results(
"SELECT email, max(bid_amt)
FROM $table
WHERE post_id = '$postid')"
);
```
Now I want to assign those two values to independent variables such as `$high_bid` and `$high_bidder`. I know the two values are in an array of some sort. I read in the codex but don't ascertain from that How to access and assign them?
Any help is greatly appreciated. I'm learning here :)
Thanks!
|
Even with the missing open php tag, this won't work the way you're trying to do it. The Divi code module accepts html code and PHP shortcodes. I haven't tried javascript, so not sure about that.
You'll need to integrate your code as a stand alone plugin. After that, you can use the shortcode in the Divi code module and should also be able to use it in the text tab mode.
|
251,702 |
<p>In my single wordpress posts I want to apply a padding of 100px to the left and right. The problem is that when I apply it to .single .post-content the images also get a padding. However, I want all of the images on the posts pages to be set to 100%. Is there a way to separate the actual body text and the images? This seems like a fairly simple question. But I can't figure it out. Any help is appreciated.</p>
<p>single.php</p>
<pre class="lang-html prettyprint-override"><code><?php
get_header();
if (have_posts()) :
while (have_posts()) : the_post(); ?>
<article class="post">
<?php $featuredImage = wp_get_attachment_url( get_post_thumbnail_id($post->ID), 'full' ); ?>
<div class="banner" style="background:url(<?php echo $featuredImage; ?>) no-repeat;"></div>
<?php wpb_set_post_views(get_the_ID()); ?>
<div class="post-info">
<h1 class="post-title"><?php the_title(); ?></h1>
<h2 class="post-date"><?php echo strip_tags(get_the_term_list( $post->ID, 'location', 'Location: ', ', ', ' • ' ));?><?php the_date('F m, Y'); ?></h2>
</div>
<div class="post-content"><?php the_content(); ?></div>
<div id="wrapper-footer"><div class="post-footer"><h1 class="post-footer-comment"><?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'post-footer-comment-count', 'none'); ?></h1><div class="share"><span>share</span> <?php get_template_part( 'share-buttons-post' ); ?></div></div>
<div class="post-footer-bloglovin"><h1>never miss a post</h1><h2><a href="#">follow on email'</a></h2></div></div>
<?php get_template_part( 'prevandnextpost' ); ?>
<?php get_template_part( 'related-posts' ); ?>
<?php comments_template(); ?>
</article>
<?php endwhile;
else :
echo '<p>No content found</p>';
endif;
get_footer();
?>
</code></pre>
<p>css</p>
<pre class="lang-html prettyprint-override"><code>.single .post-title,
.post-title a,
.post-title a:link, .post-title a:visited {
font-family: 'Questrial', sans-serif;
font-size:30px;
margin-left:6px;
margin: 0 auto;
color:#000000;
margin-bottom: 3px;
margin-top:30px;
}
.single .post-date {
font-family: 'Questrial', sans-serif;
font-size:13px;
margin-left:6px;
margin: 0 auto;
color:#000000;
}
.single .post-content {
text-decoration: none;
color: #000000;
display: block;
font-family: 'Crimson Text', serif;
font-size: 18px;
margin:0 auto;
margin-top: -50px;
}
.single .post-info {
background:#ffffff;
padding-left: 100px;
padding-right:100px;
max-width: 1865px;
background-position:center;
background-clip: content-box;
margin: 0 auto;
height:110px;
bottom:100px;
position: relative;
}
.single img {
max-width:100%;
padding: 0 0 0 0 !important;
height:auto;
}
</code></pre>
|
[
{
"answer_id": 251679,
"author": "CompuSolver",
"author_id": 110446,
"author_profile": "https://wordpress.stackexchange.com/users/110446",
"pm_score": 1,
"selected": false,
"text": "<p>Even with the missing open php tag, this won't work the way you're trying to do it. The Divi code module accepts html code and PHP shortcodes. I haven't tried javascript, so not sure about that.</p>\n\n<p>You'll need to integrate your code as a stand alone plugin. After that, you can use the shortcode in the Divi code module and should also be able to use it in the text tab mode.</p>\n"
},
{
"answer_id": 251752,
"author": "Kirk",
"author_id": 110216,
"author_profile": "https://wordpress.stackexchange.com/users/110216",
"pm_score": 1,
"selected": false,
"text": "<p>I figured it out.I rearranged the HTML and used variables so there was no break in the code. I also removed</p>\n\n<pre><code>esc_attr_e( 'Select:', 'textdomain' );\n</code></pre>\n\n<p>Because it was causing the results to appear outside the DIV the shortcode was put in.</p>\n\n<pre><code>function searchbar_function() {//Creates shortcode [searchbar]\n$MainCategories = get_categories( array(\n 'orderby' => 'name',\n 'parent' => 0\n) );//Grabs just the parent categories\n$CodeResult.='<form action=\"action_page.php\">';\n\nforeach ( $MainCategories as $MainCategory ) {\n $MainCatID=esc_html($MainCategory->term_id);//Gets Main Category ID\n if($MainCatID!=='1' && $MainCatID!=='153'){//Exclude Uncategorized or Featured from Main Category List\n $MainCatURL=esc_url( get_category_link( $MainCategory->term_id ) );//Gets Main Category URL\n $MainCatName=esc_html( $MainCategory->name );//Gets Main Category Name\n $MainCatSlug=esc_html( $MainCategory->slug );//Gets Main Category Slug\n $MainCatCount=esc_html( $MainCategory->category_count );\n $MainCat='<label>'.$MainCatName.'</label>';\n $MainCatCode='<option value=\"'.$MainCatSlug.'\">ALL '.$MainCatName.'</option>';\n $CodeResult.=$MainCat;\n $SelectCode='<select name=\"'.$MainCatSlug.'-dropdown\"><option value=\"\">Select:</option>';\n $CodeResult.=$SelectCode;\n $CodeResult.=$MainCatCode;//Makes Main Category first choice\n $categories = get_categories( array( 'child_of' => $MainCatID ) );//Number is the Main Category ID \n foreach ( $categories as $category ) {\n $SubCatValueName= esc_attr($category->category_nicename);\n $SubCatValue= esc_attr( '/category/archives/' . $category->category_nicename );\n $SubCatName=esc_html( $category->cat_name );\n $SubCatCount=esc_html( $category->category_count );\n $SubCatOption ='<option value=\"'.$SubCatValueName.'\">'.$SubCatName.'</option>';\n $CodeResult.=$SubCatOption;\n }\n $CodeResult.='</select>';\n }\n}\n$SubmitEnd='<input type=\"submit\" value=\"Search\">\n </form>';\n$CodeResult.=$SubmitEnd;\n return $CodeResult;\n}\nadd_shortcode( 'searchbar', 'searchbar_function' );\n</code></pre>\n"
},
{
"answer_id": 251801,
"author": "Thinkerman",
"author_id": 110469,
"author_profile": "https://wordpress.stackexchange.com/users/110469",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code>ob_start()</code> before starting your shortcode codes and right after the shortcode codes use something like</p>\n\n<pre><code>$my_clean_ob = ob_get_clean();\nreturn $my_clean_ob;\n</code></pre>\n\n<p>Hope it helps. </p>\n"
}
] |
2017/01/08
|
[
"https://wordpress.stackexchange.com/questions/251702",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101743/"
] |
In my single wordpress posts I want to apply a padding of 100px to the left and right. The problem is that when I apply it to .single .post-content the images also get a padding. However, I want all of the images on the posts pages to be set to 100%. Is there a way to separate the actual body text and the images? This seems like a fairly simple question. But I can't figure it out. Any help is appreciated.
single.php
```html
<?php
get_header();
if (have_posts()) :
while (have_posts()) : the_post(); ?>
<article class="post">
<?php $featuredImage = wp_get_attachment_url( get_post_thumbnail_id($post->ID), 'full' ); ?>
<div class="banner" style="background:url(<?php echo $featuredImage; ?>) no-repeat;"></div>
<?php wpb_set_post_views(get_the_ID()); ?>
<div class="post-info">
<h1 class="post-title"><?php the_title(); ?></h1>
<h2 class="post-date"><?php echo strip_tags(get_the_term_list( $post->ID, 'location', 'Location: ', ', ', ' • ' ));?><?php the_date('F m, Y'); ?></h2>
</div>
<div class="post-content"><?php the_content(); ?></div>
<div id="wrapper-footer"><div class="post-footer"><h1 class="post-footer-comment"><?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'post-footer-comment-count', 'none'); ?></h1><div class="share"><span>share</span> <?php get_template_part( 'share-buttons-post' ); ?></div></div>
<div class="post-footer-bloglovin"><h1>never miss a post</h1><h2><a href="#">follow on email'</a></h2></div></div>
<?php get_template_part( 'prevandnextpost' ); ?>
<?php get_template_part( 'related-posts' ); ?>
<?php comments_template(); ?>
</article>
<?php endwhile;
else :
echo '<p>No content found</p>';
endif;
get_footer();
?>
```
css
```html
.single .post-title,
.post-title a,
.post-title a:link, .post-title a:visited {
font-family: 'Questrial', sans-serif;
font-size:30px;
margin-left:6px;
margin: 0 auto;
color:#000000;
margin-bottom: 3px;
margin-top:30px;
}
.single .post-date {
font-family: 'Questrial', sans-serif;
font-size:13px;
margin-left:6px;
margin: 0 auto;
color:#000000;
}
.single .post-content {
text-decoration: none;
color: #000000;
display: block;
font-family: 'Crimson Text', serif;
font-size: 18px;
margin:0 auto;
margin-top: -50px;
}
.single .post-info {
background:#ffffff;
padding-left: 100px;
padding-right:100px;
max-width: 1865px;
background-position:center;
background-clip: content-box;
margin: 0 auto;
height:110px;
bottom:100px;
position: relative;
}
.single img {
max-width:100%;
padding: 0 0 0 0 !important;
height:auto;
}
```
|
Even with the missing open php tag, this won't work the way you're trying to do it. The Divi code module accepts html code and PHP shortcodes. I haven't tried javascript, so not sure about that.
You'll need to integrate your code as a stand alone plugin. After that, you can use the shortcode in the Divi code module and should also be able to use it in the text tab mode.
|
251,719 |
<p>Is it possible to install WordPress on a public server that doesn't have a domain name configured yet? I thought I'd set it up on IP-only, and had the line <code>server_name _;</code> in my Nginx configuration. I think it's because of this that the WordPress installation dies at <code>wp-admin/install.php?step=2</code> and I see the following error in the Nginx logs:</p>
<pre><code>2017/01/08 07:24:53 [error] 25686#25686: *22 FastCGI sent in stderr: "PHP message: PHP Fatal error: Uncaught phpmailerException: Invalid address: wordpress@_ in /home/ankush/wp_main_site/wp-includes/class-phpmailer.php:946
Stack trace:
#0 /home/ankush/wp_main_site/wp-includes/pluggable.php(352): PHPMailer->setFrom('wordpress@_', 'WordPress', false)
#1 /home/ankush/wp_main_site/wp-admin/includes/upgrade.php(395): wp_mail('dkasolutions.sa...', 'New WordPress S...', 'Your new WordPr...')
</code></pre>
<p>Is a domain name a must or am I doing something wrong?</p>
|
[
{
"answer_id": 251720,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 2,
"selected": true,
"text": "<p>Set <code>server_name</code> to the IP address, eg:</p>\n\n<pre><code>server {\n listen 80;\n server_name 0.1.2.3;\n // other stuff\n}\n</code></pre>\n\n<p>You could also leave it out, because the default in ngninx is an empty string. But then all those pieces in WordPress that don't validate <code>$_SERVER['SERVER_NAME']</code> and similar values … will just break.</p>\n\n<p>See ticket <a href=\"https://core.trac.wordpress.org/ticket/25239\" rel=\"nofollow noreferrer\" title=\"$_SERVER['SERVER_NAME'] not a reliable when generating email host names\">#25239</a> for the progress on this front.</p>\n\n<p>If only WordPress had a <code>Request</code> object, like everyone else. Then it would be easy to prepare all these global values. See <a href=\"https://github.com/symfony/http-foundation/blob/75acea00ecf498cbb65da48916d622dea1edc3e1/Request.php#L335\" rel=\"nofollow noreferrer\">Symfony for an example</a>.</p>\n"
},
{
"answer_id": 251767,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Is it possible to install WordPress on a public server that doesn't have a domain name configured yet? </p>\n</blockquote>\n\n<p>Yes.</p>\n\n<blockquote>\n <p>I thought I'd set it up on IP-only, and had the line server_name _; in my Nginx configuration. </p>\n</blockquote>\n\n<p>You can use server name you like, for instance.</p>\n\n<pre><code>server_name tattarrattat.com;\n</code></pre>\n\n<p>Your WordPress installation can be aware of the server name <code>tattarrattat.com</code>.</p>\n\n<p>On your end you can set inside your <code>/etc/hosts</code> file something like this.</p>\n\n<pre><code>1.2.3.4 tattarrattat.com\n</code></pre>\n\n<p>Where 1.2.3.4 is your server IP address. \nSo even thought you test on a remote server you use the domain you like.</p>\n\n<hr>\n\n<p>You may also use <a href=\"https://www.google.rs/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjY09_X1LXRAhXG1iwKHRedAl4QFggaMAA&url=https%3A%2F%2Fchrome.google.com%2Fwebstore%2Fdetail%2Fvirtual-hosts%2Faiehidpclglccialeifedhajckcpedom%3Fhl%3Den&usg=AFQjCNFHTlFFN02giViPAAn4b8408DjXJg&sig2=srnBD8jOIHig4Y5E-9luwA\" rel=\"nofollow noreferrer\">Virtual Hosts extension</a> in Chrome, when previewing the web site on your end.</p>\n"
}
] |
2017/01/08
|
[
"https://wordpress.stackexchange.com/questions/251719",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57726/"
] |
Is it possible to install WordPress on a public server that doesn't have a domain name configured yet? I thought I'd set it up on IP-only, and had the line `server_name _;` in my Nginx configuration. I think it's because of this that the WordPress installation dies at `wp-admin/install.php?step=2` and I see the following error in the Nginx logs:
```
2017/01/08 07:24:53 [error] 25686#25686: *22 FastCGI sent in stderr: "PHP message: PHP Fatal error: Uncaught phpmailerException: Invalid address: wordpress@_ in /home/ankush/wp_main_site/wp-includes/class-phpmailer.php:946
Stack trace:
#0 /home/ankush/wp_main_site/wp-includes/pluggable.php(352): PHPMailer->setFrom('wordpress@_', 'WordPress', false)
#1 /home/ankush/wp_main_site/wp-admin/includes/upgrade.php(395): wp_mail('dkasolutions.sa...', 'New WordPress S...', 'Your new WordPr...')
```
Is a domain name a must or am I doing something wrong?
|
Set `server_name` to the IP address, eg:
```
server {
listen 80;
server_name 0.1.2.3;
// other stuff
}
```
You could also leave it out, because the default in ngninx is an empty string. But then all those pieces in WordPress that don't validate `$_SERVER['SERVER_NAME']` and similar values … will just break.
See ticket [#25239](https://core.trac.wordpress.org/ticket/25239 "$_SERVER['SERVER_NAME'] not a reliable when generating email host names") for the progress on this front.
If only WordPress had a `Request` object, like everyone else. Then it would be easy to prepare all these global values. See [Symfony for an example](https://github.com/symfony/http-foundation/blob/75acea00ecf498cbb65da48916d622dea1edc3e1/Request.php#L335).
|
251,735 |
<p>I am trying to <a href="https://wordpress.stackexchange.com/questions/56884/how-to-only-hook-on-single-php-after-content">use this method</a> to include a template part (HTML Code) rather than using some plain text. When I use text, it shows correctly below the content with the the_content filter. However, If I try to get_template_part, the content shows at the top of the Wordpress post rather than below the content.</p>
<p>Is there a better way to include/get template parts hooked to the before/after of single content in Wordpress?</p>
<p>Here is the code I am trying with the filter:</p>
<pre><code>function educadme_book_fields_content_hook( $content ) {
if( is_singular('books') ) {
$beforecontent = '';
$aftercontent = get_template_part( 'parts/book', 'fields' );
$fullcontent = $beforecontent . $content . $aftercontent;
return $fullcontent;
}
</code></pre>
<p>Also tried:</p>
<pre><code>$content .= get_template_part( 'parts/book', 'fields' );
return $content;
</code></pre>
<p>Still getting the same issue as all content of the get_template_part are shown above even the title, not just the_content.
Thanks!</p>
|
[
{
"answer_id": 251720,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 2,
"selected": true,
"text": "<p>Set <code>server_name</code> to the IP address, eg:</p>\n\n<pre><code>server {\n listen 80;\n server_name 0.1.2.3;\n // other stuff\n}\n</code></pre>\n\n<p>You could also leave it out, because the default in ngninx is an empty string. But then all those pieces in WordPress that don't validate <code>$_SERVER['SERVER_NAME']</code> and similar values … will just break.</p>\n\n<p>See ticket <a href=\"https://core.trac.wordpress.org/ticket/25239\" rel=\"nofollow noreferrer\" title=\"$_SERVER['SERVER_NAME'] not a reliable when generating email host names\">#25239</a> for the progress on this front.</p>\n\n<p>If only WordPress had a <code>Request</code> object, like everyone else. Then it would be easy to prepare all these global values. See <a href=\"https://github.com/symfony/http-foundation/blob/75acea00ecf498cbb65da48916d622dea1edc3e1/Request.php#L335\" rel=\"nofollow noreferrer\">Symfony for an example</a>.</p>\n"
},
{
"answer_id": 251767,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Is it possible to install WordPress on a public server that doesn't have a domain name configured yet? </p>\n</blockquote>\n\n<p>Yes.</p>\n\n<blockquote>\n <p>I thought I'd set it up on IP-only, and had the line server_name _; in my Nginx configuration. </p>\n</blockquote>\n\n<p>You can use server name you like, for instance.</p>\n\n<pre><code>server_name tattarrattat.com;\n</code></pre>\n\n<p>Your WordPress installation can be aware of the server name <code>tattarrattat.com</code>.</p>\n\n<p>On your end you can set inside your <code>/etc/hosts</code> file something like this.</p>\n\n<pre><code>1.2.3.4 tattarrattat.com\n</code></pre>\n\n<p>Where 1.2.3.4 is your server IP address. \nSo even thought you test on a remote server you use the domain you like.</p>\n\n<hr>\n\n<p>You may also use <a href=\"https://www.google.rs/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjY09_X1LXRAhXG1iwKHRedAl4QFggaMAA&url=https%3A%2F%2Fchrome.google.com%2Fwebstore%2Fdetail%2Fvirtual-hosts%2Faiehidpclglccialeifedhajckcpedom%3Fhl%3Den&usg=AFQjCNFHTlFFN02giViPAAn4b8408DjXJg&sig2=srnBD8jOIHig4Y5E-9luwA\" rel=\"nofollow noreferrer\">Virtual Hosts extension</a> in Chrome, when previewing the web site on your end.</p>\n"
}
] |
2017/01/08
|
[
"https://wordpress.stackexchange.com/questions/251735",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43332/"
] |
I am trying to [use this method](https://wordpress.stackexchange.com/questions/56884/how-to-only-hook-on-single-php-after-content) to include a template part (HTML Code) rather than using some plain text. When I use text, it shows correctly below the content with the the\_content filter. However, If I try to get\_template\_part, the content shows at the top of the Wordpress post rather than below the content.
Is there a better way to include/get template parts hooked to the before/after of single content in Wordpress?
Here is the code I am trying with the filter:
```
function educadme_book_fields_content_hook( $content ) {
if( is_singular('books') ) {
$beforecontent = '';
$aftercontent = get_template_part( 'parts/book', 'fields' );
$fullcontent = $beforecontent . $content . $aftercontent;
return $fullcontent;
}
```
Also tried:
```
$content .= get_template_part( 'parts/book', 'fields' );
return $content;
```
Still getting the same issue as all content of the get\_template\_part are shown above even the title, not just the\_content.
Thanks!
|
Set `server_name` to the IP address, eg:
```
server {
listen 80;
server_name 0.1.2.3;
// other stuff
}
```
You could also leave it out, because the default in ngninx is an empty string. But then all those pieces in WordPress that don't validate `$_SERVER['SERVER_NAME']` and similar values … will just break.
See ticket [#25239](https://core.trac.wordpress.org/ticket/25239 "$_SERVER['SERVER_NAME'] not a reliable when generating email host names") for the progress on this front.
If only WordPress had a `Request` object, like everyone else. Then it would be easy to prepare all these global values. See [Symfony for an example](https://github.com/symfony/http-foundation/blob/75acea00ecf498cbb65da48916d622dea1edc3e1/Request.php#L335).
|
251,746 |
<p>I'd like to get the closest post to today's post; yes, I checked and search this topic and found the code working for me:</p>
<pre><code>date_default_timezone_set("Europe/Warsaw");
setlocale(LC_ALL, en_GB);
$year = strftime('%Y');
$month = strftime('%m');
$day = strftime('%e');
//$hour = strftime('%k');
if($month < 10)
{
$month = substr($month,1);
}
$argsi = array(
'numberposts' => 1,
'post_type' => 'koncerty',
'orderby' => 'date',
'order' => 'ASC',
'date_query' => array(
'after' => array(
'year' => $year,
'month' => $month
),
'inclusive' => 'true'
)
);
$recent_post = wp_get_recent_posts($argsi, ARRAY_A);
</code></pre>
<p>the problem is, when I'm trying to inlude the day to the array</p>
<pre><code>$argsi = array(
'numberposts' => 1,
'post_type' => 'koncerty',
'orderby' => 'date',
'order' => 'ASC',
'date_query' => array(
'after' => array(
'year' => $year,
'month' => $month,
'day' => $day
),
'inclusive' => 'true'
)
);
</code></pre>
<p>the code stopped working and I don't know why. I tried <code>$day = strftime('%d')</code> and then remove 0 in it if day < 10, but still nothing :/</p>
|
[
{
"answer_id": 251720,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 2,
"selected": true,
"text": "<p>Set <code>server_name</code> to the IP address, eg:</p>\n\n<pre><code>server {\n listen 80;\n server_name 0.1.2.3;\n // other stuff\n}\n</code></pre>\n\n<p>You could also leave it out, because the default in ngninx is an empty string. But then all those pieces in WordPress that don't validate <code>$_SERVER['SERVER_NAME']</code> and similar values … will just break.</p>\n\n<p>See ticket <a href=\"https://core.trac.wordpress.org/ticket/25239\" rel=\"nofollow noreferrer\" title=\"$_SERVER['SERVER_NAME'] not a reliable when generating email host names\">#25239</a> for the progress on this front.</p>\n\n<p>If only WordPress had a <code>Request</code> object, like everyone else. Then it would be easy to prepare all these global values. See <a href=\"https://github.com/symfony/http-foundation/blob/75acea00ecf498cbb65da48916d622dea1edc3e1/Request.php#L335\" rel=\"nofollow noreferrer\">Symfony for an example</a>.</p>\n"
},
{
"answer_id": 251767,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Is it possible to install WordPress on a public server that doesn't have a domain name configured yet? </p>\n</blockquote>\n\n<p>Yes.</p>\n\n<blockquote>\n <p>I thought I'd set it up on IP-only, and had the line server_name _; in my Nginx configuration. </p>\n</blockquote>\n\n<p>You can use server name you like, for instance.</p>\n\n<pre><code>server_name tattarrattat.com;\n</code></pre>\n\n<p>Your WordPress installation can be aware of the server name <code>tattarrattat.com</code>.</p>\n\n<p>On your end you can set inside your <code>/etc/hosts</code> file something like this.</p>\n\n<pre><code>1.2.3.4 tattarrattat.com\n</code></pre>\n\n<p>Where 1.2.3.4 is your server IP address. \nSo even thought you test on a remote server you use the domain you like.</p>\n\n<hr>\n\n<p>You may also use <a href=\"https://www.google.rs/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjY09_X1LXRAhXG1iwKHRedAl4QFggaMAA&url=https%3A%2F%2Fchrome.google.com%2Fwebstore%2Fdetail%2Fvirtual-hosts%2Faiehidpclglccialeifedhajckcpedom%3Fhl%3Den&usg=AFQjCNFHTlFFN02giViPAAn4b8408DjXJg&sig2=srnBD8jOIHig4Y5E-9luwA\" rel=\"nofollow noreferrer\">Virtual Hosts extension</a> in Chrome, when previewing the web site on your end.</p>\n"
}
] |
2017/01/08
|
[
"https://wordpress.stackexchange.com/questions/251746",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102644/"
] |
I'd like to get the closest post to today's post; yes, I checked and search this topic and found the code working for me:
```
date_default_timezone_set("Europe/Warsaw");
setlocale(LC_ALL, en_GB);
$year = strftime('%Y');
$month = strftime('%m');
$day = strftime('%e');
//$hour = strftime('%k');
if($month < 10)
{
$month = substr($month,1);
}
$argsi = array(
'numberposts' => 1,
'post_type' => 'koncerty',
'orderby' => 'date',
'order' => 'ASC',
'date_query' => array(
'after' => array(
'year' => $year,
'month' => $month
),
'inclusive' => 'true'
)
);
$recent_post = wp_get_recent_posts($argsi, ARRAY_A);
```
the problem is, when I'm trying to inlude the day to the array
```
$argsi = array(
'numberposts' => 1,
'post_type' => 'koncerty',
'orderby' => 'date',
'order' => 'ASC',
'date_query' => array(
'after' => array(
'year' => $year,
'month' => $month,
'day' => $day
),
'inclusive' => 'true'
)
);
```
the code stopped working and I don't know why. I tried `$day = strftime('%d')` and then remove 0 in it if day < 10, but still nothing :/
|
Set `server_name` to the IP address, eg:
```
server {
listen 80;
server_name 0.1.2.3;
// other stuff
}
```
You could also leave it out, because the default in ngninx is an empty string. But then all those pieces in WordPress that don't validate `$_SERVER['SERVER_NAME']` and similar values … will just break.
See ticket [#25239](https://core.trac.wordpress.org/ticket/25239 "$_SERVER['SERVER_NAME'] not a reliable when generating email host names") for the progress on this front.
If only WordPress had a `Request` object, like everyone else. Then it would be easy to prepare all these global values. See [Symfony for an example](https://github.com/symfony/http-foundation/blob/75acea00ecf498cbb65da48916d622dea1edc3e1/Request.php#L335).
|
251,755 |
<p>I setup a single directory/ multiple sites WordPress Setup. And it worked as well. For some time. It still works but for one problem. The image upload doesn't work properly.</p>
<p>I'll explain.</p>
<p>Setup:-
1. One master directory containing full WordPress installation.
2. One directory for client site - lets say client1.
Here is the full folder structure within public_html </p>
<pre><code>-MasterDirectory
-client1
-wordpress -> MasterDirectory/wordpress
-wp-config.php
-wp-content
-plugins -> MasterDirectory/wordpress/wp-content/plugins
-themes -> MasterDirectory/wordpress/wp-content/themes
-uploads
</code></pre>
<p>3. Master installation wp-config.php edited to only contain</p>
<pre><code>$site_directory = dirname($_SERVER['DOCUMENT_ROOT']);
define('WP_CONTENT_DIR', $site_directory . '/wp-content');
define('WP_CONTENT_URL', 'https://' . $_SERVER['SERVER_NAME'] . '/wp-content');
// load site-specific configurations
require_once dirname($_SERVER['DOCUMENT_ROOT']) . '/wp-config.php';
</code></pre>
<p>I took advice from <a href="https://jason.pureconcepts.net/2013/04/updated-wordpress-multitenancy/" rel="nofollow noreferrer">here</a>. </p>
<ol start="4">
<li>I created client1/wp-config.php and updated it correctly. </li>
<li>Fired up wordpress and it worked smoothly.</li>
<li>Now when I upload image, it gets uploaded correctly to client1/wp-content/uploads/2017.... However, when I try to load it, it results in 404. Even in media library, no thumbnails are visible (missing images). Funnily, when I click on Edit Image button, the image is visible.</li>
</ol>
<p>Attempted Debugging Till now-
7. Server log shows, that it is trying to look for the image in MasterDirectory/wordpress/wp-content/uploads/2017/.... instead of client1/wp-content/uploads/2017/....
8. I tested to check what are the wordpress values by checking the contents of <code>wp_upload_dir();</code>. All expected values are returned.</p>
<pre><code>path=public_html/client1/wp-content/uploads/2017/01
url=https://example.com/wp-content/uploads/2017/01
subdir=/2017/01 </br>basedir=public_html/client1/wp-content/uploads
baseurl=https://example.com/wp-content/uploads
error=
</code></pre>
<p>I have spent the entire sunday trying to figure out the anomaly but can't find the problem as to why is server looking for image in MasterDirectory when the wordpress variables/ constants are correctly set.</p>
<p>Site is using default twentyseventeen theme through child theme. No plugins activated whatsoever, although quite a few are placed in plugins folder. Theme </p>
<p>The question is lengthy, as I tried to explain the maximum.</p>
<p>Thanks for your time people.</p>
|
[
{
"answer_id": 251720,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 2,
"selected": true,
"text": "<p>Set <code>server_name</code> to the IP address, eg:</p>\n\n<pre><code>server {\n listen 80;\n server_name 0.1.2.3;\n // other stuff\n}\n</code></pre>\n\n<p>You could also leave it out, because the default in ngninx is an empty string. But then all those pieces in WordPress that don't validate <code>$_SERVER['SERVER_NAME']</code> and similar values … will just break.</p>\n\n<p>See ticket <a href=\"https://core.trac.wordpress.org/ticket/25239\" rel=\"nofollow noreferrer\" title=\"$_SERVER['SERVER_NAME'] not a reliable when generating email host names\">#25239</a> for the progress on this front.</p>\n\n<p>If only WordPress had a <code>Request</code> object, like everyone else. Then it would be easy to prepare all these global values. See <a href=\"https://github.com/symfony/http-foundation/blob/75acea00ecf498cbb65da48916d622dea1edc3e1/Request.php#L335\" rel=\"nofollow noreferrer\">Symfony for an example</a>.</p>\n"
},
{
"answer_id": 251767,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Is it possible to install WordPress on a public server that doesn't have a domain name configured yet? </p>\n</blockquote>\n\n<p>Yes.</p>\n\n<blockquote>\n <p>I thought I'd set it up on IP-only, and had the line server_name _; in my Nginx configuration. </p>\n</blockquote>\n\n<p>You can use server name you like, for instance.</p>\n\n<pre><code>server_name tattarrattat.com;\n</code></pre>\n\n<p>Your WordPress installation can be aware of the server name <code>tattarrattat.com</code>.</p>\n\n<p>On your end you can set inside your <code>/etc/hosts</code> file something like this.</p>\n\n<pre><code>1.2.3.4 tattarrattat.com\n</code></pre>\n\n<p>Where 1.2.3.4 is your server IP address. \nSo even thought you test on a remote server you use the domain you like.</p>\n\n<hr>\n\n<p>You may also use <a href=\"https://www.google.rs/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjY09_X1LXRAhXG1iwKHRedAl4QFggaMAA&url=https%3A%2F%2Fchrome.google.com%2Fwebstore%2Fdetail%2Fvirtual-hosts%2Faiehidpclglccialeifedhajckcpedom%3Fhl%3Den&usg=AFQjCNFHTlFFN02giViPAAn4b8408DjXJg&sig2=srnBD8jOIHig4Y5E-9luwA\" rel=\"nofollow noreferrer\">Virtual Hosts extension</a> in Chrome, when previewing the web site on your end.</p>\n"
}
] |
2017/01/08
|
[
"https://wordpress.stackexchange.com/questions/251755",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106155/"
] |
I setup a single directory/ multiple sites WordPress Setup. And it worked as well. For some time. It still works but for one problem. The image upload doesn't work properly.
I'll explain.
Setup:-
1. One master directory containing full WordPress installation.
2. One directory for client site - lets say client1.
Here is the full folder structure within public\_html
```
-MasterDirectory
-client1
-wordpress -> MasterDirectory/wordpress
-wp-config.php
-wp-content
-plugins -> MasterDirectory/wordpress/wp-content/plugins
-themes -> MasterDirectory/wordpress/wp-content/themes
-uploads
```
3. Master installation wp-config.php edited to only contain
```
$site_directory = dirname($_SERVER['DOCUMENT_ROOT']);
define('WP_CONTENT_DIR', $site_directory . '/wp-content');
define('WP_CONTENT_URL', 'https://' . $_SERVER['SERVER_NAME'] . '/wp-content');
// load site-specific configurations
require_once dirname($_SERVER['DOCUMENT_ROOT']) . '/wp-config.php';
```
I took advice from [here](https://jason.pureconcepts.net/2013/04/updated-wordpress-multitenancy/).
4. I created client1/wp-config.php and updated it correctly.
5. Fired up wordpress and it worked smoothly.
6. Now when I upload image, it gets uploaded correctly to client1/wp-content/uploads/2017.... However, when I try to load it, it results in 404. Even in media library, no thumbnails are visible (missing images). Funnily, when I click on Edit Image button, the image is visible.
Attempted Debugging Till now-
7. Server log shows, that it is trying to look for the image in MasterDirectory/wordpress/wp-content/uploads/2017/.... instead of client1/wp-content/uploads/2017/....
8. I tested to check what are the wordpress values by checking the contents of `wp_upload_dir();`. All expected values are returned.
```
path=public_html/client1/wp-content/uploads/2017/01
url=https://example.com/wp-content/uploads/2017/01
subdir=/2017/01 </br>basedir=public_html/client1/wp-content/uploads
baseurl=https://example.com/wp-content/uploads
error=
```
I have spent the entire sunday trying to figure out the anomaly but can't find the problem as to why is server looking for image in MasterDirectory when the wordpress variables/ constants are correctly set.
Site is using default twentyseventeen theme through child theme. No plugins activated whatsoever, although quite a few are placed in plugins folder. Theme
The question is lengthy, as I tried to explain the maximum.
Thanks for your time people.
|
Set `server_name` to the IP address, eg:
```
server {
listen 80;
server_name 0.1.2.3;
// other stuff
}
```
You could also leave it out, because the default in ngninx is an empty string. But then all those pieces in WordPress that don't validate `$_SERVER['SERVER_NAME']` and similar values … will just break.
See ticket [#25239](https://core.trac.wordpress.org/ticket/25239 "$_SERVER['SERVER_NAME'] not a reliable when generating email host names") for the progress on this front.
If only WordPress had a `Request` object, like everyone else. Then it would be easy to prepare all these global values. See [Symfony for an example](https://github.com/symfony/http-foundation/blob/75acea00ecf498cbb65da48916d622dea1edc3e1/Request.php#L335).
|
251,776 |
<p>I've got some problems with templates in Wordpress (multisite). I've created a file in the root of my child-theme folder (template-test.php) </p>
<pre><code><?php
/**
* Template Name: Test template
*
*/
?>
<?php get_header(); ?>
<?php get_footer(); ?>
</code></pre>
<p>This template is not showing up in the templates dropdown when creating a new page, or editing an existing page. The only thing in the dropdown is the 'default template'.</p>
<p>What I've tried so far:
- Disabling and enabling my theme
- Flush permalinks
- Check permissions of my files
- Check if style.css is in the root of the template folder (it is)</p>
<p>I've tried the same file on another Wordpress installation, and there it works fine. </p>
|
[
{
"answer_id": 251779,
"author": "Levi",
"author_id": 103404,
"author_profile": "https://wordpress.stackexchange.com/users/103404",
"pm_score": 1,
"selected": false,
"text": "<p>Templates can be deactivated by unsetting them from the <code>wp_themes</code> global variable before the template dropdown is loaded. </p>\n\n<p>Run this code on the page to see what templates show up: </p>\n\n<pre><code>global $wp_themes;\n$tema = wp_get_themes();\nprint_r($tema[\"child-theme folder name\"][\"Template Files\"]);\n</code></pre>\n\n<p>If your template does not show up, the parent theme might have unset it from the array. </p>\n\n<p>It might show up, if you run this code in front-end, as the parent theme might only unset it during the load of the admin editor page.</p>\n\n<p>Download the parent theme and search the files for <code>$wp_themes</code> and <code>wp_get_themes();</code> to find the location of that code. </p>\n\n<p>Hopefully they've given you a way to prevent it using a filter, if not you might have to re-add the files in the child theme. \nThis could be helpful: <a href=\"http://www.wpexplorer.com/wordpress-page-templates-plugin/\" rel=\"nofollow noreferrer\">http://www.wpexplorer.com/wordpress-page-templates-plugin/</a> </p>\n"
},
{
"answer_id": 260203,
"author": "jg314",
"author_id": 26202,
"author_profile": "https://wordpress.stackexchange.com/users/26202",
"pm_score": 2,
"selected": false,
"text": "<p>I also had this problem with a site on WordPress Multisite and was able to fix it by following these steps:</p>\n\n<ol>\n<li>Go to <a href=\"http://example.com/wp-admin/network/themes.php\" rel=\"nofollow noreferrer\">http://example.com/wp-admin/network/themes.php</a> (replace example.com with your URL).</li>\n<li>Click the \"Edit\" link under the theme that's causing you issues.</li>\n<li>In the right sidebar click the name of the template file that's not showing up. For example, it might say \"Events Page Template (template_events.php)\".</li>\n<li>Don't make any edits to the file and click the blue \"Update File\" button.</li>\n<li>Refresh the page's edit screen where you're trying to set the template and it should now display in the dropdown.</li>\n</ol>\n\n<p>If this doesn't do the trick for you I'd suggest checking out <a href=\"http://vanseodesign.com/wordpress/wp-page-templates-dropdown/\" rel=\"nofollow noreferrer\">http://vanseodesign.com/wordpress/wp-page-templates-dropdown/</a>. There are some other possible solutions in there.</p>\n\n<p>Good luck.</p>\n"
},
{
"answer_id": 284721,
"author": "Isu",
"author_id": 102934,
"author_profile": "https://wordpress.stackexchange.com/users/102934",
"pm_score": 2,
"selected": false,
"text": "<p>Make sure you have index.php in your main theme. Main theme must have index.php. I have same issue, and this was the case.\nChecked by:</p>\n\n<pre><code>function testate(){\n global $wp_themes;\n $tema = wp_get_theme();\n echo '<pre>';\n print_r($tema);\n die;\n}\n\nadd_action('init', 'testate' );\n</code></pre>\n"
},
{
"answer_id": 286575,
"author": "Jan Żankowski",
"author_id": 82066,
"author_profile": "https://wordpress.stackexchange.com/users/82066",
"pm_score": 5,
"selected": false,
"text": "<p>Just in Wordpress 4.9 there's this bug: <a href=\"https://core.trac.wordpress.org/ticket/42573\" rel=\"noreferrer\">https://core.trac.wordpress.org/ticket/42573</a> causing the template files to only be rescanned once every hour.</p>\n\n<p>To fix (until they release a new WP version with this changed), download the patch on that bug ticket and make the changes from the patch to <code>wp-includes/class-wp-theme.php</code>.</p>\n\n<p>Hope this saves someone the 2 hours I wasted on this..</p>\n"
},
{
"answer_id": 286597,
"author": "brilliantairic",
"author_id": 77587,
"author_profile": "https://wordpress.stackexchange.com/users/77587",
"pm_score": 2,
"selected": false,
"text": "<p>There's a bug in Wordpress 4.9.</p>\n\n<p>I found this temporary plugin super straightforward. I plan on uninstalling it once they fix the bug, but it works great in the meantime!</p>\n\n<p>Plugin: <a href=\"https://github.com/connorlacombe/WP-Clear-File-Cache\" rel=\"nofollow noreferrer\">https://github.com/connorlacombe/WP-Clear-File-Cache</a></p>\n"
},
{
"answer_id": 287263,
"author": "Rohit Savaj",
"author_id": 93150,
"author_profile": "https://wordpress.stackexchange.com/users/93150",
"pm_score": -1,
"selected": false,
"text": "<p>Fix page template not showing in dropdown menu\nplease activate below plugin to fix (instead of changing wordpress core files)</p>\n\n<p>Below is link for download\n<a href=\"https://drive.google.com/file/d/1ycHQGdc_vQtvtfBaznJp1KRsEbcoRwxB/view?usp=sharing\" rel=\"nofollow noreferrer\">https://drive.google.com/file/d/1ycHQGdc_vQtvtfBaznJp1KRsEbcoRwxB/view?usp=sharing</a></p>\n"
},
{
"answer_id": 329455,
"author": "Jason Is My Name",
"author_id": 159876,
"author_profile": "https://wordpress.stackexchange.com/users/159876",
"pm_score": 0,
"selected": false,
"text": "<p>Have you accidentally moved or removed the style.css file from the theme root?</p>\n\n<p>If so, it could be this - recreate the themes style.css to re-enable the template dropdown.</p>\n"
}
] |
2017/01/08
|
[
"https://wordpress.stackexchange.com/questions/251776",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89977/"
] |
I've got some problems with templates in Wordpress (multisite). I've created a file in the root of my child-theme folder (template-test.php)
```
<?php
/**
* Template Name: Test template
*
*/
?>
<?php get_header(); ?>
<?php get_footer(); ?>
```
This template is not showing up in the templates dropdown when creating a new page, or editing an existing page. The only thing in the dropdown is the 'default template'.
What I've tried so far:
- Disabling and enabling my theme
- Flush permalinks
- Check permissions of my files
- Check if style.css is in the root of the template folder (it is)
I've tried the same file on another Wordpress installation, and there it works fine.
|
Just in Wordpress 4.9 there's this bug: <https://core.trac.wordpress.org/ticket/42573> causing the template files to only be rescanned once every hour.
To fix (until they release a new WP version with this changed), download the patch on that bug ticket and make the changes from the patch to `wp-includes/class-wp-theme.php`.
Hope this saves someone the 2 hours I wasted on this..
|
251,789 |
<p>I prevent WordPress from generating <code>thumbnail</code>, <code>medium</code>, and <code>large</code> image sizes for images I upload to the Media Library, by setting their dimensions to <code>0</code> from the dashboard: <code>Settings -> Media</code> panel.</p>
<p>I have also gotten rid of all instances of <code>add_image_size</code> and <code>set_post_thumbnail_size</code> from the <code>functions.php</code> file of my theme.</p>
<p>However, when I upload new images, WordPress is still generating a <code>768px</code> width version (called 'medium_large') from my original full size image. I believe it has something to do with <a href="https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/" rel="nofollow noreferrer">this update</a>.</p>
<p>Is there is any way to prevent this from happening?</p>
|
[
{
"answer_id": 251810,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": false,
"text": "<p>To remove the <code>medium_large</code> image size you can try to remove it with the <a href=\"https://developer.wordpress.org/reference/hooks/intermediate_image_sizes/\" rel=\"noreferrer\"><code>intermediate_image_sizes</code></a> filter:</p>\n\n<pre><code>add_filter( 'intermediate_image_sizes', function( $sizes )\n{\n return array_filter( $sizes, function( $val )\n {\n return 'medium_large' !== $val; // Filter out 'medium_large'\n } );\n} );\n</code></pre>\n\n<p>Not sure if you're trying to remove all the intermediate sizes, but then you could try out:</p>\n\n<pre><code>add_filter( 'intermediate_image_sizes', '__return_empty_array', 999 );\n</code></pre>\n\n<p>where <a href=\"https://developer.wordpress.org/reference/functions/__return_empty_array/\" rel=\"noreferrer\"><code>__return_empty_array</code>()`</a> is a built-in core function.</p>\n\n<p>We should note that it's not possible to remove it with</p>\n\n<pre><code>remove_image_size( 'medium_large' );\n</code></pre>\n\n<p>because it's not added with <code>add_image_size()</code> and therefore not part of the <code>$_wp_additional_image_sizes</code> global array or <code>wp_get_additional_image_sizes()</code>;</p>\n"
},
{
"answer_id": 270626,
"author": "Sil2",
"author_id": 122141,
"author_profile": "https://wordpress.stackexchange.com/users/122141",
"pm_score": 2,
"selected": false,
"text": "<p>this will work</p>\n\n<pre><code>\nfunction paulund_remove_default_image_sizes( $sizes) {\n unset( $sizes['medium_large']);\n return $sizes;\n}\nadd_filter('intermediate_image_sizes_advanced','paulund_remove_default_image_sizes');\n\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/intermediate_image_sizes_advanced/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/intermediate_image_sizes_advanced/</a></p>\n"
},
{
"answer_id": 305331,
"author": "Dima Stefantsov",
"author_id": 76002,
"author_profile": "https://wordpress.stackexchange.com/users/76002",
"pm_score": 3,
"selected": false,
"text": "<p>Remove image size the same way wordpress core code does it:</p>\n\n<pre><code>add_filter('intermediate_image_sizes', function($sizes) {\n return array_diff($sizes, ['medium_large']);\n});\n</code></pre>\n\n<p>Keep in mind that <code>medium_large</code> is generally a good size to have in <code>srcset</code>, only remove it if you have understanding how <code>srcset</code> works, if you have similar sizes there already.</p>\n"
}
] |
2017/01/09
|
[
"https://wordpress.stackexchange.com/questions/251789",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110512/"
] |
I prevent WordPress from generating `thumbnail`, `medium`, and `large` image sizes for images I upload to the Media Library, by setting their dimensions to `0` from the dashboard: `Settings -> Media` panel.
I have also gotten rid of all instances of `add_image_size` and `set_post_thumbnail_size` from the `functions.php` file of my theme.
However, when I upload new images, WordPress is still generating a `768px` width version (called 'medium\_large') from my original full size image. I believe it has something to do with [this update](https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/).
Is there is any way to prevent this from happening?
|
To remove the `medium_large` image size you can try to remove it with the [`intermediate_image_sizes`](https://developer.wordpress.org/reference/hooks/intermediate_image_sizes/) filter:
```
add_filter( 'intermediate_image_sizes', function( $sizes )
{
return array_filter( $sizes, function( $val )
{
return 'medium_large' !== $val; // Filter out 'medium_large'
} );
} );
```
Not sure if you're trying to remove all the intermediate sizes, but then you could try out:
```
add_filter( 'intermediate_image_sizes', '__return_empty_array', 999 );
```
where [`__return_empty_array`()`](https://developer.wordpress.org/reference/functions/__return_empty_array/) is a built-in core function.
We should note that it's not possible to remove it with
```
remove_image_size( 'medium_large' );
```
because it's not added with `add_image_size()` and therefore not part of the `$_wp_additional_image_sizes` global array or `wp_get_additional_image_sizes()`;
|
251,825 |
<p>Strangely I don't find much sources on the web talking about my desires. So I hope it is a trivial thing I'm asking (although I fear it's not and Wordpress is just..).</p>
<p>Naturally I need custom fields in my custom post types.</p>
<p>Wordpress' native way of handling custom fields is very inconvenient and I can't expect my clients to deal with these dropdowns, adding fields as they need it–</p>
<p>So far I manage my custom fields with the "Advanced Custom Fields" plugin.</p>
<p>I wanna understand how to do this on my own and therefore hope for more flexibility in customizing the work area / admin area of the "new post" and "edit post" pages.</p>
<p>There must be a way to set custom fields in code and influence how the inputs are accessible on the admin page.</p>
<p>Providing a simple example, I want to add a quicklink-feature to the page, where the admin can add posts containing nothing but a title and a url (I'm aware of the native "Links" area and purposely avoid using it)</p>
<p>So far I made a simple one-file-plugin containing the declaration for the custom post type:</p>
<pre><code><?php
/*
Plugin Name: Got Nexxt Quicklinks
Plugin URI: none
Description: Quicklinks custom post type + special admin area
Author: René Eschke
Version: 1.0
Author URI: http://www.eschke.info/
*/
function my_custom_post_quicklinks() {
$labels = array(
'name' => _x( 'Quicklinks', 'post type general name' ),
'singular_name' => _x( 'Quicklink', 'post type singular name' ),
'add_new' => _x( 'Hinzuf&uuml;gen', 'book' ),
'add_new_item' => __( 'Quicklink hinzuf&uuml;gen' ),
'edit_item' => __( 'Quicklink bearbeiten' ),
'new_item' => __( 'Neue Quicklink' ),
'all_items' => __( 'Alle Quicklinks' ),
'view_item' => __( 'Quicklink ansehen' ),
'search_items' => __( 'Quicklink durchsuchen' ),
'not_found' => __( 'Kein Quicklink gefunden' ),
'not_found_in_trash' => __( 'Keine Quicklinks im Papierkorb gefunden' ),
'parent_item_colon' => '',
'menu_name' => 'Quicklinks'
);
$args = array(
'labels' => $labels,
'menu_icon' => 'dashicons-admin-links',
'description' => 'Quicklinks sind vor allem für Shortcuts zu bestimmten Podcast-positionen da',
'public' => true,
'menu_position' => 5,
'supports' => array('title'),
'has_archive' => false,
);
register_post_type('quicklink', $args);
}
add_action( 'init', 'my_custom_post_quicklinks' );
?>
</code></pre>
<p>Again:
<strong>I want to implement this myself all in code without using a plugin.</strong></p>
<p>Thanks!</p>
<p><a href="https://i.stack.imgur.com/TMcod.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TMcod.png" alt="done with Advanced Custom Fields"></a></p>
|
[
{
"answer_id": 251832,
"author": "LWS-Mo",
"author_id": 88895,
"author_profile": "https://wordpress.stackexchange.com/users/88895",
"pm_score": 2,
"selected": false,
"text": "<p>I think you are looking for \"meta boxes\".</p>\n\n<p>You will work with <code>add_meta_box()</code> to <strong>create</strong> one or multiple new meta-boxes for your post-types. (<a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\">Codex</a>)</p>\n\n<p>You have to set up some <strong>callback function</strong> which holds the HTML of the fields you want to show/display.</p>\n\n<p>And you will also need a function to <strong>save</strong> these fields using <code>add_post_meta()</code> and <code>update_post_meta()</code>. (Codex to <a href=\"https://codex.wordpress.org/Function_Reference/add_post_meta\" rel=\"nofollow noreferrer\">ADD</a> and <a href=\"https://codex.wordpress.org/Function_Reference/update_post_meta\" rel=\"nofollow noreferrer\">UPDATE</a>)</p>\n\n<p>If you want to <strong>remove</strong> some existing meta-boxes you can use <code>remove_meta_box()</code>. (<a href=\"https://codex.wordpress.org/Function_Reference/remove_meta_box\" rel=\"nofollow noreferrer\">Codex</a>)</p>\n\n<hr>\n\n<p><strong>Some Details:</strong></p>\n\n<p>With the following code you can create a new Meta-box on the new/edit screen of your \"quicklinks\" post-type. (cause I entered \"quicklink\" as the post-type)</p>\n\n<pre><code>function create_custom_metabox() {\n add_meta_box( \n 'my_meta', // HTML 'id' attribute of the metabox\n __( 'My Setting', 'textdomain' ), // Title of metabox\n 'my_fields_callback', // Function that prints out the HTML for metabox\n 'quicklink', // The post-type of writing screen on which to show the edit screen section (example 'post' or 'page')\n 'normal', // The part of the page where the metabox should be shown ('normal', 'advanced', or 'side')\n 'high' // The priority within the context where the boxes should show ('high', 'core', 'default' or 'low')\n );\n}\nadd_action( 'add_meta_boxes', 'create_custom_metabox' );\n</code></pre>\n\n<p>After this code you will already see a new Meta-Box, but it will be empty, there are no fields yet to show.</p>\n\n<p>So next we create a new callback function with our new fields: (see function name and callback argument in <code>add_meta_box()</code> above)</p>\n\n<pre><code>function my_fields_callback( $post ) {\n\n // creating a custom nonce\n wp_nonce_field( basename( __FILE__ ), 'my_custom_nonce' );\n\n // see and get if some meta is already saved\n $stored_meta = get_post_meta( $post->ID );\n\n ?>\n <!-- Textfield START -->\n <p>\n <span class=\"my-row-title\">\n <label for=\"meta-text\" class=\"my-row-title\"><?php _e( 'Text', 'textdomain' )?></label>\n </span>\n <div class=\"my-row-content\">\n <input type=\"text\" name=\"meta-text\" id=\"meta-text\" placeholder=\"Text...\" value=\"<?php if ( isset ( $stored_meta['meta-text'] ) ) echo $stored_meta['meta-text'][0]; ?>\" />\n\n </div>\n </p>\n <!-- Textfield END -->\n\n<?php\n}\n</code></pre>\n\n<p>After this code, you will already see a new input field and a label. But if you enter something it will still not get saved! So we need to add a save function to this:</p>\n\n<pre><code>function save_my_meta( $post_id ) {\n\n // Checks save status\n $is_autosave = wp_is_post_autosave( $post_id );\n $is_revision = wp_is_post_revision( $post_id );\n $is_valid_nonce = ( isset( $_POST[ 'my_custom_nonce' ] ) && wp_verify_nonce( $_POST[ 'my_custom_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';\n\n // Exits script depending on save status\n if ( $is_autosave || $is_revision || !$is_valid_nonce ) {\n return;\n }\n\n\n // save our new created field\n if( isset( $_POST[ 'meta-text' ] ) ) {\n // if there is some content in the field, we update it\n update_post_meta( $post_id, 'meta-text', sanitize_text_field( $_POST[ 'meta-text' ] ) );\n }\n\n\n}\nadd_action( 'save_post', 'save_my_meta' );\n</code></pre>\n\n<p>After that we can save the values of your new field.</p>\n\n<p>If you want to show these values you can use the <code>get_post_meta()</code> function. (<a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\">Codex</a>) like this:</p>\n\n<pre><code>$my_meta_value = get_post_meta( get_the_ID(), 'meta-text', true );\n\nif( !empty( $my_meta_value ) ) {\n echo $my_meta_value;\n}\n</code></pre>\n\n<p>So, you see there are several functions needed. There are a lots of tutorials out there, <a href=\"http://themefoundation.com/wordpress-meta-boxes-guide/\" rel=\"nofollow noreferrer\">here is an old one which still functions.</a></p>\n\n<p>I couldnt find one in german in the moment, sorry.</p>\n\n<p>Be also sure to have an eye an sanitize the different values of the fields on saving and retrieving.</p>\n\n<p>I hope this helps!</p>\n\n<hr>\n\n<p><strong>Update:</strong></p>\n\n<p>When you create a meta-box with the <code>add_meta_box()</code> function, you can set where the meta-box should appear with the context parameter...</p>\n\n<pre><code>add_meta_box( \n 'my_meta', \n __( 'My Setting', 'textdomain' ), \n 'my_fields_callback', \n 'quicklink',\n 'normal', // The part of the page where the metabox should be shown ('normal', 'advanced', or 'side')\n 'high'\n );\n</code></pre>\n\n<p>If you choose <strong>side</strong>, the box will be created on the right sidebar.</p>\n\n<p><strong>Regarding ACF and fields without the wrapper container:</strong></p>\n\n<p>It seems when you create an field with ACF without the meta-box-wrapper/container, some elements are just hidden, and some extra styles are added to hide the container!</p>\n\n<p>So I think the best way would be to load some custom css and maybe jQuery, <em>only</em> on the edit/new page of the post-type which has your custom fields.</p>\n\n<pre><code>function add_scripts_and_styles()\n{\n global $typenow;\n if( 'quicklink' != $typenow )\n return; \n\n echo \"\n<script type='text/javascript'>\n jQuery(document).ready( function($) {\n $('#my_meta').removeClass('postbox');\n $('#my_meta h3').hide();\n }); \n</script>\n<style type='text/css'>\n /* CUSTOM RULES */\n</style>\n\";\n}\nadd_action( 'admin_head-post-new.php', 'add_scripts_and_styles' );\nadd_action( 'admin_head-post.php', 'add_scripts_and_styles' );\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/a/17459485/4792216\"><strong>Source: This Stackexchange answer</strong></a></p>\n\n<hr>\n\n<p><strong>Nonces:</strong>\nI try to explain it, but maybe the codex will be clearer to you:</p>\n\n<p>A nonce in the WP envoirnment is a security feature.\nIts a random and unique combination of numbers and letters which is only valid a limited time and also per user.</p>\n\n<p>In this case we are using it in the form to check that the input-data are coming from the genuine user.\nThe system will check the nonce upon saving to see that nobody/something else is trying to save the data. </p>\n\n<p>Or as the codex says it: </p>\n\n<blockquote>\n <p>The nonce field is used to validate that the contents of the form request came from the current site and not somewhere else.</p>\n</blockquote>\n\n<p>You can read <a href=\"https://codex.wordpress.org/WordPress_Nonces\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://codex.wordpress.org/Function_Reference/wp_nonce_field\" rel=\"nofollow noreferrer\">here</a> about nonces.</p>\n"
},
{
"answer_id": 251833,
"author": "janw",
"author_id": 10911,
"author_profile": "https://wordpress.stackexchange.com/users/10911",
"pm_score": 0,
"selected": false,
"text": "<p>What you are looking for is a <em>custom meta box</em></p>\n\n<p>You will need <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes\" rel=\"nofollow noreferrer\">add_meta_box()</a>, take a look.\nAlso here is a nice tutorial which deals with the basics:\n<a href=\"https://www.smashingmagazine.com/2011/10/create-custom-post-meta-boxes-wordpress/\" rel=\"nofollow noreferrer\">https://www.smashingmagazine.com/2011/10/create-custom-post-meta-boxes-wordpress/</a></p>\n"
},
{
"answer_id": 252581,
"author": "kater louis",
"author_id": 102487,
"author_profile": "https://wordpress.stackexchange.com/users/102487",
"pm_score": 1,
"selected": true,
"text": "<p>I found a totally customizable solution.\nThe general approach illustrated by LWS-mo remains the same.\nBut instead of using <code>add_meta_box()</code> I used <strong><code>add_post_meta()</code></strong></p>\n\n<p><code>add_meta_box()</code> requires a callback function that prints out the HTML. Using <code>add_post_meta()</code> a callback has to be hooked in manually.</p>\n\n<p>The key action hook here is <strong><code>edit_form_after_editor</code></strong>. (Actually there are a lot of hooks for the admin-work-area <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request\" rel=\"nofollow noreferrer\" title=\"WP Codex\">> WP Codex</a>)</p>\n\n<hr>\n\n<p>Another important insight I had:\nAll these <strong>changes apply to every post type</strong> unless you return the functions when the post type differs your desired one. Therefore I made a helper-function, which needs to be called first thing in the action hooks.</p>\n\n<p>Furthermore I skipped calling function names in the <code>add_action</code> function and used anonymous functions as parameter. I find this way more convenient; <em>please correct me if I miss something bigger here.</em></p>\n\n<p>Here's the code in short version:</p>\n\n<pre><code>// helper function to prevent editing other post types than desired\nfunction is_my_posttype() {\n global $post;\n if ($post->post_type == \"my_custom_posttype\") return true;\n else return false;\n}\n\n// create custom post type\nadd_action(\"init\", function() {\n $labels = ... \n $args = ...\n register_post_type(\"my_custom_posttype\", $args); \n});\n\n// add custom fields \nadd_action(\"add_meta_boxes\", function() {\n if (!is_my_posttype()) return;\n add_post_meta($post->ID, \"url\", \"\", true); // true creates a unique custom field; no initial value needed\n add_post_meta(...)\n // create as many as you need\n});\n\n// insert the html in both ADD and EDIT forms\n// $post parameter required\nadd_action(\"edit_form_after_editor\", function( $post ) {\n if (!is_my_posttype()) return;\n\n wp_nonce_field( basename( __FILE__ ), 'my_custom_nonce' ); // to check for later in save function \n\n $stored_meta = get_post_meta( $post->ID );\n\n // now do whatever magic you want; \n // it gets inserted straight below the editor\n // without any wrapping html cage\n ?> \n <label ...>Some Label</label>\n <input type=\"text\" name=\"url\" value=\"<?php if (isset($stored_meta[\"url\"])) echo $stored_meta[\"url\"][0]; ?>\" />\n Add even more\n <?php\n});\n\n// make the custom fields savable \nadd_action(\"save_post\", function( $post_id )) {\n if (!is_my_posttype()) return;\n\n // Checks save status\n $is_autosave = wp_is_post_autosave( $post_id );\n $is_revision = wp_is_post_revision( $post_id );\n $is_valid_nonce = ( isset( $_POST[ 'my_custom_nonce' ] ) && wp_verify_nonce( $_POST[ 'my_custom_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';\n\n // Exits script depending on save status\n if ( $is_autosave || $is_revision || !$is_valid_nonce ) {\n return;\n }\n\n update_post_meta($post_id, \"url\", $_POST[\"url\"]);\n update_post_meta( ... )\n // update all the other post metas \n\n});\n</code></pre>\n"
}
] |
2017/01/09
|
[
"https://wordpress.stackexchange.com/questions/251825",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102487/"
] |
Strangely I don't find much sources on the web talking about my desires. So I hope it is a trivial thing I'm asking (although I fear it's not and Wordpress is just..).
Naturally I need custom fields in my custom post types.
Wordpress' native way of handling custom fields is very inconvenient and I can't expect my clients to deal with these dropdowns, adding fields as they need it–
So far I manage my custom fields with the "Advanced Custom Fields" plugin.
I wanna understand how to do this on my own and therefore hope for more flexibility in customizing the work area / admin area of the "new post" and "edit post" pages.
There must be a way to set custom fields in code and influence how the inputs are accessible on the admin page.
Providing a simple example, I want to add a quicklink-feature to the page, where the admin can add posts containing nothing but a title and a url (I'm aware of the native "Links" area and purposely avoid using it)
So far I made a simple one-file-plugin containing the declaration for the custom post type:
```
<?php
/*
Plugin Name: Got Nexxt Quicklinks
Plugin URI: none
Description: Quicklinks custom post type + special admin area
Author: René Eschke
Version: 1.0
Author URI: http://www.eschke.info/
*/
function my_custom_post_quicklinks() {
$labels = array(
'name' => _x( 'Quicklinks', 'post type general name' ),
'singular_name' => _x( 'Quicklink', 'post type singular name' ),
'add_new' => _x( 'Hinzufügen', 'book' ),
'add_new_item' => __( 'Quicklink hinzufügen' ),
'edit_item' => __( 'Quicklink bearbeiten' ),
'new_item' => __( 'Neue Quicklink' ),
'all_items' => __( 'Alle Quicklinks' ),
'view_item' => __( 'Quicklink ansehen' ),
'search_items' => __( 'Quicklink durchsuchen' ),
'not_found' => __( 'Kein Quicklink gefunden' ),
'not_found_in_trash' => __( 'Keine Quicklinks im Papierkorb gefunden' ),
'parent_item_colon' => '',
'menu_name' => 'Quicklinks'
);
$args = array(
'labels' => $labels,
'menu_icon' => 'dashicons-admin-links',
'description' => 'Quicklinks sind vor allem für Shortcuts zu bestimmten Podcast-positionen da',
'public' => true,
'menu_position' => 5,
'supports' => array('title'),
'has_archive' => false,
);
register_post_type('quicklink', $args);
}
add_action( 'init', 'my_custom_post_quicklinks' );
?>
```
Again:
**I want to implement this myself all in code without using a plugin.**
Thanks!
[](https://i.stack.imgur.com/TMcod.png)
|
I found a totally customizable solution.
The general approach illustrated by LWS-mo remains the same.
But instead of using `add_meta_box()` I used **`add_post_meta()`**
`add_meta_box()` requires a callback function that prints out the HTML. Using `add_post_meta()` a callback has to be hooked in manually.
The key action hook here is **`edit_form_after_editor`**. (Actually there are a lot of hooks for the admin-work-area [> WP Codex](https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request "WP Codex"))
---
Another important insight I had:
All these **changes apply to every post type** unless you return the functions when the post type differs your desired one. Therefore I made a helper-function, which needs to be called first thing in the action hooks.
Furthermore I skipped calling function names in the `add_action` function and used anonymous functions as parameter. I find this way more convenient; *please correct me if I miss something bigger here.*
Here's the code in short version:
```
// helper function to prevent editing other post types than desired
function is_my_posttype() {
global $post;
if ($post->post_type == "my_custom_posttype") return true;
else return false;
}
// create custom post type
add_action("init", function() {
$labels = ...
$args = ...
register_post_type("my_custom_posttype", $args);
});
// add custom fields
add_action("add_meta_boxes", function() {
if (!is_my_posttype()) return;
add_post_meta($post->ID, "url", "", true); // true creates a unique custom field; no initial value needed
add_post_meta(...)
// create as many as you need
});
// insert the html in both ADD and EDIT forms
// $post parameter required
add_action("edit_form_after_editor", function( $post ) {
if (!is_my_posttype()) return;
wp_nonce_field( basename( __FILE__ ), 'my_custom_nonce' ); // to check for later in save function
$stored_meta = get_post_meta( $post->ID );
// now do whatever magic you want;
// it gets inserted straight below the editor
// without any wrapping html cage
?>
<label ...>Some Label</label>
<input type="text" name="url" value="<?php if (isset($stored_meta["url"])) echo $stored_meta["url"][0]; ?>" />
Add even more
<?php
});
// make the custom fields savable
add_action("save_post", function( $post_id )) {
if (!is_my_posttype()) return;
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'my_custom_nonce' ] ) && wp_verify_nonce( $_POST[ 'my_custom_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
update_post_meta($post_id, "url", $_POST["url"]);
update_post_meta( ... )
// update all the other post metas
});
```
|
251,841 |
<p>I'm using PHP handlebars templates and would like to keep all of the HTML in the template file so I don't have a header.php but rather the handlebars looks like </p>
<pre><code><html>
<head>
{{#wpHead}}
</head>
</code></pre>
<p>where wpHead is a helper that has nothing but <code>wp_head();</code> but the output comes first before the <code><html></code> tag. I'm thinking I'll have to use output buffering to store it as a string... Is that the only/best way? </p>
<p>The plan with the string is to add it to the data array that is passed to the handlebars render function:</p>
<pre><code>global $post;
$data = array(
'wpHead' => get_wp_head_as_string(),
'postContent' => $post->post_content,
'postContentFiltered' => apply_filters( 'the_content', $post->post_content )
);
render( 'default', $data );
</code></pre>
<p>And then just output it directly in the template instead of with a helper:</p>
<pre><code><html>
<head>
<!-- other head stuff -->
{{{wpHead}}} <!-- wp head output -->
</head>
<body>
{{{postContentFiltered}}}
</body>
</code></pre>
<p></p>
|
[
{
"answer_id": 251889,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": false,
"text": "<p>You can use PHP's output buffering. WIth this you can write a wrapper for the <strong><code>get_head()</code></strong> function</p>\n\n<pre><code>function wpse251841_wp_head() {\n ob_start();\n wp_head();\n return ob_get_clean();\n}\n</code></pre>\n\n<p>You can then use this as</p>\n\n<pre><code>$data = array(\n 'wpHead' => wpse251841_wp_head(),\n 'postContent' => $post->post_content,\n 'postContentFiltered' => apply_filters( 'the_content', $post->post_content )\n);\n</code></pre>\n\n<p><strong>Reference: <a href=\"http://php.net/manual/en/ref.outcontrol.php\" rel=\"nofollow noreferrer\">Output Control Functions</a></strong></p>\n"
},
{
"answer_id": 389102,
"author": "tsdexter",
"author_id": 31352,
"author_profile": "https://wordpress.stackexchange.com/users/31352",
"pm_score": 1,
"selected": true,
"text": "<p>Thanks to @Tunji's answer, I accomplished this with a more generic function:</p>\n<pre><code> /**\n * Use output buffering to convert a function that echoes\n * to a return string instead\n */\n function echo_to_string( $function )\n {\n ob_start();\n call_user_func( $function );\n $html = ob_get_contents();\n ob_end_clean();\n return $html;\n }\n</code></pre>\n<p>Then it can be used like this:</p>\n<pre><code>$data->wpHead = echo_to_string( 'wp_head' );\n</code></pre>\n"
}
] |
2017/01/09
|
[
"https://wordpress.stackexchange.com/questions/251841",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31352/"
] |
I'm using PHP handlebars templates and would like to keep all of the HTML in the template file so I don't have a header.php but rather the handlebars looks like
```
<html>
<head>
{{#wpHead}}
</head>
```
where wpHead is a helper that has nothing but `wp_head();` but the output comes first before the `<html>` tag. I'm thinking I'll have to use output buffering to store it as a string... Is that the only/best way?
The plan with the string is to add it to the data array that is passed to the handlebars render function:
```
global $post;
$data = array(
'wpHead' => get_wp_head_as_string(),
'postContent' => $post->post_content,
'postContentFiltered' => apply_filters( 'the_content', $post->post_content )
);
render( 'default', $data );
```
And then just output it directly in the template instead of with a helper:
```
<html>
<head>
<!-- other head stuff -->
{{{wpHead}}} <!-- wp head output -->
</head>
<body>
{{{postContentFiltered}}}
</body>
```
|
Thanks to @Tunji's answer, I accomplished this with a more generic function:
```
/**
* Use output buffering to convert a function that echoes
* to a return string instead
*/
function echo_to_string( $function )
{
ob_start();
call_user_func( $function );
$html = ob_get_contents();
ob_end_clean();
return $html;
}
```
Then it can be used like this:
```
$data->wpHead = echo_to_string( 'wp_head' );
```
|
251,865 |
<p>Is there a way to append Javascript to the body in the script tag without using a file?
Normally you would do it with </p>
<pre><code>wp_enqueue_script('name', 'path/to/js/file');
</code></pre>
<p>Is there a way to include js in the script tag directly?<br>
Like:</p>
<pre><code><script>My awesome code </script>
</code></pre>
|
[
{
"answer_id": 251873,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, you can directly insert what you want in the header or the footer using the action <a href=\"https://codex.wordpress.org/Function_Reference/wp_head\" rel=\"nofollow noreferrer\"><code>wp_head</code></a> or <code>wp_footer</code></p>\n\n<pre><code>add_action('wp_head', 'custom_script');\n\nfunction custom_script(){\n ?>\n <script>My awesome code </script>\n <?php\n\n}\n</code></pre>\n\n<p>You only have to put this in functions.php of your child theme</p>\n"
},
{
"answer_id": 251874,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": false,
"text": "<p>Check <a href=\"https://wordpress.org/plugins/hello-dolly/\" rel=\"nofollow noreferrer\">Hello Dolly plugin</a> that comes with WordPress;</p>\n\n<pre><code>// File: wp-content/plugins/hello.php\n// We need some CSS to position the paragraph\nfunction dolly_css() {\n // This makes sure that the positioning is also good for right-to-left languages\n $x = is_rtl() ? 'left' : 'right';\n\n echo \"\n <style type='text/css'>\n #dolly {\n float: $x;\n padding-$x: 15px;\n padding-top: 5px; \n margin: 0;\n font-size: 11px;\n }\n </style>\n \";\n}\nadd_action( 'admin_head', 'dolly_css' );\n</code></pre>\n\n<p>Like @benoti mentioned use <code>wp_head</code> hook in you don't need the admin side:</p>\n\n<pre><code>add_action('wp_head', 'function_callback' );\n</code></pre>\n\n<p>BTW, this plugins appends styles and the same works for scripts.</p>\n"
}
] |
2017/01/09
|
[
"https://wordpress.stackexchange.com/questions/251865",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102247/"
] |
Is there a way to append Javascript to the body in the script tag without using a file?
Normally you would do it with
```
wp_enqueue_script('name', 'path/to/js/file');
```
Is there a way to include js in the script tag directly?
Like:
```
<script>My awesome code </script>
```
|
Yes, you can directly insert what you want in the header or the footer using the action [`wp_head`](https://codex.wordpress.org/Function_Reference/wp_head) or `wp_footer`
```
add_action('wp_head', 'custom_script');
function custom_script(){
?>
<script>My awesome code </script>
<?php
}
```
You only have to put this in functions.php of your child theme
|
251,866 |
<p>I'm building a custom carousel for a client. I've got a function which gets blocks of three images from all of the images attached to a post:</p>
<pre><code>global $rental;
$images = get_children( array(
'post_parent' => $rental_id,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID'
) );
$array = $images;
$number_of_elements = 3;
$count = count( $array );
$split = array();
for ( $i = 0; $i <= $count - 1; $i++ ) {
$slices = array_slice( $array, $i , $number_of_elements);
if ( count( $slices ) != $number_of_elements )
break;
$split[] = $slices;
}
if ($split) :
foreach ($split as $outeritem) :
echo '<div class="Outer Top">';
foreach ($split as $inneritem) :
echo '<div class="Inner Top">';
echo '<img src="' . $inneritem . '">';
echo '</div>';
endforeach;
echo '</div>';
endforeach;
endif;
//print_r( $split );
</code></pre>
<p>All I need to finalize this is to replace <code>inneritem</code> with the URL of the image. The data is all there in an array, and as you can see I just need to pull the value of <em>guid</em> for each item. The array below comes from uncommenting the <code>print_r( $split );</code> and I've removed all the extraneous data for the sake of tidiness:</p>
<pre><code>Array (
[0] => Array (
[0] => WP_Post Object (
[ID] => 120
[guid] => http://******/wp-content/uploads/2016/12/T15923-11-1-1.jpg
)
[1] => WP_Post Object (
[ID] => 121
[guid] => http://******/wp-content/uploads/2016/12/T15923-12-1-1.jpg
)
[2] => WP_Post Object (
[ID] => 122
[guid] => http://******/wp-content/uploads/2016/12/T15898.jpg
)
)
[1] => Array (
[0] => WP_Post Object (
[ID] => 121
[guid] => http://******/wp-content/uploads/2016/12/T15923-12-1-1.jpg
)
[1] => WP_Post Object (
[ID] => 122
[guid] => http://******/wp-content/uploads/2016/12/T15898.jpg
)
[2] => WP_Post Object (
[ID] => 123
[guid] => http://******/wp-content/uploads/2016/12/T15923-13-1-1.jpg
)
)
[2] => Array (
[0] => WP_Post Object (
[ID] => 122
[guid] => http://******/wp-content/uploads/2016/12/T15898.jpg
)
[1] => WP_Post Object (
[ID] => 123
[guid] => http://******/wp-content/uploads/2016/12/T15923-13-1-1.jpg
)
[2] => WP_Post Object (
[ID] => 124
[guid] => http://******/wp-content/uploads/2016/12/T15923-14-1.jpg
)
)
)
</code></pre>
|
[
{
"answer_id": 251871,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": true,
"text": "<p>You should be able to rewrite what you have about and also use <a href=\"https://developer.wordpress.org/reference/functions/get_permalink/\" rel=\"nofollow noreferrer\"><strong><code>get_permalink</code></strong></a> as <a href=\"https://wordpress.stackexchange.com/users/58141/benoti\">@Benoti</a> stated while omitting the <code>$split</code> array.</p>\n\n<blockquote>\n <p><a href=\"https://developer.wordpress.org/reference/functions/get_permalink/\" rel=\"nofollow noreferrer\"><strong><code>get_permalink</code></strong></a> accepts either the Post ID or a post object.</p>\n</blockquote>\n\n<pre><code>global $rental;\n\n$images = get_children( array(\n 'post_parent' => $rental_id,\n 'post_status' => 'inherit',\n 'post_type' => 'attachment',\n 'post_mime_type' => 'image',\n 'order' => 'ASC',\n 'orderby' => 'menu_order ID'\n) );\n\n$array = $images;\n$number_of_elements = 3;\n$count = count( $array );\n\nfor ( $i = 0; $i <= $count - 1; $i++ ) {\n $slices = array_slice( $array, $i , $number_of_elements);\n if ( count( $slices ) != $number_of_elements )\n break;\n\n echo \"<div class='Outer Top'>\";\n foreach( $slices as $inneritem ) {\n $link = wp_get_attachment_url( $inneritem->ID );\n echo \"<div class='Inner Top'>\";\n echo \"<img src=' $link '>\";\n echo \"</div>\";\n }\n echo \"</div>\";\n}\n</code></pre>\n"
},
{
"answer_id": 251872,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 2,
"selected": false,
"text": "<p>I didn't test anything and read your code, but it seems that you can get_permalink() as I was told in the comment but it's true that you will get the attachment page not its url.</p>\n\n<p>You can access to the object ID, guid easily</p>\n\n<pre><code>wp_get_attachment_url($inneritem[$i]->ID);\n</code></pre>\n\n<p>So </p>\n\n<pre><code>if ($split) :\nforeach ($split as $outeritem) : \n echo '<div class=\"Outer Top\">';\n $i=0;\n foreach ($split as $inneritem) :\n echo '<div class=\"Inner Top\">';\n echo '<img src=\"' . wp_get_attachment_url($inneritem[$i]->ID) . '\">';\n echo '</div>';\n $i++;\n endforeach;\n echo '</div>';\n endforeach;\nendif;\n</code></pre>\n"
}
] |
2017/01/09
|
[
"https://wordpress.stackexchange.com/questions/251866",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109355/"
] |
I'm building a custom carousel for a client. I've got a function which gets blocks of three images from all of the images attached to a post:
```
global $rental;
$images = get_children( array(
'post_parent' => $rental_id,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID'
) );
$array = $images;
$number_of_elements = 3;
$count = count( $array );
$split = array();
for ( $i = 0; $i <= $count - 1; $i++ ) {
$slices = array_slice( $array, $i , $number_of_elements);
if ( count( $slices ) != $number_of_elements )
break;
$split[] = $slices;
}
if ($split) :
foreach ($split as $outeritem) :
echo '<div class="Outer Top">';
foreach ($split as $inneritem) :
echo '<div class="Inner Top">';
echo '<img src="' . $inneritem . '">';
echo '</div>';
endforeach;
echo '</div>';
endforeach;
endif;
//print_r( $split );
```
All I need to finalize this is to replace `inneritem` with the URL of the image. The data is all there in an array, and as you can see I just need to pull the value of *guid* for each item. The array below comes from uncommenting the `print_r( $split );` and I've removed all the extraneous data for the sake of tidiness:
```
Array (
[0] => Array (
[0] => WP_Post Object (
[ID] => 120
[guid] => http://******/wp-content/uploads/2016/12/T15923-11-1-1.jpg
)
[1] => WP_Post Object (
[ID] => 121
[guid] => http://******/wp-content/uploads/2016/12/T15923-12-1-1.jpg
)
[2] => WP_Post Object (
[ID] => 122
[guid] => http://******/wp-content/uploads/2016/12/T15898.jpg
)
)
[1] => Array (
[0] => WP_Post Object (
[ID] => 121
[guid] => http://******/wp-content/uploads/2016/12/T15923-12-1-1.jpg
)
[1] => WP_Post Object (
[ID] => 122
[guid] => http://******/wp-content/uploads/2016/12/T15898.jpg
)
[2] => WP_Post Object (
[ID] => 123
[guid] => http://******/wp-content/uploads/2016/12/T15923-13-1-1.jpg
)
)
[2] => Array (
[0] => WP_Post Object (
[ID] => 122
[guid] => http://******/wp-content/uploads/2016/12/T15898.jpg
)
[1] => WP_Post Object (
[ID] => 123
[guid] => http://******/wp-content/uploads/2016/12/T15923-13-1-1.jpg
)
[2] => WP_Post Object (
[ID] => 124
[guid] => http://******/wp-content/uploads/2016/12/T15923-14-1.jpg
)
)
)
```
|
You should be able to rewrite what you have about and also use [**`get_permalink`**](https://developer.wordpress.org/reference/functions/get_permalink/) as [@Benoti](https://wordpress.stackexchange.com/users/58141/benoti) stated while omitting the `$split` array.
>
> [**`get_permalink`**](https://developer.wordpress.org/reference/functions/get_permalink/) accepts either the Post ID or a post object.
>
>
>
```
global $rental;
$images = get_children( array(
'post_parent' => $rental_id,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID'
) );
$array = $images;
$number_of_elements = 3;
$count = count( $array );
for ( $i = 0; $i <= $count - 1; $i++ ) {
$slices = array_slice( $array, $i , $number_of_elements);
if ( count( $slices ) != $number_of_elements )
break;
echo "<div class='Outer Top'>";
foreach( $slices as $inneritem ) {
$link = wp_get_attachment_url( $inneritem->ID );
echo "<div class='Inner Top'>";
echo "<img src=' $link '>";
echo "</div>";
}
echo "</div>";
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.